From 229ceab8a3bd88313eff5e2979a0bc6bd681d86f Mon Sep 17 00:00:00 2001 From: Jonathan Wang <31040440+jonathanpwang@users.noreply.github.com> Date: Mon, 4 Dec 2023 13:02:33 -0500 Subject: [PATCH] Release 0.1.6 (#47) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Rollback to pse halo2 and halo2wrong for first release (#5) * feat: move `Accumulator` to `accumulator.rs` * feat: update due to halo2 * feat: upgrade to use branch `feature/generic-instructions` of `halo2wrong` * refactor: rollback to `{halo2,halo2_wrong}` without challenge API and cleanup dependencies * chore: rename statement to instance and auxliary to witness * chore: use `finalize` instead of `code` * feat: add `Code::deployment` and `EvmLoader::deployment_code`; add example `evm-verifier-codegen` * fix: typo * feat: reduce generated evm verifier size; rename to `evm-verifier` and add another example `evm-verifier-with-accumulator` * fix: due to `halo2wrong` * feat: reorganize mods and traits * fix: allow empty `values` in `sum_*` and move them under `ScalarLoader` * ci: use `--all-features` for `cargo test` * fix: use same strategy for aggregation testing * fix: simplify trait `PlonkVerifier` again * fix: move system specified transcript under mod `system` * feat: add `quotient_poly` info in `Protocol` * feat: implement linearization for circom integration * feat: re-export loader's dependency for consumer * refactor: for circom's integration * tmp: pin `revm` to rev * fix: remove parentheses * fix: upgrade for multi-phase halo2 * feat: improve error reporting * chore: rename crate to snake case * feat: add `Domain` as an input of `PolynomialCommitmentScheme::read_proof` * refactor: for further integration * feat: generalize to suppoer also ipa and add builder fns to `system::halo2::Config` * feat: add `KzgDecider` for simple evm verifier * refactor: split `AccumulationScheme` and `AccumulatorEncoding` * refactor: split `PolynomialCommitmentScheme` and `MultiOpenScheme` * fix: not need sealed actually * fix: `chunk_size` should be `LIMBS` when recovering accumulator * feat: add `Expression::DistributePowers` to avoid stack overflow * fix: update and pin foundry * fix: move testing circuits under `system/halo2` * fix: allow accumulate single accumulator * feat: remove all patch and make less depending `halo2wrong` * Generalized `Halo2Loader` (#12) * feat: generalize `Protocol` for further usage * feat: add `EccInstruction::{fixed_base_msm,variable_base_msm,sum_with_const}` * chore: move `rand_chacha` as dev dependency * General refactor for further integration (#13) * feat: remove dev-dependency `foundry` and vendor necessary part of it * refactor: simplify traits and remove unused stuff * refactor: much less clone * feat: generalized `AccumulatorEncoding` for `EccInstructions` * feat: implement ipa pcs and accumulation (#14) * ci: add `svm-rs` and install `solc@0.8.17` in job `test` (#16) * Update `EvmLoader` to generate Yul code instead of bytecode (#15) * Update `EvmLoader` to generate Yul instead of bytecode * feat: simplify * feat: Add missing end_gas_metering impl Co-authored-by: Han Co-authored-by: Han * fix: pin all `revm` dependencies (#18) * fix: looser trait bound on impl `CostEstimation` for `Plonk` (#20) * Restructure for more kind of verifier (#21) * feat: restructure to monorepo and expand the project scope to be generic (s)nark verifier * feat: reorganize mods and traits for further new features * refactor: simplify trait bounds * chore: use hyphen case for crate name (`snark_verifier` -> `snark-verifier`) * docs: add `#![deny(missing_docs)]` and simple documents * refactor: remove redudant check `validate_ec_point` (still doesn not support identity) * feat: expand more things and fix typos Co-authored-by: Chih Cheng Liang Co-authored-by: Carlos Pérez <37264926+CPerezz@users.noreply.github.com> * fix: rustdoc warnings * chore: update dependencies (#24) * chore: update `halo2` and `halo2wrong` version (#25) * fix: enable `util::hash::poseidon` only when `feature = loader_halo2` (#27) * feat: working update to halo2-lib v0.3.0 * feat: update zkevm bench * feat: update recursion example * feat: switch poseidon native implementation to Scroll's audited version * fix: invert determinant only once in Cramer's rule * chore: fix doc * chore * chore: forgot to update halo2-base dependency in snark-verifier-sdk * Minor update (#8) * feat(sdk): remove duplicate code in `RangeWithInstanceCircuitBuilder::synthesize` * feat(sdk): Proof caching when using feature 'halo2-pse' * chore: sync with halo2-lib * chore: switch to halo2-lib release-0.3.0 branch * Moved `RangeWithInstanceCircuitBuilder` to halo2-lib (#9) * chore: sync with halo2-lib * fix: clippy * chore: fix halo2-base branch in sdk * feat: update to halo2-lib new types (#10) * feat: add `assert` for non-empty accumulators in `decide_all` (#11) * feat: use `zip_eq` for `Polynomial` add/sub (#12) * fix: git CI turn off all features * fix: `rotate_scalar` misbehaves on `i32::MIN` (#13) Should never actually be callable with such a large negative rotation * fix: cleanup code quality (#14) * fix: `split_by_ascii_whitespace` (#15) * fix: `batch_invert_and_mul` do not allow zeros (#16) * feat: verify proof in release mode (#17) Verify proof before caching it as extra safety * fix: add better error messages/docs for catching empty inputs (#18) * chore: add Cargo.lock * chore: update Cargo dependencies * chore: update dependencies * Minor: merge v0.1.1 to develop (#21) Just cargo fixes * feat: remove use of env vars for circuit configuration (#22) * feat: remove use of env vars for circuit configuration This is a companion to https://github.com/axiom-crypto/halo2-lib/pull/92 * chore: remove rustfmt CI check PSE upstream uses different rustfmt configuration than us, so some files disagree in formatting * chore: fix dependencies * Feat/read pk buffer capacity (#24) * feat: change default `read_pk` buffer capacity to 1MB * feat: add bench for read_pk * [Update] use ff v0.13 (#28) * feat(snark-verifier): update to ff v0.13 * feat(snark-verifier): update examples * feat(snark-verifier-sdk): update to ff v0.13 * fix: conversion from BaseConfigParams to AggregationConfigParams * chore: pin poseidon rev * refactor(sdk): add `AggregationCtxBuilder` for aggregation Contains the populated builder after aggregating, without creating the `AggregationCircuit`. Doesn't need config parameters and break points. * chore: update cargo * [Feat] Universal verifier circuit (#26) * feat: add example with different vkey as private witness Same aggregation circuit, verifies different snarks with different vkeys (same standard plonk gate, but different selectors / copy constraints) * fix: save break points when generating agg circuit for first time (#23) * fix: save break points when generating agg circuit for first time * chore: add circuit files to gitignore * feat: halo2-lib universal verifier example * chore: cargo fix * feat: allow circuit size (number of rows) to be loaded as witness * chore: clippy fix * fix(n_as_witness): computation of shifts depends on `omega` `omega` which changes when `k` changes, so all shift computations need to be done as witness. Current implementation is likely not the most optimal. Instead of storing `shift` as `omega^i`, we store just `Rotation(i)`. We de-duplicate when possible using `BTreeMap` of `Rotation`. Note you must use `Rotation` instead of `F` for `BTreeMap` because the ordering of `omega^i` may change depending on `omega`. * fix: temp remove pow_var * add universal verifier range check test * chore: do not serialize domain_as_witness if none * Revert "fix: temp remove pow_var" This reverts commit 69f648e12a850a1d16235fc33acebfb5f8b2f290. * fix: halo2_lib example * test: halo2_lib with variable lookup table passes * Bump version to 0.1.3 --------- Co-authored-by: Roshan * chore: derive Default for VerifierUniversality * feat: upgrade `revm` to support lastest hardfork (#40) * Update: use `halo2-lib` v0.4.0 (#29) * feat: update snark-verifier * update: use `halo2-lib` v0.4.0 * feat: load `k` as witness and compute `n = 2^k` and `omega` from `k` (#30) * feat: load `k` as witness and compute `n = 2^k` and `omega` from `k` Removes need to make `omega` a public output in universal verifier. * fix: bit_length * Move `OptimizedPoseidonSpec` to `halo2-base` (#31) * chore: move `OptimizedPoseidonSpec` to `halo2-base` * Bump version to 0.1.5 and remove poseidon-rs dep * chore: util::hash available without loader_halo2 feature * chore: nit * [feat] change yul code into Solidity assembly (#32) feat: change yul code into Solidity assembly Just changes to wrapping yul in solidity assembly block * chore: change halo2-lib branch * chore: `snark-verifier` re-exports `halo2-base`, `halo2-ecc` (#38) and `snark-verifier-sdk` re-exports `snark-verifier`. This is to minimize cargo dependency / version issues until we publish to crates.io. * [feat] make assembly block Solidity memory safe (#39) * feat: make assembly block Solidity memory safe * chore: add back example solidity code * chore: switch CI to solidity v0.8.19 * [chore] add `cargo audit` and update dependencies (#40) * chore: add `cargo audit` and update dependencies disabling zkevm benches due to versioning issues * chore: autobenches false * fix: audit-check CI * [chore] fix hyperlinks in docs (#41) chore: fix hyperlinks in docs * [chore] separate `revm` import into separate feature (#44) * chore: import `ruint` separately to not rely on `revm` * feat: add feature `revm` to toggle `revm` import Separates `revm` import, which is only used for testing EVM execution, from `loader_evm` feature, which is used more broadly for generating proofs to be sent to on-chain verifier. * chore: add CI to check `--release` compilation with assembly * fix: import under revm * fix: compute `system_challenge_offset` correctly (#53) * chore: turn off halo2-pse for crates.io * chore: add package descriptions * chore: update description * chore: add snark-verifier version --------- Co-authored-by: Han Co-authored-by: DoHoon Kim <59155248+DoHoonKim8@users.noreply.github.com> Co-authored-by: Chih Cheng Liang Co-authored-by: Carlos Pérez <37264926+CPerezz@users.noreply.github.com> Co-authored-by: dante <45801863+alexander-camuto@users.noreply.github.com> Co-authored-by: Jonathan Wang Co-authored-by: Roshan --- .github/workflows/ci.yaml | 18 +- .github/workflows/release.yaml | 36 + .gitignore | 4 + Cargo.lock | 3217 +++++++++++++++++ Cargo.toml | 1 + rust-toolchain | 2 +- snark-verifier-sdk/Cargo.toml | 77 +- snark-verifier-sdk/benches/read_pk.rs | 223 ++ snark-verifier-sdk/benches/standard_plonk.rs | 54 +- .../examples/StandardPlonkVerifier.sol | 1443 ++++++++ snark-verifier-sdk/examples/k_as_witness.rs | 187 + snark-verifier-sdk/examples/range_check.rs | 76 + snark-verifier-sdk/examples/standard_plonk.rs | 219 ++ .../examples/vkey_as_witness.rs | 183 + snark-verifier-sdk/src/evm.rs | 24 +- snark-verifier-sdk/src/halo2.rs | 36 +- snark-verifier-sdk/src/halo2/aggregation.rs | 361 +- snark-verifier-sdk/src/lib.rs | 27 +- snark-verifier/Cargo.toml | 42 +- .../examples/evm-verifier-with-accumulator.rs | 238 +- snark-verifier/examples/evm-verifier.rs | 28 +- snark-verifier/examples/recursion.rs | 223 +- snark-verifier/src/lib.rs | 4 + snark-verifier/src/loader.rs | 30 +- snark-verifier/src/loader/evm.rs | 12 +- snark-verifier/src/loader/evm/code.rs | 74 +- snark-verifier/src/loader/evm/loader.rs | 83 +- snark-verifier/src/loader/evm/test.rs | 48 - snark-verifier/src/loader/evm/test/tui.rs | 943 ----- snark-verifier/src/loader/evm/util.rs | 20 +- .../src/loader/evm/util/executor.rs | 912 +---- snark-verifier/src/loader/halo2.rs | 2 +- snark-verifier/src/loader/halo2/loader.rs | 28 +- snark-verifier/src/loader/halo2/shim.rs | 87 +- snark-verifier/src/loader/native.rs | 7 +- snark-verifier/src/pcs.rs | 24 +- snark-verifier/src/pcs/ipa.rs | 2 +- snark-verifier/src/pcs/ipa/accumulation.rs | 4 +- snark-verifier/src/pcs/ipa/decider.rs | 2 +- snark-verifier/src/pcs/ipa/multiopen/bgh19.rs | 96 +- snark-verifier/src/pcs/kzg.rs | 2 +- snark-verifier/src/pcs/kzg/accumulation.rs | 4 +- snark-verifier/src/pcs/kzg/accumulator.rs | 13 +- snark-verifier/src/pcs/kzg/decider.rs | 27 +- .../src/pcs/kzg/multiopen/bdfg21.rs | 193 +- snark-verifier/src/pcs/kzg/multiopen/gwc19.rs | 54 +- snark-verifier/src/system/halo2.rs | 24 +- snark-verifier/src/system/halo2/transcript.rs | 23 +- .../src/system/halo2/transcript/evm.rs | 11 +- .../src/system/halo2/transcript/halo2.rs | 20 +- snark-verifier/src/util/arithmetic.rs | 31 +- snark-verifier/src/util/hash.rs | 4 +- snark-verifier/src/util/hash/poseidon.rs | 369 +- .../src/util/hash/poseidon/tests.rs | 6 +- snark-verifier/src/util/msm.rs | 2 +- snark-verifier/src/util/poly.rs | 22 +- snark-verifier/src/verifier/plonk.rs | 17 +- snark-verifier/src/verifier/plonk/proof.rs | 43 +- snark-verifier/src/verifier/plonk/protocol.rs | 106 +- 59 files changed, 6867 insertions(+), 3201 deletions(-) create mode 100644 .github/workflows/release.yaml create mode 100644 Cargo.lock create mode 100644 snark-verifier-sdk/benches/read_pk.rs create mode 100644 snark-verifier-sdk/examples/StandardPlonkVerifier.sol create mode 100644 snark-verifier-sdk/examples/k_as_witness.rs create mode 100644 snark-verifier-sdk/examples/range_check.rs create mode 100644 snark-verifier-sdk/examples/standard_plonk.rs create mode 100644 snark-verifier-sdk/examples/vkey_as_witness.rs delete mode 100644 snark-verifier/src/loader/evm/test.rs delete mode 100644 snark-verifier/src/loader/evm/test/tui.rs diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 634eed77..d8c87a8d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -24,11 +24,14 @@ jobs: cache-on-failure: true - name: Install solc - run: (hash svm 2>/dev/null || cargo install svm-rs) && svm install 0.8.17 && solc --version + run: (hash svm 2>/dev/null || cargo install --version 0.2.23 svm-rs) && svm install 0.8.19 && solc --version - name: Run test - run: cargo test --all -- --nocapture + run: cargo test --all --features "revm" -- --nocapture + - name: Run example + working-directory: "snark-verifier-sdk" + run: cargo run --example standard_plonk --features "revm" lint: name: Lint @@ -47,8 +50,13 @@ jobs: with: cache-on-failure: true - - name: Run fmt - run: cargo fmt --all -- --check - - name: Run clippy run: cargo clippy --all --all-targets -- -D warnings + + - name: Generate Cargo.lock + run: cargo generate-lockfile + + - name: Run cargo audit + uses: actions-rs/audit-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 00000000..1c89b2e3 --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,36 @@ +name: CI + +on: + pull_request: + branches: + - ["main", "release-*"] + push: + branches: + - main + +jobs: + test: + name: Test assembly release + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Install toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + override: false + + - uses: Swatinem/rust-cache@v1 + with: + cache-on-failure: true + + - name: Install solc + run: (hash svm 2>/dev/null || cargo install --version 0.2.23 svm-rs) && svm install 0.8.19 && solc --version + + - name: Run test + run: cargo test --all --features "revm, halo2-base/asm" -- --nocapture + + - name: Run example + working-directory: "snark-verifier-sdk" + run: cargo run --example standard_plonk --features "revm, halo2-base/asm" diff --git a/.gitignore b/.gitignore index 829691c6..8d7c1190 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ /target testdata +# Cargo.lock +params +agg.pk +break_points.json diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..0ddec621 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3217 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "ahash" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91429305e9f0a25f6205c5b8e0d2db09e0708a7a6df0f42212bb56c32c8ac97a" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" + +[[package]] +name = "alloy-primitives" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0628ec0ba5b98b3370bb6be17b12f23bfce8ee4ad83823325a20546d9b03b78" +dependencies = [ + "alloy-rlp", + "bytes", + "cfg-if", + "const-hex", + "derive_more", + "hex-literal", + "itoa", + "ruint", + "tiny-keccak", +] + +[[package]] +name = "alloy-rlp" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc0fac0fc16baf1f63f78b47c3d24718f3619b0714076f6a02957d808d52cbef" +dependencies = [ + "alloy-rlp-derive", + "arrayvec", + "bytes", + "smol_str", +] + +[[package]] +name = "alloy-rlp-derive" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0391754c09fab4eae3404d19d0d297aa1c670c1775ab51d8a5312afeca23157" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" + +[[package]] +name = "ark-ff" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b3235cc41ee7a12aaaf2c575a2ad7b46713a8a50bda2fc3b003a04845c05dd6" +dependencies = [ + "ark-ff-asm 0.3.0", + "ark-ff-macros 0.3.0", + "ark-serialize 0.3.0", + "ark-std 0.3.0", + "derivative", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.3.3", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" +dependencies = [ + "ark-ff-asm 0.4.2", + "ark-ff-macros 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "derivative", + "digest 0.10.7", + "itertools 0.10.5", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.4.0", + "zeroize", +] + +[[package]] +name = "ark-ff-asm" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-asm" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" +dependencies = [ + "num-bigint", + "num-traits", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-serialize" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d6c2b318ee6e10f8c2853e73a83adc0ccb88995aa978d8a3408d492ab2ee671" +dependencies = [ + "ark-std 0.3.0", + "digest 0.9.0", +] + +[[package]] +name = "ark-serialize" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" +dependencies = [ + "ark-std 0.4.0", + "digest 0.10.7", + "num-bigint", +] + +[[package]] +name = "ark-std" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1df2c09229cbc5a028b1d70e00fdb2acee28b1055dfb5ca73eea49c5a25c4e7c" +dependencies = [ + "colored", + "num-traits", + "rand", +] + +[[package]] +name = "ark-std" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "arrayref" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" + +[[package]] +name = "arrayvec" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" + +[[package]] +name = "auto_impl" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fee3da8ef1276b0bee5dd1c7258010d8fffd31801447323115a25560e1327b89" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "base64ct" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bindgen" +version = "0.66.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7" +dependencies = [ + "bitflags 2.4.1", + "cexpr", + "clang-sys", + "lazy_static", + "lazycell", + "log", + "peeking_take_while", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn 2.0.38", + "which", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" + +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "blake2b_simd" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23285ad32269793932e830392f2fe2f83e26488fd3ec778883a93c8323735780" +dependencies = [ + "arrayref", + "arrayvec", + "constant_time_eq", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blst" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c94087b935a822949d3291a9989ad2b2051ea141eda0fd4e478a75f6aa3e604b" +dependencies = [ + "cc", + "glob", + "threadpool", + "zeroize", +] + +[[package]] +name = "bumpalo" +version = "3.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" + +[[package]] +name = "byte-slice-cast" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" + +[[package]] +name = "bytemuck" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374d28ec25809ee0e23827c2ab573d729e293f281dfe393500e7ad618baa61c6" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" + +[[package]] +name = "c-kzg" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac926d808fb72fe09ebf471a091d6d72918876ccf0b4989766093d2d0d24a0ef" +dependencies = [ + "bindgen", + "blst", + "cc", + "glob", + "hex", + "libc", + "serde", +] + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + +[[package]] +name = "cc" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" +dependencies = [ + "libc", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "num-traits", + "serde", + "windows-targets", +] + +[[package]] +name = "ciborium" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "effd91f6c78e5a4ace8a5d3c0b6bfaec9e2baaef55f3efc00e45fb2e477ee926" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdf919175532b369853f5d5e20b26b43112613fd6fe7aee757e35f7a44642656" + +[[package]] +name = "ciborium-ll" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "defaa24ecc093c77630e6c15e17c51f5e187bf35ee514f4e2d67baaa96dae22b" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "clang-sys" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac495e00dcec98c83465d5ad66c5c4fabd652fd6686e7c6269b117e729a6f17b" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77ed9a32a62e6ca27175d00d29d05ca32e396ea1eb5fb01d8256b669cec7663" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" + +[[package]] +name = "colored" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2674ec482fbc38012cf31e6c42ba0177b431a0cb6f15fe40efa5aab1bda516f6" +dependencies = [ + "is-terminal", + "lazy_static", + "windows-sys", +] + +[[package]] +name = "const-hex" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5104de16b218eddf8e34ffe2f86f74bfa4e61e95a1b89732fccf6325efd0557" +dependencies = [ + "cfg-if", + "cpufeatures", + "hex", + "proptest", + "serde", +] + +[[package]] +name = "const-oid" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" + +[[package]] +name = "constant_time_eq" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7144d30dcf0fafbce74250a3963025d8d52177934239851c917d29f1df280c2" + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "core-foundation-sys" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" + +[[package]] +name = "cpp_demangle" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e8227005286ec39567949b33df9896bcadfa6051bccca2488129f108ca23119" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cpufeatures" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0" +dependencies = [ + "libc", +] + +[[package]] +name = "criterion" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "is-terminal", + "itertools 0.10.5", + "num-traits", + "once_cell", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-macro" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "288a8f36b28a19d7dbd572c76006c0a0eba1f3bf912a254dda211c6f665e7ffc" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "criterion-plot" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +dependencies = [ + "cast", + "itertools 0.10.5", +] + +[[package]] +name = "crossbeam" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2801af0d36612ae591caa9568261fddce32ce6e08a7275ea334a06a4ad021a2c" +dependencies = [ + "cfg-if", + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "memoffset", + "scopeguard", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossterm" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67" +dependencies = [ + "bitflags 1.3.2", + "crossterm_winapi", + "libc", + "mio", + "parking_lot", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" +dependencies = [ + "bitflags 2.4.1", + "crossterm_winapi", + "libc", + "mio", + "parking_lot", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" + +[[package]] +name = "crypto-bigint" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "740fe28e594155f10cfc383984cbefd529d7396050557148f79cb0f621204124" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.38", +] + +[[package]] +name = "darling_macro" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "uuid", +] + +[[package]] +name = "der" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f32d04922c60427da6f9fef14d042d9edddef64cb9d4ce0d64d0685fbeb1fd3" +dependencies = [ + "powerfmt", + "serde", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_more" +version = "0.99.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version 0.4.0", + "syn 1.0.109", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "ecdsa" +version = "0.16.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4b1e0c257a9e9f25f90ff76d7a68360ed497ee519c8e428d1825ef0000799d4" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "either" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" + +[[package]] +name = "elliptic-curve" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d97ca172ae9dc9f9b779a6e3a65d308f2af74e5b8c921299075bdb4a0370e914" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "pkcs8", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "enumn" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2ad8cef1d801a4686bfd8919f0b30eac4c8e48968c437a6405ded4fb5272d2b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3e13f66a2f95e32a39eaa81f6b95d42878ca0e1db0c7543723dfe12557e860" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "ethbloom" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c22d4b5885b6aa2fe5e8b9329fb8d232bf739e434e6b87347c63bdd00c120f60" +dependencies = [ + "crunchy", + "fixed-hash", + "tiny-keccak", +] + +[[package]] +name = "ethereum-types" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d215cbf040552efcbe99a38372fe80ab9d00268e20012b79fcd0f073edd8ee" +dependencies = [ + "ethbloom", + "fixed-hash", + "primitive-types", + "uint", +] + +[[package]] +name = "fastrand" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" + +[[package]] +name = "fastrlp" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139834ddba373bbdd213dffe02c8d110508dcf1726c2be27e8d1f7d7e1856418" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", +] + +[[package]] +name = "ff" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" +dependencies = [ + "bitvec", + "rand_core", + "subtle", +] + +[[package]] +name = "findshlibs" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40b9e59cd0f7e0806cca4be089683ecb6434e602038df21fe6bf6711b2f07f64" +dependencies = [ + "cc", + "lazy_static", + "libc", + "winapi", +] + +[[package]] +name = "fixed-hash" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" +dependencies = [ + "byteorder", + "rand", + "rustc-hex", + "static_assertions", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getset" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e45727250e75cc04ff2846a66397da8ef2b3db8e40e0cef4df67950a07621eb9" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "gimli" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "half" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" + +[[package]] +name = "halo2-axiom" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa28f319d49a0c23297d7c6792528dc31a7f2fc7d6b13a8d54836bf2a2c08c5" +dependencies = [ + "blake2b_simd", + "crossbeam", + "ff", + "group", + "halo2curves-axiom", + "maybe-rayon", + "pairing", + "rand", + "rand_core", + "rustc-hash", + "sha3", + "tracing", +] + +[[package]] +name = "halo2-base" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eeb378fa79d4904b626da0c08dcafd974e8194928c73cdccdcdd00796441a8" +dependencies = [ + "getset", + "halo2-axiom", + "itertools 0.11.0", + "jemallocator", + "log", + "num-bigint", + "num-integer", + "num-traits", + "poseidon-primitives", + "rand_chacha", + "rayon", + "rustc-hash", + "serde", + "serde_json", +] + +[[package]] +name = "halo2-ecc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cfe18bc332c7b2b50100442ed0dd24dea87d1ca16a4eb8912d0875960b0176" +dependencies = [ + "halo2-base", + "itertools 0.10.5", + "num-bigint", + "num-integer", + "num-traits", + "rand", + "rand_chacha", + "rand_core", + "rayon", + "serde", + "serde_json", + "test-case", +] + +[[package]] +name = "halo2curves-axiom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d47eaec6a3040c2fbaa020716bf571b0c55025126242510f774183aff84b92e" +dependencies = [ + "blake2b_simd", + "ff", + "group", + "hex", + "lazy_static", + "maybe-rayon", + "num-bigint", + "num-traits", + "pairing", + "pasta_curves", + "paste", + "rand", + "rand_core", + "serde", + "serde_arrays", + "static_assertions", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" +dependencies = [ + "ahash", + "allocator-api2", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "hermit-abi" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +dependencies = [ + "serde", +] + +[[package]] +name = "hex-literal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "home" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8326b86b6cff230b97d0d312a6c40a60726df3332e721f72a1b035f451663b20" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "impl-codec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" +dependencies = [ + "parity-scale-codec", +] + +[[package]] +name = "impl-trait-for-tuples" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d7a9f6330b71fea57921c9b61c47ee6e84f72d394754eff6163ae67e7395eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" +dependencies = [ + "equivalent", + "hashbrown 0.14.2", +] + +[[package]] +name = "indoc" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8" + +[[package]] +name = "inferno" +version = "0.11.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c50453ec3a6555fad17b1cd1a80d16af5bc7cb35094f64e429fd46549018c6a3" +dependencies = [ + "ahash", + "indexmap 2.1.0", + "is-terminal", + "itoa", + "log", + "num-format", + "once_cell", + "quick-xml", + "rgb", + "str_stack", +] + +[[package]] +name = "is-terminal" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +dependencies = [ + "hermit-abi", + "rustix", + "windows-sys", +] + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" + +[[package]] +name = "jemalloc-sys" +version = "0.5.4+5.3.0-patched" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6c1946e1cea1788cbfde01c993b52a10e2da07f4bac608228d1bed20bfebf2" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "jemallocator" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0de374a9f8e63150e6f5e8a60cc14c668226d7a347d8aee1a45766e3c4dd3bc" +dependencies = [ + "jemalloc-sys", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54c0c35952f67de54bb584e9fd912b3023117cbafc0a77d8f3dee1fb5f572fe8" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "k256" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cadb76004ed8e97623117f3df85b17aaa6626ab0b0831e6573f104df16cd1bcc" +dependencies = [ + "cfg-if", + "ecdsa", + "elliptic-curve", + "once_cell", + "sha2", +] + +[[package]] +name = "keccak" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6d5ed8676d904364de097082f4e7d240b571b67989ced0240f08b7f966f940" +dependencies = [ + "cpufeatures", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +dependencies = [ + "spin", +] + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "libc" +version = "0.2.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libm" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" + +[[package]] +name = "linux-raw-sys" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" + +[[package]] +name = "lock_api" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" + +[[package]] +name = "lru" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efa59af2ddfad1854ae27d75009d538d0998b4b2fd47083e743ac1a10e46c60" +dependencies = [ + "hashbrown 0.14.2", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" + +[[package]] +name = "memmap2" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a5a03cefb0d953ec0be133036f14e109412fa594edc2f77227249db66cc3ed" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys", +] + +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05180d69e3da0e530ba2a1dae5110317e49e3b7f3d41be227dc5f92e49ee7af" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", + "rand", +] + +[[package]] +name = "num-complex" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ba157ca0885411de85d6ca030ba7e2a83a28636056c7c699b07c8b6f7383214" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-format" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3" +dependencies = [ + "arrayvec", + "itoa", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" +dependencies = [ + "autocfg", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" + +[[package]] +name = "oorandom" +version = "11.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" + +[[package]] +name = "pairing" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" +dependencies = [ + "group", +] + +[[package]] +name = "parity-scale-codec" +version = "3.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dec8a8073036902368c2cdc0387e85ff9a37054d7e7c98e592145e0c92cd4fb" +dependencies = [ + "arrayvec", + "bitvec", + "byte-slice-cast", + "impl-trait-for-tuples", + "parity-scale-codec-derive", + "serde", +] + +[[package]] +name = "parity-scale-codec-derive" +version = "3.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312270ee71e1cd70289dacf597cab7b207aa107d2f28191c2ae45b2ece18a260" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets", +] + +[[package]] +name = "pasta_curves" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e57598f73cc7e1b2ac63c79c517b31a0877cd7c402cdcaa311b5208de7a095" +dependencies = [ + "blake2b_simd", + "ff", + "group", + "lazy_static", + "rand", + "static_assertions", + "subtle", +] + +[[package]] +name = "paste" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" + +[[package]] +name = "peeking_take_while" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" + +[[package]] +name = "pest" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" +dependencies = [ + "memchr", + "thiserror", + "ucd-trie", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "plotters" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609" + +[[package]] +name = "plotters-svg" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab" +dependencies = [ + "plotters-backend", +] + +[[package]] +name = "poseidon-primitives" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bd95570f7ea849b4187298b5bb229643e44e1d47ddf3979d0db8a1c28be26a8" +dependencies = [ + "bitvec", + "ff", + "lazy_static", + "log", + "rand", + "rand_xorshift", + "thiserror", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "pprof" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef5c97c51bd34c7e742402e216abdeb44d415fbe6ae41d56b114723e953711cb" +dependencies = [ + "backtrace", + "cfg-if", + "criterion", + "findshlibs", + "inferno", + "libc", + "log", + "nix", + "once_cell", + "parking_lot", + "smallvec", + "symbolic-demangle", + "tempfile", + "thiserror", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "prettyplease" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae005bd773ab59b4725093fd7df83fd7892f7d8eafb48dbd7de6e024e4215f9d" +dependencies = [ + "proc-macro2", + "syn 2.0.38", +] + +[[package]] +name = "primitive-types" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b34d9fd68ae0b74a41b21c03c2f62847aa0ffea044eee893b4c140b37e244e2" +dependencies = [ + "fixed-hash", + "impl-codec", + "uint", +] + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c003ac8c77cb07bb74f5f198bce836a689bcd5a42574612bf14d17bfd08c20e" +dependencies = [ + "bitflags 2.4.1", + "lazy_static", + "num-traits", + "rand", + "rand_chacha", + "rand_xorshift", + "regex-syntax 0.7.5", + "unarray", +] + +[[package]] +name = "quick-xml" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f50b1c63b38611e7d4d7f68b82d3ad0cc71a2ad2e7f61fc10f1328d917c93cd" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_xorshift" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" +dependencies = [ + "rand_core", +] + +[[package]] +name = "ratatui" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ebc917cfb527a566c37ecb94c7e3fd098353516fb4eb6bea17015ade0182425" +dependencies = [ + "bitflags 2.4.1", + "cassowary", + "crossterm 0.27.0", + "indoc", + "itertools 0.11.0", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "rayon" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "regex" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax 0.8.2", +] + +[[package]] +name = "regex-automata" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax 0.8.2", +] + +[[package]] +name = "regex-syntax" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" + +[[package]] +name = "regex-syntax" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" + +[[package]] +name = "revm" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f4ca8ae0345104523b4af1a8a7ea97cfa1865cdb7a7c25d23c1a18d9b48598" +dependencies = [ + "auto_impl", + "revm-interpreter", + "revm-precompile", +] + +[[package]] +name = "revm-interpreter" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f959cafdf64a7f89b014fa73dc2325001cf654b3d9400260b212d19a2ebe3da0" +dependencies = [ + "revm-primitives", +] + +[[package]] +name = "revm-precompile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d360a88223d85709d2e95d4609eb1e19c649c47e28954bfabae5e92bb37e83e" +dependencies = [ + "c-kzg", + "k256", + "num", + "once_cell", + "revm-primitives", + "ripemd", + "secp256k1", + "sha2", + "substrate-bn", +] + +[[package]] +name = "revm-primitives" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51187b852d9e458816a2e19c81f1dd6c924077e1a8fccd16e4f044f865f299d7" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "auto_impl", + "bitflags 2.4.1", + "bitvec", + "c-kzg", + "enumn", + "hashbrown 0.14.2", + "hex", + "once_cell", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rgb" +version = "0.8.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05aaa8004b64fd573fc9d002f4e632d51ad4f026c2b5ba95fcb6c2f32c2c47d8" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "ripemd" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "rlp" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb919243f34364b6bd2fc10ef797edbfa75f33c252e7998527479c6d6b47e1ec" +dependencies = [ + "bytes", + "rustc-hex", +] + +[[package]] +name = "ruint" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95294d6e3a6192f3aabf91c38f56505a625aa495533442744185a36d75a790c4" +dependencies = [ + "alloy-rlp", + "ark-ff 0.3.0", + "ark-ff 0.4.2", + "bytes", + "fastrlp", + "num-bigint", + "parity-scale-codec", + "primitive-types", + "proptest", + "rand", + "rlp", + "ruint-macro", + "serde", + "valuable", + "zeroize", +] + +[[package]] +name = "ruint-macro" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e666a5496a0b2186dbcd0ff6106e29e093c15591bde62c20d3842007c6978a09" + +[[package]] +name = "rustc-demangle" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hex" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" + +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver 1.0.20", +] + +[[package]] +name = "rustix" +version = "0.38.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" +dependencies = [ + "bitflags 2.4.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" + +[[package]] +name = "ryu" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "secp256k1" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25996b82292a7a57ed3508f052cfff8640d38d32018784acd714758b43da9c8f" +dependencies = [ + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70a129b9e9efbfb223753b9163c4ab3b13cff7fd9c7f010fbac25ab4099fa07e" +dependencies = [ + "cc", +] + +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" + +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + +[[package]] +name = "serde" +version = "1.0.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91d3c334ca1ee894a2c6f6ad698fe8c435b76d504b13d436f0685d648d6d96f7" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_arrays" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38636132857f68ec3d5f3eb121166d2af33cb55174c4d5ff645db6165cbef0fd" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c5609f394e5c2bd7fc51efda478004ea80ef42fee983d5c67a65e34f32c0e3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "serde_json" +version = "1.0.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07ff71d2c147a7b57362cead5e22f772cd52f6ab31cfcd9edcd7f6aeb2a0afbe" +dependencies = [ + "base64", + "chrono", + "hex", + "indexmap 1.9.3", + "serde", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "881b6f881b17d13214e5d494c939ebab463d01264ce1811e9d4ac3a882e7695f" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.7", +] + +[[package]] +name = "sha3" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" +dependencies = [ + "digest 0.10.7", + "keccak", +] + +[[package]] +name = "shlex" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" + +[[package]] +name = "signal-hook" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +dependencies = [ + "libc", +] + +[[package]] +name = "signature" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500" +dependencies = [ + "digest 0.10.7", + "rand_core", +] + +[[package]] +name = "smallvec" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" + +[[package]] +name = "smol_str" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74212e6bbe9a4352329b2f68ba3130c15a3f26fe88ff22dbdc6cdd58fa85e99c" +dependencies = [ + "serde", +] + +[[package]] +name = "snark-verifier" +version = "0.1.6" +dependencies = [ + "ark-std 0.3.0", + "crossterm 0.25.0", + "halo2-base", + "halo2-ecc", + "hex", + "itertools 0.11.0", + "lazy_static", + "num-bigint", + "num-integer", + "num-traits", + "pairing", + "paste", + "rand", + "rand_chacha", + "ratatui", + "rayon", + "revm", + "ruint", + "serde", + "serde_json", + "sha3", +] + +[[package]] +name = "snark-verifier-sdk" +version = "0.1.6" +dependencies = [ + "ark-std 0.3.0", + "bincode", + "criterion", + "criterion-macro", + "crossterm 0.25.0", + "ethereum-types", + "getset", + "halo2-base", + "hex", + "itertools 0.11.0", + "lazy_static", + "num-bigint", + "num-integer", + "num-traits", + "paste", + "pprof", + "rand", + "rand_chacha", + "ratatui", + "serde", + "serde_json", + "serde_with", + "snark-verifier", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "spki" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1e996ef02c474957d681f1b05213dfb0abab947b446a62d37770b23500184a" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "str_stack" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9091b6114800a5f2141aee1d1b9d6ca3592ac062dc5decb3764ec5895a47b4eb" + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.38", +] + +[[package]] +name = "substrate-bn" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b5bbfa79abbae15dd642ea8176a21a635ff3c00059961d1ea27ad04e5b441c" +dependencies = [ + "byteorder", + "crunchy", + "lazy_static", + "rand", + "rustc-hex", +] + +[[package]] +name = "subtle" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" + +[[package]] +name = "symbolic-common" +version = "12.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d3aa424281de488c1ddbaffb55a421ad87d04b0fdd5106e7e71d748c0c71ea6" +dependencies = [ + "debugid", + "memmap2", + "stable_deref_trait", + "uuid", +] + +[[package]] +name = "symbolic-demangle" +version = "12.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bdcf77effe2908a21c1011b4d49a7122e0f44487a6ad89db67c55a1687e2572" +dependencies = [ + "cpp_demangle", + "rustc-demangle", + "symbolic-common", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +dependencies = [ + "cfg-if", + "fastrand", + "redox_syscall", + "rustix", + "windows-sys", +] + +[[package]] +name = "test-case" +version = "3.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8f1e820b7f1d95a0cdbf97a5df9de10e1be731983ab943e56703ac1b8e9d425" +dependencies = [ + "test-case-macros", +] + +[[package]] +name = "test-case-core" +version = "3.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54c25e2cb8f5fcd7318157634e8838aa6f7e4715c96637f969fabaccd1ef5462" +dependencies = [ + "cfg-if", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "test-case-macros" +version = "3.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37cfd7bbc88a0104e304229fba519bdc45501a30b760fb72240342f1289ad257" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.38", + "test-case-core", +] + +[[package]] +name = "thiserror" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + +[[package]] +name = "time" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a34ab300f2dee6e562c10a046fc05e358b29f9bf92277f30c3c8d82275f6f5" +dependencies = [ + "deranged", + "itoa", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20" +dependencies = [ + "time-core", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "toml_datetime" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.1.0", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "ucd-trie" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" + +[[package]] +name = "uint" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f64bba2c53b04fcab63c01a7d7427eadc821e3bc48c34dc9ba29c501164b52" +dependencies = [ + "byteorder", + "crunchy", + "hex", + "static_assertions", +] + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + +[[package]] +name = "unicode-width" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" + +[[package]] +name = "uuid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ad59a7560b41a70d191093a945f0b87bc1deeda46fb237479708a1d6b6cdfc" + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "walkdir" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.88" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7daec296f25a1bae309c0cd5c29c4b260e510e6d813c286b19eaadf409d40fce" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.88" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e397f4664c0e4e428e8313a469aaa58310d302159845980fd23b0f22a847f217" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.38", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.88" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5961017b3b08ad5f3fe39f1e79877f8ee7c23c5e5fd5eb80de95abc41f1f16b2" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.88" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5353b8dab669f5e10f5bd76df26a9360c748f054f862ff5f3f8aae0c7fb3907" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.88" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d046c5d029ba91a1ed14da14dca44b68bf2f124cfbaf741c54151fdb3e0750b" + +[[package]] +name = "web-sys" +version = "0.3.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db499c5f66323272151db0e666cd34f78617522fb0c1604d31a27c50c206a85" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.51.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "winnow" +version = "0.5.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829846f3e3db426d4cee4510841b71a8e58aa2a76b1132579487ae430ccd9c7b" +dependencies = [ + "memchr", +] + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "zerocopy" +version = "0.7.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092cd76b01a033a9965b9097da258689d9e17c69ded5dcf41bca001dd20ebc6d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13a20a7c6a90e2034bcc65495799da92efcec6a8dd4f3fcb6f7a48988637ead" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "zeroize" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] diff --git a/Cargo.toml b/Cargo.toml index 552212b3..53c98f1a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ members = [ "snark-verifier", "snark-verifier-sdk", ] +resolver = "2" [profile.dev] opt-level = 3 diff --git a/rust-toolchain b/rust-toolchain index 51ab4759..6f6d7b39 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1 +1 @@ -nightly-2022-10-28 \ No newline at end of file +nightly-2023-08-12 diff --git a/snark-verifier-sdk/Cargo.toml b/snark-verifier-sdk/Cargo.toml index 4901528b..2ba375af 100644 --- a/snark-verifier-sdk/Cargo.toml +++ b/snark-verifier-sdk/Cargo.toml @@ -1,10 +1,17 @@ [package] name = "snark-verifier-sdk" -version = "0.1.1" +version = "0.1.6" +authors = ["Privacy Scaling Explorations Team", "Intrinsic Technologies"] +license = "MIT" edition = "2021" +repository = "https://github.com/axiom-crypto/snark-verifier" +readme = "../README.md" +description = "SDK for using snark-verifier." +rust-version = "1.73.0" +autobenches = false [dependencies] -itertools = "0.10.5" +itertools = "0.11" lazy_static = "1.4.0" num-bigint = "0.4.3" num-integer = "0.1.45" @@ -17,55 +24,73 @@ serde_json = "1.0" serde_with = { version = "2.2", optional = true } bincode = "1.3.3" ark-std = { version = "0.3.0", features = ["print-trace"], optional = true } -halo2-base = { git = "https://github.com/axiom-crypto/halo2-lib.git", tag = "v0.3.0", default-features = false } -snark-verifier = { path = "../snark-verifier", default-features = false } +halo2-base = { version = "=0.4.0", default-features = false } +# halo2-base = { git = "https://github.com/axiom-crypto/halo2-lib.git", branch = "release-0.4.0-rc", default-features = false } +snark-verifier = { version = "=0.1.6", path = "../snark-verifier", default-features = false } +getset = "0.1.2" # loader_evm -ethereum-types = { version = "=0.14.1", default-features = false, features = ["std"], optional = true } -# sha3 = { version = "0.10", optional = true } -# revm = { version = "2.3.1", optional = true } -# bytes = { version = "1.2", optional = true } -# rlp = { version = "0.5", default-features = false, features = ["std"], optional = true } +ethereum-types = { version = "=0.14.1", default-features = false, features = [ + "std", +], optional = true } # zkevm benchmarks -zkevm-circuits = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", features = ["test"], optional = true } -bus-mapping = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", optional = true } -eth-types = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", optional = true } -mock = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", optional = true } +# zkevm-circuits = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", features = [ +# "test", +# ], optional = true } +# bus-mapping = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", optional = true } +# eth-types = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", optional = true } +# mock = { git = "https://github.com/privacy-scaling-explorations/zkevm-circuits.git", rev = "f834e61", optional = true } [dev-dependencies] ark-std = { version = "0.3.0", features = ["print-trace"] } paste = "1.0.7" -pprof = { version = "0.11", features = ["criterion", "flamegraph"] } -criterion = "0.4" +pprof = { version = "0.13", features = ["criterion", "flamegraph"] } +criterion = "0.5.1" criterion-macro = "0.4" # loader_evm crossterm = { version = "0.25" } -tui = { version = "0.19", default-features = false, features = ["crossterm"] } +ratatui = { version = "0.24", default-features = false, features = ["crossterm"] } [features] -default = ["loader_halo2", "loader_evm", "halo2-axiom", "halo2-base/jemallocator", "display"] +default = [ + "loader_halo2", + "loader_evm", + "halo2-axiom", + "halo2-base/jemallocator", + "display", +] display = ["snark-verifier/display", "dep:ark-std"] -loader_evm = ["snark-verifier/loader_evm", "dep:ethereum-types"] loader_halo2 = ["snark-verifier/loader_halo2"] +loader_evm = ["snark-verifier/loader_evm", "dep:ethereum-types"] +revm = ["snark-verifier/revm"] parallel = ["snark-verifier/parallel"] # EXACTLY one of halo2-pse / halo2-axiom should always be turned on; not sure how to enforce this with Cargo -halo2-pse = ["snark-verifier/halo2-pse", "dep:serde_with"] +# halo2-pse = ["snark-verifier/halo2-pse", "dep:serde_with"] halo2-axiom = ["snark-verifier/halo2-axiom"] -zkevm = ["dep:zkevm-circuits", "dep:bus-mapping", "dep:mock", "dep:eth-types"] +# zkevm = ["dep:zkevm-circuits", "dep:bus-mapping", "dep:mock", "dep:eth-types"] [[bench]] name = "standard_plonk" required-features = ["loader_halo2"] harness = false -[[bench]] -name = "zkevm" -required-features = ["loader_halo2", "loader_evm", "zkevm", "halo2-pse"] -harness = false +# [[bench]] +# name = "zkevm" +# required-features = ["loader_halo2", "loader_evm", "zkevm", "halo2-pse"] +# harness = false + +# [[bench]] +# name = "zkevm_plus_state" +# required-features = ["loader_halo2", "loader_evm", "zkevm", "halo2-pse"] +# harness = false [[bench]] -name = "zkevm_plus_state" -required-features = ["loader_halo2", "loader_evm", "zkevm", "halo2-pse"] +name = "read_pk" +required-features = ["loader_halo2"] harness = false + +[[example]] +name = "standard_plonk" +required-features = ["loader_halo2", "loader_evm"] diff --git a/snark-verifier-sdk/benches/read_pk.rs b/snark-verifier-sdk/benches/read_pk.rs new file mode 100644 index 00000000..4adc42fd --- /dev/null +++ b/snark-verifier-sdk/benches/read_pk.rs @@ -0,0 +1,223 @@ +use ark_std::{end_timer, start_timer}; +use criterion::Criterion; +use criterion::{criterion_group, criterion_main}; +use halo2_base::gates::circuit::CircuitBuilderStage; +use halo2_base::halo2_proofs; +use halo2_base::utils::fs::gen_srs; +use halo2_proofs::halo2curves as halo2_curves; +use halo2_proofs::{halo2curves::bn256::Bn256, poly::kzg::commitment::ParamsKZG}; +use pprof::criterion::{Output, PProfProfiler}; +use rand::rngs::OsRng; + +use snark_verifier_sdk::halo2::aggregation::{AggregationConfigParams, VerifierUniversality}; +use snark_verifier_sdk::{ + gen_pk, + halo2::{aggregation::AggregationCircuit, gen_snark_shplonk}, + Snark, +}; +use snark_verifier_sdk::{read_pk_with_capacity, SHPLONK}; +use std::path::Path; + +mod application { + use super::halo2_curves::bn256::Fr; + use super::halo2_proofs::{ + circuit::{Layouter, SimpleFloorPlanner, Value}, + plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, Instance}, + poly::Rotation, + }; + use rand::RngCore; + use snark_verifier_sdk::CircuitExt; + + #[derive(Clone, Copy)] + pub struct StandardPlonkConfig { + a: Column, + b: Column, + c: Column, + q_a: Column, + q_b: Column, + q_c: Column, + q_ab: Column, + constant: Column, + #[allow(dead_code)] + instance: Column, + } + + impl StandardPlonkConfig { + fn configure(meta: &mut ConstraintSystem) -> Self { + let [a, b, c] = [(); 3].map(|_| meta.advice_column()); + let [q_a, q_b, q_c, q_ab, constant] = [(); 5].map(|_| meta.fixed_column()); + let instance = meta.instance_column(); + + [a, b, c].map(|column| meta.enable_equality(column)); + + meta.create_gate( + "q_a·a + q_b·b + q_c·c + q_ab·a·b + constant + instance = 0", + |meta| { + let [a, b, c] = + [a, b, c].map(|column| meta.query_advice(column, Rotation::cur())); + let [q_a, q_b, q_c, q_ab, constant] = [q_a, q_b, q_c, q_ab, constant] + .map(|column| meta.query_fixed(column, Rotation::cur())); + let instance = meta.query_instance(instance, Rotation::cur()); + Some( + q_a * a.clone() + + q_b * b.clone() + + q_c * c + + q_ab * a * b + + constant + + instance, + ) + }, + ); + + StandardPlonkConfig { a, b, c, q_a, q_b, q_c, q_ab, constant, instance } + } + } + + #[derive(Clone, Default)] + pub struct StandardPlonk(Fr); + + impl StandardPlonk { + pub fn rand(mut rng: R) -> Self { + Self(Fr::from(rng.next_u32() as u64)) + } + } + + impl CircuitExt for StandardPlonk { + fn num_instance(&self) -> Vec { + vec![1] + } + + fn instances(&self) -> Vec> { + vec![vec![self.0]] + } + } + + impl Circuit for StandardPlonk { + type Config = StandardPlonkConfig; + type FloorPlanner = SimpleFloorPlanner; + + fn without_witnesses(&self) -> Self { + Self::default() + } + + fn configure(meta: &mut ConstraintSystem) -> Self::Config { + meta.set_minimum_degree(4); + StandardPlonkConfig::configure(meta) + } + + fn synthesize( + &self, + config: Self::Config, + mut layouter: impl Layouter, + ) -> Result<(), Error> { + layouter.assign_region( + || "", + |mut region| { + #[cfg(feature = "halo2-pse")] + { + region.assign_advice(|| "", config.a, 0, || Value::known(self.0))?; + region.assign_fixed(|| "", config.q_a, 0, || Value::known(-Fr::one()))?; + region.assign_advice( + || "", + config.a, + 1, + || Value::known(-Fr::from(5u64)), + )?; + for (idx, column) in (1..).zip([ + config.q_a, + config.q_b, + config.q_c, + config.q_ab, + config.constant, + ]) { + region.assign_fixed( + || "", + column, + 1, + || Value::known(Fr::from(idx as u64)), + )?; + } + let a = + region.assign_advice(|| "", config.a, 2, || Value::known(Fr::one()))?; + a.copy_advice(|| "", &mut region, config.b, 3)?; + a.copy_advice(|| "", &mut region, config.c, 4)?; + } + #[cfg(feature = "halo2-axiom")] + { + region.assign_advice(config.a, 0, Value::known(self.0)); + region.assign_fixed(config.q_a, 0, -Fr::one()); + region.assign_advice(config.a, 1, Value::known(-Fr::from(5u64))); + for (idx, column) in (1..).zip([ + config.q_a, + config.q_b, + config.q_c, + config.q_ab, + config.constant, + ]) { + region.assign_fixed(column, 1, Fr::from(idx as u64)); + } + + let a = region.assign_advice(config.a, 2, Value::known(Fr::one())); + a.copy_advice(&mut region, config.b, 3); + a.copy_advice(&mut region, config.c, 4); + } + + Ok(()) + }, + ) + } + } +} + +fn gen_application_snark(params: &ParamsKZG) -> Snark { + let circuit = application::StandardPlonk::rand(OsRng); + + let pk = gen_pk(params, &circuit, None); + gen_snark_shplonk(params, &pk, circuit, None::<&str>) +} + +fn bench(c: &mut Criterion) { + let path = "./configs/example_evm_accumulator.json"; + let params_app = gen_srs(8); + + let snarks = [(); 3].map(|_| gen_application_snark(¶ms_app)); + let agg_config = AggregationConfigParams::from_path(path); + let params = gen_srs(agg_config.degree); + + let agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + agg_config, + ¶ms, + snarks, + VerifierUniversality::None, + ); + + std::fs::remove_file("examples/agg.pk").ok(); + let start0 = start_timer!(|| "gen vk & pk"); + gen_pk(¶ms, &agg_circuit, Some(Path::new("examples/agg.pk"))); + end_timer!(start0); + + let mut group = c.benchmark_group("read-pk"); + group.sample_size(10); + group.bench_with_input("buffer 1mb capacity", &(1024 * 1024), |b, &c| { + b.iter(|| read_pk_with_capacity::(c, "examples/agg.pk", agg_config)) + }); + group.bench_with_input("buffer 10mb capacity", &(10 * 1024 * 1024), |b, &c| { + b.iter(|| read_pk_with_capacity::(c, "examples/agg.pk", agg_config)) + }); + group.bench_with_input("buffer 100mb capacity", &(100 * 1024 * 1024), |b, &c| { + b.iter(|| read_pk_with_capacity::(c, "examples/agg.pk", agg_config)) + }); + group.bench_with_input("buffer 1gb capacity", &(1024 * 1024 * 1024), |b, &c| { + b.iter(|| read_pk_with_capacity::(c, "examples/agg.pk", agg_config)) + }); + group.finish(); + std::fs::remove_file("examples/agg.pk").unwrap(); +} + +criterion_group! { + name = benches; + config = Criterion::default().with_profiler(PProfProfiler::new(10, Output::Flamegraph(None))); + targets = bench +} +criterion_main!(benches); diff --git a/snark-verifier-sdk/benches/standard_plonk.rs b/snark-verifier-sdk/benches/standard_plonk.rs index 70d600ea..6f933bb9 100644 --- a/snark-verifier-sdk/benches/standard_plonk.rs +++ b/snark-verifier-sdk/benches/standard_plonk.rs @@ -1,19 +1,20 @@ +use ark_std::{end_timer, start_timer}; use criterion::{criterion_group, criterion_main}; use criterion::{BenchmarkId, Criterion}; -use halo2_base::gates::builder::CircuitBuilderStage; -use halo2_base::utils::fs::gen_srs; -use pprof::criterion::{Output, PProfProfiler}; -use rand::rngs::OsRng; -use std::path::Path; -use ark_std::{end_timer, start_timer}; +use halo2_base::gates::circuit::CircuitBuilderStage; use halo2_base::halo2_proofs; +use halo2_base::utils::fs::gen_srs; use halo2_proofs::halo2curves as halo2_curves; use halo2_proofs::{ halo2curves::bn256::Bn256, poly::{commitment::Params, kzg::commitment::ParamsKZG}, }; -use snark_verifier_sdk::evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier_shplonk}; -use snark_verifier_sdk::halo2::aggregation::AggregationConfigParams; +use pprof::criterion::{Output, PProfProfiler}; +use rand::rngs::OsRng; +#[cfg(feature = "revm")] +use snark_verifier_sdk::evm::evm_verify; +use snark_verifier_sdk::evm::{gen_evm_proof_shplonk, gen_evm_verifier_shplonk}; +use snark_verifier_sdk::halo2::aggregation::{AggregationConfigParams, VerifierUniversality}; use snark_verifier_sdk::{ gen_pk, halo2::{aggregation::AggregationCircuit, gen_proof_shplonk, gen_snark_shplonk}, @@ -175,8 +176,8 @@ mod application { fn gen_application_snark(params: &ParamsKZG) -> Snark { let circuit = application::StandardPlonk::rand(OsRng); - let pk = gen_pk(params, &circuit, Some(Path::new("app.pk"))); - gen_snark_shplonk(params, &pk, circuit, Some(Path::new("app.snark"))) + let pk = gen_pk(params, &circuit, None); + gen_snark_shplonk(params, &pk, circuit, None::<&str>) } fn bench(c: &mut Criterion) { @@ -186,14 +187,20 @@ fn bench(c: &mut Criterion) { let snarks = [(); 3].map(|_| gen_application_snark(¶ms_app)); let agg_config = AggregationConfigParams::from_path(path); let params = gen_srs(agg_config.degree); - let lookup_bits = params.k() as usize - 1; - let agg_circuit = AggregationCircuit::keygen::(¶ms, snarks.clone()); + let agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + agg_config, + ¶ms, + snarks.clone(), + VerifierUniversality::None, + ); let start0 = start_timer!(|| "gen vk & pk"); - let pk = gen_pk(¶ms, &agg_circuit, Some(Path::new("agg.pk"))); + let pk = gen_pk(¶ms, &agg_circuit, None); end_timer!(start0); let break_points = agg_circuit.break_points(); + drop(agg_circuit); let mut group = c.benchmark_group("plonk-prover"); group.sample_size(10); @@ -204,11 +211,12 @@ fn bench(c: &mut Criterion) { b.iter(|| { let agg_circuit = AggregationCircuit::new::( CircuitBuilderStage::Prover, - Some(break_points.clone()), - lookup_bits, + agg_config, params, snarks.clone(), - ); + VerifierUniversality::None, + ) + .use_break_points(break_points.clone()); let instances = agg_circuit.instances(); gen_proof_shplonk(params, pk, agg_circuit, instances, None) }) @@ -221,22 +229,24 @@ fn bench(c: &mut Criterion) { // do one more time to verify let agg_circuit = AggregationCircuit::new::( CircuitBuilderStage::Prover, - Some(break_points), - lookup_bits, + agg_config, ¶ms, snarks.clone(), - ); + VerifierUniversality::None, + ) + .use_break_points(break_points); let num_instances = agg_circuit.num_instance(); let instances = agg_circuit.instances(); - let proof = gen_evm_proof_shplonk(¶ms, &pk, agg_circuit, instances.clone()); + let _proof = gen_evm_proof_shplonk(¶ms, &pk, agg_circuit, instances.clone()); - let deployment_code = gen_evm_verifier_shplonk::( + let _deployment_code = gen_evm_verifier_shplonk::( ¶ms, pk.get_vk(), num_instances, None, ); - evm_verify(deployment_code, instances, proof); + #[cfg(feature = "revm")] + evm_verify(_deployment_code, instances, _proof); } } diff --git a/snark-verifier-sdk/examples/StandardPlonkVerifier.sol b/snark-verifier-sdk/examples/StandardPlonkVerifier.sol new file mode 100644 index 00000000..2ac09483 --- /dev/null +++ b/snark-verifier-sdk/examples/StandardPlonkVerifier.sol @@ -0,0 +1,1443 @@ + +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.19; + +contract Halo2Verifier { + fallback(bytes calldata) external returns (bytes memory) { + assembly ("memory-safe") { + // Enforce that Solidity memory layout is respected + let data := mload(0x40) + if iszero(eq(data, 0x80)) { + revert(0, 0) + } + + let success := true + let f_p := 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 + let f_q := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 + function validate_ec_point(x, y) -> valid { + { + let x_lt_p := lt(x, 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47) + let y_lt_p := lt(y, 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47) + valid := and(x_lt_p, y_lt_p) + } + { + let y_square := mulmod(y, y, 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47) + let x_square := mulmod(x, x, 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47) + let x_cube := mulmod(x_square, x, 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47) + let x_cube_plus_3 := addmod(x_cube, 3, 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47) + let is_affine := eq(x_cube_plus_3, y_square) + valid := and(valid, is_affine) + } + } + mstore(0xa0, mod(calldataload(0x0), f_q)) +mstore(0xc0, mod(calldataload(0x20), f_q)) +mstore(0xe0, mod(calldataload(0x40), f_q)) +mstore(0x100, mod(calldataload(0x60), f_q)) +mstore(0x120, mod(calldataload(0x80), f_q)) +mstore(0x140, mod(calldataload(0xa0), f_q)) +mstore(0x160, mod(calldataload(0xc0), f_q)) +mstore(0x180, mod(calldataload(0xe0), f_q)) +mstore(0x1a0, mod(calldataload(0x100), f_q)) +mstore(0x1c0, mod(calldataload(0x120), f_q)) +mstore(0x1e0, mod(calldataload(0x140), f_q)) +mstore(0x200, mod(calldataload(0x160), f_q)) +mstore(0x80, 4821513469282282135963313459762076388609226322911319502565905456075264100373) + + { + let x := calldataload(0x180) + mstore(0x220, x) + let y := calldataload(0x1a0) + mstore(0x240, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x1c0) + mstore(0x260, x) + let y := calldataload(0x1e0) + mstore(0x280, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x200) + mstore(0x2a0, x) + let y := calldataload(0x220) + mstore(0x2c0, y) + success := and(validate_ec_point(x, y), success) + } +mstore(0x2e0, keccak256(0x80, 608)) +{ + let hash := mload(0x2e0) + mstore(0x300, mod(hash, f_q)) + mstore(0x320, hash) + } + + { + let x := calldataload(0x240) + mstore(0x340, x) + let y := calldataload(0x260) + mstore(0x360, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x280) + mstore(0x380, x) + let y := calldataload(0x2a0) + mstore(0x3a0, y) + success := and(validate_ec_point(x, y), success) + } +mstore(0x3c0, keccak256(0x320, 160)) +{ + let hash := mload(0x3c0) + mstore(0x3e0, mod(hash, f_q)) + mstore(0x400, hash) + } +mstore8(1056, 1) +mstore(0x420, keccak256(0x400, 33)) +{ + let hash := mload(0x420) + mstore(0x440, mod(hash, f_q)) + mstore(0x460, hash) + } + + { + let x := calldataload(0x2c0) + mstore(0x480, x) + let y := calldataload(0x2e0) + mstore(0x4a0, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x300) + mstore(0x4c0, x) + let y := calldataload(0x320) + mstore(0x4e0, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x340) + mstore(0x500, x) + let y := calldataload(0x360) + mstore(0x520, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x380) + mstore(0x540, x) + let y := calldataload(0x3a0) + mstore(0x560, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x3c0) + mstore(0x580, x) + let y := calldataload(0x3e0) + mstore(0x5a0, y) + success := and(validate_ec_point(x, y), success) + } +mstore(0x5c0, keccak256(0x460, 352)) +{ + let hash := mload(0x5c0) + mstore(0x5e0, mod(hash, f_q)) + mstore(0x600, hash) + } + + { + let x := calldataload(0x400) + mstore(0x620, x) + let y := calldataload(0x420) + mstore(0x640, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x440) + mstore(0x660, x) + let y := calldataload(0x460) + mstore(0x680, y) + success := and(validate_ec_point(x, y), success) + } + + { + let x := calldataload(0x480) + mstore(0x6a0, x) + let y := calldataload(0x4a0) + mstore(0x6c0, y) + success := and(validate_ec_point(x, y), success) + } +mstore(0x6e0, keccak256(0x600, 224)) +{ + let hash := mload(0x6e0) + mstore(0x700, mod(hash, f_q)) + mstore(0x720, hash) + } +mstore(0x740, mod(calldataload(0x4c0), f_q)) +mstore(0x760, mod(calldataload(0x4e0), f_q)) +mstore(0x780, mod(calldataload(0x500), f_q)) +mstore(0x7a0, mod(calldataload(0x520), f_q)) +mstore(0x7c0, mod(calldataload(0x540), f_q)) +mstore(0x7e0, mod(calldataload(0x560), f_q)) +mstore(0x800, mod(calldataload(0x580), f_q)) +mstore(0x820, mod(calldataload(0x5a0), f_q)) +mstore(0x840, mod(calldataload(0x5c0), f_q)) +mstore(0x860, mod(calldataload(0x5e0), f_q)) +mstore(0x880, mod(calldataload(0x600), f_q)) +mstore(0x8a0, mod(calldataload(0x620), f_q)) +mstore(0x8c0, mod(calldataload(0x640), f_q)) +mstore(0x8e0, mod(calldataload(0x660), f_q)) +mstore(0x900, mod(calldataload(0x680), f_q)) +mstore(0x920, mod(calldataload(0x6a0), f_q)) +mstore(0x940, mod(calldataload(0x6c0), f_q)) +mstore(0x960, mod(calldataload(0x6e0), f_q)) +mstore(0x980, mod(calldataload(0x700), f_q)) +mstore(0x9a0, mod(calldataload(0x720), f_q)) +mstore(0x9c0, mod(calldataload(0x740), f_q)) +mstore(0x9e0, mod(calldataload(0x760), f_q)) +mstore(0xa00, mod(calldataload(0x780), f_q)) +mstore(0xa20, mod(calldataload(0x7a0), f_q)) +mstore(0xa40, mod(calldataload(0x7c0), f_q)) +mstore(0xa60, mod(calldataload(0x7e0), f_q)) +mstore(0xa80, mod(calldataload(0x800), f_q)) +mstore(0xaa0, mod(calldataload(0x820), f_q)) +mstore(0xac0, mod(calldataload(0x840), f_q)) +mstore(0xae0, mod(calldataload(0x860), f_q)) +mstore(0xb00, mod(calldataload(0x880), f_q)) +mstore(0xb20, mod(calldataload(0x8a0), f_q)) +mstore(0xb40, keccak256(0x720, 1056)) +{ + let hash := mload(0xb40) + mstore(0xb60, mod(hash, f_q)) + mstore(0xb80, hash) + } +mstore8(2976, 1) +mstore(0xba0, keccak256(0xb80, 33)) +{ + let hash := mload(0xba0) + mstore(0xbc0, mod(hash, f_q)) + mstore(0xbe0, hash) + } + + { + let x := calldataload(0x8c0) + mstore(0xc00, x) + let y := calldataload(0x8e0) + mstore(0xc20, y) + success := and(validate_ec_point(x, y), success) + } +mstore(0xc40, keccak256(0xbe0, 96)) +{ + let hash := mload(0xc40) + mstore(0xc60, mod(hash, f_q)) + mstore(0xc80, hash) + } + + { + let x := calldataload(0x900) + mstore(0xca0, x) + let y := calldataload(0x920) + mstore(0xcc0, y) + success := and(validate_ec_point(x, y), success) + } +{ + let x := mload(0xa0) +x := add(x, shl(88, mload(0xc0))) +x := add(x, shl(176, mload(0xe0))) +mstore(3296, x) +let y := mload(0x100) +y := add(y, shl(88, mload(0x120))) +y := add(y, shl(176, mload(0x140))) +mstore(3328, y) + + success := and(validate_ec_point(x, y), success) + } +{ + let x := mload(0x160) +x := add(x, shl(88, mload(0x180))) +x := add(x, shl(176, mload(0x1a0))) +mstore(3360, x) +let y := mload(0x1c0) +y := add(y, shl(88, mload(0x1e0))) +y := add(y, shl(176, mload(0x200))) +mstore(3392, y) + + success := and(validate_ec_point(x, y), success) + } +mstore(0xd60, mulmod(mload(0x700), mload(0x700), f_q)) +mstore(0xd80, mulmod(mload(0xd60), mload(0xd60), f_q)) +mstore(0xda0, mulmod(mload(0xd80), mload(0xd80), f_q)) +mstore(0xdc0, mulmod(mload(0xda0), mload(0xda0), f_q)) +mstore(0xde0, mulmod(mload(0xdc0), mload(0xdc0), f_q)) +mstore(0xe00, mulmod(mload(0xde0), mload(0xde0), f_q)) +mstore(0xe20, mulmod(mload(0xe00), mload(0xe00), f_q)) +mstore(0xe40, mulmod(mload(0xe20), mload(0xe20), f_q)) +mstore(0xe60, mulmod(mload(0xe40), mload(0xe40), f_q)) +mstore(0xe80, mulmod(mload(0xe60), mload(0xe60), f_q)) +mstore(0xea0, mulmod(mload(0xe80), mload(0xe80), f_q)) +mstore(0xec0, mulmod(mload(0xea0), mload(0xea0), f_q)) +mstore(0xee0, mulmod(mload(0xec0), mload(0xec0), f_q)) +mstore(0xf00, mulmod(mload(0xee0), mload(0xee0), f_q)) +mstore(0xf20, mulmod(mload(0xf00), mload(0xf00), f_q)) +mstore(0xf40, mulmod(mload(0xf20), mload(0xf20), f_q)) +mstore(0xf60, mulmod(mload(0xf40), mload(0xf40), f_q)) +mstore(0xf80, mulmod(mload(0xf60), mload(0xf60), f_q)) +mstore(0xfa0, mulmod(mload(0xf80), mload(0xf80), f_q)) +mstore(0xfc0, mulmod(mload(0xfa0), mload(0xfa0), f_q)) +mstore(0xfe0, mulmod(mload(0xfc0), mload(0xfc0), f_q)) +mstore(0x1000, addmod(mload(0xfe0), 21888242871839275222246405745257275088548364400416034343698204186575808495616, f_q)) +mstore(0x1020, mulmod(mload(0x1000), 21888232434711746154598842647110004286396165347431605739555851272621938401409, f_q)) +mstore(0x1040, mulmod(mload(0x1020), 20975929243409798062839949658616274858986091382510192949221301676705706354487, f_q)) +mstore(0x1060, addmod(mload(0x700), 912313628429477159406456086641000229562273017905841394476902509870102141130, f_q)) +mstore(0x1080, mulmod(mload(0x1020), 495188420091111145957709789221178673495499187437761988132837836548330853701, f_q)) +mstore(0x10a0, addmod(mload(0x700), 21393054451748164076288695956036096415052865212978272355565366350027477641916, f_q)) +mstore(0x10c0, mulmod(mload(0x1020), 16064522944768515290584536219762686197737451920702130080538975732575755569557, f_q)) +mstore(0x10e0, addmod(mload(0x700), 5823719927070759931661869525494588890810912479713904263159228454000052926060, f_q)) +mstore(0x1100, mulmod(mload(0x1020), 14686510910986211321976396297238126901237973400949744736326777596334651355305, f_q)) +mstore(0x1120, addmod(mload(0x700), 7201731960853063900270009448019148187310390999466289607371426590241157140312, f_q)) +mstore(0x1140, mulmod(mload(0x1020), 10939663269433627367777756708678102241564365262857670666700619874077960926249, f_q)) +mstore(0x1160, addmod(mload(0x700), 10948579602405647854468649036579172846983999137558363676997584312497847569368, f_q)) +mstore(0x1180, mulmod(mload(0x1020), 15402826414547299628414612080036060696555554914079673875872749760617770134879, f_q)) +mstore(0x11a0, addmod(mload(0x700), 6485416457291975593831793665221214391992809486336360467825454425958038360738, f_q)) +mstore(0x11c0, mulmod(mload(0x1020), 2785514556381676080176937710880804108647911392478702105860685610379369825016, f_q)) +mstore(0x11e0, addmod(mload(0x700), 19102728315457599142069468034376470979900453007937332237837518576196438670601, f_q)) +mstore(0x1200, mulmod(mload(0x1020), 1, f_q)) +mstore(0x1220, addmod(mload(0x700), 21888242871839275222246405745257275088548364400416034343698204186575808495616, f_q)) +mstore(0x1240, mulmod(mload(0x1020), 1426404432721484388505361748317961535523355871255605456897797744433766488507, f_q)) +mstore(0x1260, addmod(mload(0x700), 20461838439117790833741043996939313553025008529160428886800406442142042007110, f_q)) +mstore(0x1280, mulmod(mload(0x1020), 19032961837237948602743626455740240236231119053033140765040043513661803148152, f_q)) +mstore(0x12a0, addmod(mload(0x700), 2855281034601326619502779289517034852317245347382893578658160672914005347465, f_q)) +mstore(0x12c0, mulmod(mload(0x1020), 3766081621734395783232337525162072736827576297943013392955872170138036189193, f_q)) +mstore(0x12e0, addmod(mload(0x700), 18122161250104879439014068220095202351720788102473020950742332016437772306424, f_q)) +mstore(0x1300, mulmod(mload(0x1020), 5854133144571823792863860130267644613802765696134002830362054821530146160770, f_q)) +mstore(0x1320, addmod(mload(0x700), 16034109727267451429382545614989630474745598704282031513336149365045662334847, f_q)) +mstore(0x1340, mulmod(mload(0x1020), 14557038802599140430182096396825290815503940951075961210638273254419942783582, f_q)) +mstore(0x1360, addmod(mload(0x700), 7331204069240134792064309348431984273044423449340073133059930932155865712035, f_q)) +mstore(0x1380, mulmod(mload(0x1020), 9697063347556872083384215826199993067635178715531258559890418744774301211662, f_q)) +mstore(0x13a0, addmod(mload(0x700), 12191179524282403138862189919057282020913185684884775783807785441801507283955, f_q)) +mstore(0x13c0, mulmod(mload(0x1020), 12459868075641381822485233712013080087763946065665469821362892189399541605692, f_q)) +mstore(0x13e0, addmod(mload(0x700), 9428374796197893399761172033244195000784418334750564522335311997176266889925, f_q)) +mstore(0x1400, mulmod(mload(0x1020), 6955697244493336113861667751840378876927906302623587437721024018233754910398, f_q)) +mstore(0x1420, addmod(mload(0x700), 14932545627345939108384737993416896211620458097792446905977180168342053585219, f_q)) +mstore(0x1440, mulmod(mload(0x1020), 20345677989844117909528750049476969581182118546166966482506114734614108237981, f_q)) +mstore(0x1460, addmod(mload(0x700), 1542564881995157312717655695780305507366245854249067861192089451961700257636, f_q)) +mstore(0x1480, mulmod(mload(0x1020), 5289443209903185443361862148540090689648485914368835830972895623576469023722, f_q)) +mstore(0x14a0, addmod(mload(0x700), 16598799661936089778884543596717184398899878486047198512725308562999339471895, f_q)) +mstore(0x14c0, mulmod(mload(0x1020), 557567375339945239933617516585967620814823575807691402619711360028043331811, f_q)) +mstore(0x14e0, addmod(mload(0x700), 21330675496499329982312788228671307467733540824608342941078492826547765163806, f_q)) +{ + let prod := mload(0x1060) + + prod := mulmod(mload(0x10a0), prod, f_q) + mstore(0x1500, prod) + + prod := mulmod(mload(0x10e0), prod, f_q) + mstore(0x1520, prod) + + prod := mulmod(mload(0x1120), prod, f_q) + mstore(0x1540, prod) + + prod := mulmod(mload(0x1160), prod, f_q) + mstore(0x1560, prod) + + prod := mulmod(mload(0x11a0), prod, f_q) + mstore(0x1580, prod) + + prod := mulmod(mload(0x11e0), prod, f_q) + mstore(0x15a0, prod) + + prod := mulmod(mload(0x1220), prod, f_q) + mstore(0x15c0, prod) + + prod := mulmod(mload(0x1260), prod, f_q) + mstore(0x15e0, prod) + + prod := mulmod(mload(0x12a0), prod, f_q) + mstore(0x1600, prod) + + prod := mulmod(mload(0x12e0), prod, f_q) + mstore(0x1620, prod) + + prod := mulmod(mload(0x1320), prod, f_q) + mstore(0x1640, prod) + + prod := mulmod(mload(0x1360), prod, f_q) + mstore(0x1660, prod) + + prod := mulmod(mload(0x13a0), prod, f_q) + mstore(0x1680, prod) + + prod := mulmod(mload(0x13e0), prod, f_q) + mstore(0x16a0, prod) + + prod := mulmod(mload(0x1420), prod, f_q) + mstore(0x16c0, prod) + + prod := mulmod(mload(0x1460), prod, f_q) + mstore(0x16e0, prod) + + prod := mulmod(mload(0x14a0), prod, f_q) + mstore(0x1700, prod) + + prod := mulmod(mload(0x14e0), prod, f_q) + mstore(0x1720, prod) + + prod := mulmod(mload(0x1000), prod, f_q) + mstore(0x1740, prod) + + } +mstore(0x1780, 32) +mstore(0x17a0, 32) +mstore(0x17c0, 32) +mstore(0x17e0, mload(0x1740)) +mstore(0x1800, 21888242871839275222246405745257275088548364400416034343698204186575808495615) +mstore(0x1820, 21888242871839275222246405745257275088548364400416034343698204186575808495617) +success := and(eq(staticcall(gas(), 0x5, 0x1780, 0xc0, 0x1760, 0x20), 1), success) +{ + + let inv := mload(0x1760) + let v + + v := mload(0x1000) + mstore(4096, mulmod(mload(0x1720), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x14e0) + mstore(5344, mulmod(mload(0x1700), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x14a0) + mstore(5280, mulmod(mload(0x16e0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1460) + mstore(5216, mulmod(mload(0x16c0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1420) + mstore(5152, mulmod(mload(0x16a0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x13e0) + mstore(5088, mulmod(mload(0x1680), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x13a0) + mstore(5024, mulmod(mload(0x1660), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1360) + mstore(4960, mulmod(mload(0x1640), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1320) + mstore(4896, mulmod(mload(0x1620), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x12e0) + mstore(4832, mulmod(mload(0x1600), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x12a0) + mstore(4768, mulmod(mload(0x15e0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1260) + mstore(4704, mulmod(mload(0x15c0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1220) + mstore(4640, mulmod(mload(0x15a0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x11e0) + mstore(4576, mulmod(mload(0x1580), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x11a0) + mstore(4512, mulmod(mload(0x1560), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1160) + mstore(4448, mulmod(mload(0x1540), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x1120) + mstore(4384, mulmod(mload(0x1520), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x10e0) + mstore(4320, mulmod(mload(0x1500), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x10a0) + mstore(4256, mulmod(mload(0x1060), inv, f_q)) + inv := mulmod(v, inv, f_q) + mstore(0x1060, inv) + + } +mstore(0x1840, mulmod(mload(0x1040), mload(0x1060), f_q)) +mstore(0x1860, mulmod(mload(0x1080), mload(0x10a0), f_q)) +mstore(0x1880, mulmod(mload(0x10c0), mload(0x10e0), f_q)) +mstore(0x18a0, mulmod(mload(0x1100), mload(0x1120), f_q)) +mstore(0x18c0, mulmod(mload(0x1140), mload(0x1160), f_q)) +mstore(0x18e0, mulmod(mload(0x1180), mload(0x11a0), f_q)) +mstore(0x1900, mulmod(mload(0x11c0), mload(0x11e0), f_q)) +mstore(0x1920, mulmod(mload(0x1200), mload(0x1220), f_q)) +mstore(0x1940, mulmod(mload(0x1240), mload(0x1260), f_q)) +mstore(0x1960, mulmod(mload(0x1280), mload(0x12a0), f_q)) +mstore(0x1980, mulmod(mload(0x12c0), mload(0x12e0), f_q)) +mstore(0x19a0, mulmod(mload(0x1300), mload(0x1320), f_q)) +mstore(0x19c0, mulmod(mload(0x1340), mload(0x1360), f_q)) +mstore(0x19e0, mulmod(mload(0x1380), mload(0x13a0), f_q)) +mstore(0x1a00, mulmod(mload(0x13c0), mload(0x13e0), f_q)) +mstore(0x1a20, mulmod(mload(0x1400), mload(0x1420), f_q)) +mstore(0x1a40, mulmod(mload(0x1440), mload(0x1460), f_q)) +mstore(0x1a60, mulmod(mload(0x1480), mload(0x14a0), f_q)) +mstore(0x1a80, mulmod(mload(0x14c0), mload(0x14e0), f_q)) +{ + let result := mulmod(mload(0x1920), mload(0xa0), f_q) +result := addmod(mulmod(mload(0x1940), mload(0xc0), f_q), result, f_q) +result := addmod(mulmod(mload(0x1960), mload(0xe0), f_q), result, f_q) +result := addmod(mulmod(mload(0x1980), mload(0x100), f_q), result, f_q) +result := addmod(mulmod(mload(0x19a0), mload(0x120), f_q), result, f_q) +result := addmod(mulmod(mload(0x19c0), mload(0x140), f_q), result, f_q) +result := addmod(mulmod(mload(0x19e0), mload(0x160), f_q), result, f_q) +result := addmod(mulmod(mload(0x1a00), mload(0x180), f_q), result, f_q) +result := addmod(mulmod(mload(0x1a20), mload(0x1a0), f_q), result, f_q) +result := addmod(mulmod(mload(0x1a40), mload(0x1c0), f_q), result, f_q) +result := addmod(mulmod(mload(0x1a60), mload(0x1e0), f_q), result, f_q) +result := addmod(mulmod(mload(0x1a80), mload(0x200), f_q), result, f_q) +mstore(6816, result) + } +mstore(0x1ac0, mulmod(mload(0x780), mload(0x760), f_q)) +mstore(0x1ae0, addmod(mload(0x740), mload(0x1ac0), f_q)) +mstore(0x1b00, addmod(mload(0x1ae0), sub(f_q, mload(0x7a0)), f_q)) +mstore(0x1b20, mulmod(mload(0x1b00), mload(0x8a0), f_q)) +mstore(0x1b40, mulmod(mload(0x5e0), mload(0x1b20), f_q)) +mstore(0x1b60, mulmod(mload(0x800), mload(0x7e0), f_q)) +mstore(0x1b80, addmod(mload(0x7c0), mload(0x1b60), f_q)) +mstore(0x1ba0, addmod(mload(0x1b80), sub(f_q, mload(0x820)), f_q)) +mstore(0x1bc0, mulmod(mload(0x1ba0), mload(0x8c0), f_q)) +mstore(0x1be0, addmod(mload(0x1b40), mload(0x1bc0), f_q)) +mstore(0x1c00, mulmod(mload(0x5e0), mload(0x1be0), f_q)) +mstore(0x1c20, addmod(1, sub(f_q, mload(0x9a0)), f_q)) +mstore(0x1c40, mulmod(mload(0x1c20), mload(0x1920), f_q)) +mstore(0x1c60, addmod(mload(0x1c00), mload(0x1c40), f_q)) +mstore(0x1c80, mulmod(mload(0x5e0), mload(0x1c60), f_q)) +mstore(0x1ca0, mulmod(mload(0xa60), mload(0xa60), f_q)) +mstore(0x1cc0, addmod(mload(0x1ca0), sub(f_q, mload(0xa60)), f_q)) +mstore(0x1ce0, mulmod(mload(0x1cc0), mload(0x1840), f_q)) +mstore(0x1d00, addmod(mload(0x1c80), mload(0x1ce0), f_q)) +mstore(0x1d20, mulmod(mload(0x5e0), mload(0x1d00), f_q)) +mstore(0x1d40, addmod(mload(0xa00), sub(f_q, mload(0x9e0)), f_q)) +mstore(0x1d60, mulmod(mload(0x1d40), mload(0x1920), f_q)) +mstore(0x1d80, addmod(mload(0x1d20), mload(0x1d60), f_q)) +mstore(0x1da0, mulmod(mload(0x5e0), mload(0x1d80), f_q)) +mstore(0x1dc0, addmod(mload(0xa60), sub(f_q, mload(0xa40)), f_q)) +mstore(0x1de0, mulmod(mload(0x1dc0), mload(0x1920), f_q)) +mstore(0x1e00, addmod(mload(0x1da0), mload(0x1de0), f_q)) +mstore(0x1e20, mulmod(mload(0x5e0), mload(0x1e00), f_q)) +mstore(0x1e40, addmod(1, sub(f_q, mload(0x1840)), f_q)) +mstore(0x1e60, addmod(mload(0x1860), mload(0x1880), f_q)) +mstore(0x1e80, addmod(mload(0x1e60), mload(0x18a0), f_q)) +mstore(0x1ea0, addmod(mload(0x1e80), mload(0x18c0), f_q)) +mstore(0x1ec0, addmod(mload(0x1ea0), mload(0x18e0), f_q)) +mstore(0x1ee0, addmod(mload(0x1ec0), mload(0x1900), f_q)) +mstore(0x1f00, addmod(mload(0x1e40), sub(f_q, mload(0x1ee0)), f_q)) +mstore(0x1f20, mulmod(mload(0x900), mload(0x3e0), f_q)) +mstore(0x1f40, addmod(mload(0x860), mload(0x1f20), f_q)) +mstore(0x1f60, addmod(mload(0x1f40), mload(0x440), f_q)) +mstore(0x1f80, mulmod(mload(0x920), mload(0x3e0), f_q)) +mstore(0x1fa0, addmod(mload(0x740), mload(0x1f80), f_q)) +mstore(0x1fc0, addmod(mload(0x1fa0), mload(0x440), f_q)) +mstore(0x1fe0, mulmod(mload(0x1fc0), mload(0x1f60), f_q)) +mstore(0x2000, mulmod(mload(0x1fe0), mload(0x9c0), f_q)) +mstore(0x2020, mulmod(1, mload(0x3e0), f_q)) +mstore(0x2040, mulmod(mload(0x700), mload(0x2020), f_q)) +mstore(0x2060, addmod(mload(0x860), mload(0x2040), f_q)) +mstore(0x2080, addmod(mload(0x2060), mload(0x440), f_q)) +mstore(0x20a0, mulmod(4131629893567559867359510883348571134090853742863529169391034518566172092834, mload(0x3e0), f_q)) +mstore(0x20c0, mulmod(mload(0x700), mload(0x20a0), f_q)) +mstore(0x20e0, addmod(mload(0x740), mload(0x20c0), f_q)) +mstore(0x2100, addmod(mload(0x20e0), mload(0x440), f_q)) +mstore(0x2120, mulmod(mload(0x2100), mload(0x2080), f_q)) +mstore(0x2140, mulmod(mload(0x2120), mload(0x9a0), f_q)) +mstore(0x2160, addmod(mload(0x2000), sub(f_q, mload(0x2140)), f_q)) +mstore(0x2180, mulmod(mload(0x2160), mload(0x1f00), f_q)) +mstore(0x21a0, addmod(mload(0x1e20), mload(0x2180), f_q)) +mstore(0x21c0, mulmod(mload(0x5e0), mload(0x21a0), f_q)) +mstore(0x21e0, mulmod(mload(0x940), mload(0x3e0), f_q)) +mstore(0x2200, addmod(mload(0x7c0), mload(0x21e0), f_q)) +mstore(0x2220, addmod(mload(0x2200), mload(0x440), f_q)) +mstore(0x2240, mulmod(mload(0x960), mload(0x3e0), f_q)) +mstore(0x2260, addmod(mload(0x840), mload(0x2240), f_q)) +mstore(0x2280, addmod(mload(0x2260), mload(0x440), f_q)) +mstore(0x22a0, mulmod(mload(0x2280), mload(0x2220), f_q)) +mstore(0x22c0, mulmod(mload(0x22a0), mload(0xa20), f_q)) +mstore(0x22e0, mulmod(8910878055287538404433155982483128285667088683464058436815641868457422632747, mload(0x3e0), f_q)) +mstore(0x2300, mulmod(mload(0x700), mload(0x22e0), f_q)) +mstore(0x2320, addmod(mload(0x7c0), mload(0x2300), f_q)) +mstore(0x2340, addmod(mload(0x2320), mload(0x440), f_q)) +mstore(0x2360, mulmod(11166246659983828508719468090013646171463329086121580628794302409516816350802, mload(0x3e0), f_q)) +mstore(0x2380, mulmod(mload(0x700), mload(0x2360), f_q)) +mstore(0x23a0, addmod(mload(0x840), mload(0x2380), f_q)) +mstore(0x23c0, addmod(mload(0x23a0), mload(0x440), f_q)) +mstore(0x23e0, mulmod(mload(0x23c0), mload(0x2340), f_q)) +mstore(0x2400, mulmod(mload(0x23e0), mload(0xa00), f_q)) +mstore(0x2420, addmod(mload(0x22c0), sub(f_q, mload(0x2400)), f_q)) +mstore(0x2440, mulmod(mload(0x2420), mload(0x1f00), f_q)) +mstore(0x2460, addmod(mload(0x21c0), mload(0x2440), f_q)) +mstore(0x2480, mulmod(mload(0x5e0), mload(0x2460), f_q)) +mstore(0x24a0, mulmod(mload(0x980), mload(0x3e0), f_q)) +mstore(0x24c0, addmod(mload(0x1aa0), mload(0x24a0), f_q)) +mstore(0x24e0, addmod(mload(0x24c0), mload(0x440), f_q)) +mstore(0x2500, mulmod(mload(0x24e0), mload(0xa80), f_q)) +mstore(0x2520, mulmod(284840088355319032285349970403338060113257071685626700086398481893096618818, mload(0x3e0), f_q)) +mstore(0x2540, mulmod(mload(0x700), mload(0x2520), f_q)) +mstore(0x2560, addmod(mload(0x1aa0), mload(0x2540), f_q)) +mstore(0x2580, addmod(mload(0x2560), mload(0x440), f_q)) +mstore(0x25a0, mulmod(mload(0x2580), mload(0xa60), f_q)) +mstore(0x25c0, addmod(mload(0x2500), sub(f_q, mload(0x25a0)), f_q)) +mstore(0x25e0, mulmod(mload(0x25c0), mload(0x1f00), f_q)) +mstore(0x2600, addmod(mload(0x2480), mload(0x25e0), f_q)) +mstore(0x2620, mulmod(mload(0x5e0), mload(0x2600), f_q)) +mstore(0x2640, addmod(1, sub(f_q, mload(0xaa0)), f_q)) +mstore(0x2660, mulmod(mload(0x2640), mload(0x1920), f_q)) +mstore(0x2680, addmod(mload(0x2620), mload(0x2660), f_q)) +mstore(0x26a0, mulmod(mload(0x5e0), mload(0x2680), f_q)) +mstore(0x26c0, mulmod(mload(0xaa0), mload(0xaa0), f_q)) +mstore(0x26e0, addmod(mload(0x26c0), sub(f_q, mload(0xaa0)), f_q)) +mstore(0x2700, mulmod(mload(0x26e0), mload(0x1840), f_q)) +mstore(0x2720, addmod(mload(0x26a0), mload(0x2700), f_q)) +mstore(0x2740, mulmod(mload(0x5e0), mload(0x2720), f_q)) +mstore(0x2760, addmod(mload(0xae0), mload(0x3e0), f_q)) +mstore(0x2780, mulmod(mload(0x2760), mload(0xac0), f_q)) +mstore(0x27a0, addmod(mload(0xb20), mload(0x440), f_q)) +mstore(0x27c0, mulmod(mload(0x27a0), mload(0x2780), f_q)) +mstore(0x27e0, addmod(mload(0x840), mload(0x3e0), f_q)) +mstore(0x2800, mulmod(mload(0x27e0), mload(0xaa0), f_q)) +mstore(0x2820, addmod(mload(0x880), mload(0x440), f_q)) +mstore(0x2840, mulmod(mload(0x2820), mload(0x2800), f_q)) +mstore(0x2860, addmod(mload(0x27c0), sub(f_q, mload(0x2840)), f_q)) +mstore(0x2880, mulmod(mload(0x2860), mload(0x1f00), f_q)) +mstore(0x28a0, addmod(mload(0x2740), mload(0x2880), f_q)) +mstore(0x28c0, mulmod(mload(0x5e0), mload(0x28a0), f_q)) +mstore(0x28e0, addmod(mload(0xae0), sub(f_q, mload(0xb20)), f_q)) +mstore(0x2900, mulmod(mload(0x28e0), mload(0x1920), f_q)) +mstore(0x2920, addmod(mload(0x28c0), mload(0x2900), f_q)) +mstore(0x2940, mulmod(mload(0x5e0), mload(0x2920), f_q)) +mstore(0x2960, mulmod(mload(0x28e0), mload(0x1f00), f_q)) +mstore(0x2980, addmod(mload(0xae0), sub(f_q, mload(0xb00)), f_q)) +mstore(0x29a0, mulmod(mload(0x2980), mload(0x2960), f_q)) +mstore(0x29c0, addmod(mload(0x2940), mload(0x29a0), f_q)) +mstore(0x29e0, mulmod(mload(0xfe0), mload(0xfe0), f_q)) +mstore(0x2a00, mulmod(mload(0x29e0), mload(0xfe0), f_q)) +mstore(0x2a20, mulmod(1, mload(0xfe0), f_q)) +mstore(0x2a40, mulmod(1, mload(0x29e0), f_q)) +mstore(0x2a60, mulmod(mload(0x29c0), mload(0x1000), f_q)) +mstore(0x2a80, mulmod(mload(0xd60), mload(0x700), f_q)) +mstore(0x2aa0, mulmod(mload(0x2a80), mload(0x700), f_q)) +mstore(0x2ac0, mulmod(mload(0x700), 20975929243409798062839949658616274858986091382510192949221301676705706354487, f_q)) +mstore(0x2ae0, addmod(mload(0xc60), sub(f_q, mload(0x2ac0)), f_q)) +mstore(0x2b00, mulmod(mload(0x700), 2785514556381676080176937710880804108647911392478702105860685610379369825016, f_q)) +mstore(0x2b20, addmod(mload(0xc60), sub(f_q, mload(0x2b00)), f_q)) +mstore(0x2b40, mulmod(mload(0x700), 1, f_q)) +mstore(0x2b60, addmod(mload(0xc60), sub(f_q, mload(0x2b40)), f_q)) +mstore(0x2b80, mulmod(mload(0x700), 1426404432721484388505361748317961535523355871255605456897797744433766488507, f_q)) +mstore(0x2ba0, addmod(mload(0xc60), sub(f_q, mload(0x2b80)), f_q)) +mstore(0x2bc0, mulmod(mload(0x700), 19032961837237948602743626455740240236231119053033140765040043513661803148152, f_q)) +mstore(0x2be0, addmod(mload(0xc60), sub(f_q, mload(0x2bc0)), f_q)) +mstore(0x2c00, mulmod(mload(0x700), 3766081621734395783232337525162072736827576297943013392955872170138036189193, f_q)) +mstore(0x2c20, addmod(mload(0xc60), sub(f_q, mload(0x2c00)), f_q)) +mstore(0x2c40, mulmod(12142985201493934370659158242092015678465417407805993602870272259656026591649, mload(0x2a80), f_q)) +mstore(0x2c60, mulmod(mload(0x2c40), 1, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2c40), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2c60)), f_q), result, f_q) +mstore(11392, result) + } +mstore(0x2ca0, mulmod(12858672892267984631233883117647866851148059157064290846881981435700301865966, mload(0x2a80), f_q)) +mstore(0x2cc0, mulmod(mload(0x2ca0), 1426404432721484388505361748317961535523355871255605456897797744433766488507, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2ca0), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2cc0)), f_q), result, f_q) +mstore(11488, result) + } +mstore(0x2d00, mulmod(20880316823902385764034220950270964645276820671488089374347912013802613180902, mload(0x2a80), f_q)) +mstore(0x2d20, mulmod(mload(0x2d00), 19032961837237948602743626455740240236231119053033140765040043513661803148152, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2d00), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2d20)), f_q), result, f_q) +mstore(11584, result) + } +mstore(0x2d60, mulmod(17575202995145968412995467587554373308969396527144859871466654432792864477050, mload(0x2a80), f_q)) +mstore(0x2d80, mulmod(mload(0x2d60), 3766081621734395783232337525162072736827576297943013392955872170138036189193, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2d60), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2d80)), f_q), result, f_q) +mstore(11680, result) + } +mstore(0x2dc0, mulmod(1, mload(0x2b60), f_q)) +mstore(0x2de0, mulmod(mload(0x2dc0), mload(0x2ba0), f_q)) +mstore(0x2e00, mulmod(mload(0x2de0), mload(0x2be0), f_q)) +mstore(0x2e20, mulmod(mload(0x2e00), mload(0x2c20), f_q)) +{ + let result := mulmod(mload(0xc60), 1, f_q) +result := addmod(mulmod(mload(0x700), 21888242871839275222246405745257275088548364400416034343698204186575808495616, f_q), result, f_q) +mstore(11840, result) + } +mstore(0x2e60, mulmod(21869340487638379139105209872801492456082780734504032269410146788560475001942, mload(0xd60), f_q)) +mstore(0x2e80, mulmod(mload(0x2e60), 1, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2e60), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2e80)), f_q), result, f_q) +mstore(11936, result) + } +mstore(0x2ec0, mulmod(16199055355995875908874098831560099797649990976433931925532505422809603664814, mload(0xd60), f_q)) +mstore(0x2ee0, mulmod(mload(0x2ec0), 1426404432721484388505361748317961535523355871255605456897797744433766488507, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2ec0), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2ee0)), f_q), result, f_q) +mstore(12032, result) + } +mstore(0x2f20, mulmod(4865187280763976036134135047793386535665014353502380106898040096680231678680, mload(0xd60), f_q)) +mstore(0x2f40, mulmod(mload(0x2f20), 20975929243409798062839949658616274858986091382510192949221301676705706354487, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2f20), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2f40)), f_q), result, f_q) +mstore(12128, result) + } +mstore(0x2f80, mulmod(mload(0x2de0), mload(0x2ae0), f_q)) +mstore(0x2fa0, mulmod(20461838439117790833741043996939313553025008529160428886800406442142042007111, mload(0x700), f_q)) +mstore(0x2fc0, mulmod(mload(0x2fa0), 1, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x2fa0), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x2fc0)), f_q), result, f_q) +mstore(12256, result) + } +mstore(0x3000, mulmod(1426404432721484388505361748317961535523355871255605456897797744433766488506, mload(0x700), f_q)) +mstore(0x3020, mulmod(mload(0x3000), 1426404432721484388505361748317961535523355871255605456897797744433766488507, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x3000), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x3020)), f_q), result, f_q) +mstore(12352, result) + } +mstore(0x3060, mulmod(19102728315457599142069468034376470979900453007937332237837518576196438670602, mload(0x700), f_q)) +mstore(0x3080, mulmod(mload(0x3060), 1, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x3060), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x3080)), f_q), result, f_q) +mstore(12448, result) + } +mstore(0x30c0, mulmod(2785514556381676080176937710880804108647911392478702105860685610379369825015, mload(0x700), f_q)) +mstore(0x30e0, mulmod(mload(0x30c0), 2785514556381676080176937710880804108647911392478702105860685610379369825016, f_q)) +{ + let result := mulmod(mload(0xc60), mload(0x30c0), f_q) +result := addmod(mulmod(mload(0x700), sub(f_q, mload(0x30e0)), f_q), result, f_q) +mstore(12544, result) + } +mstore(0x3120, mulmod(mload(0x2dc0), mload(0x2b20), f_q)) +{ + let prod := mload(0x2c80) + + prod := mulmod(mload(0x2ce0), prod, f_q) + mstore(0x3140, prod) + + prod := mulmod(mload(0x2d40), prod, f_q) + mstore(0x3160, prod) + + prod := mulmod(mload(0x2da0), prod, f_q) + mstore(0x3180, prod) + + prod := mulmod(mload(0x2e40), prod, f_q) + mstore(0x31a0, prod) + + prod := mulmod(mload(0x2dc0), prod, f_q) + mstore(0x31c0, prod) + + prod := mulmod(mload(0x2ea0), prod, f_q) + mstore(0x31e0, prod) + + prod := mulmod(mload(0x2f00), prod, f_q) + mstore(0x3200, prod) + + prod := mulmod(mload(0x2f60), prod, f_q) + mstore(0x3220, prod) + + prod := mulmod(mload(0x2f80), prod, f_q) + mstore(0x3240, prod) + + prod := mulmod(mload(0x2fe0), prod, f_q) + mstore(0x3260, prod) + + prod := mulmod(mload(0x3040), prod, f_q) + mstore(0x3280, prod) + + prod := mulmod(mload(0x2de0), prod, f_q) + mstore(0x32a0, prod) + + prod := mulmod(mload(0x30a0), prod, f_q) + mstore(0x32c0, prod) + + prod := mulmod(mload(0x3100), prod, f_q) + mstore(0x32e0, prod) + + prod := mulmod(mload(0x3120), prod, f_q) + mstore(0x3300, prod) + + } +mstore(0x3340, 32) +mstore(0x3360, 32) +mstore(0x3380, 32) +mstore(0x33a0, mload(0x3300)) +mstore(0x33c0, 21888242871839275222246405745257275088548364400416034343698204186575808495615) +mstore(0x33e0, 21888242871839275222246405745257275088548364400416034343698204186575808495617) +success := and(eq(staticcall(gas(), 0x5, 0x3340, 0xc0, 0x3320, 0x20), 1), success) +{ + + let inv := mload(0x3320) + let v + + v := mload(0x3120) + mstore(12576, mulmod(mload(0x32e0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x3100) + mstore(12544, mulmod(mload(0x32c0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x30a0) + mstore(12448, mulmod(mload(0x32a0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2de0) + mstore(11744, mulmod(mload(0x3280), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x3040) + mstore(12352, mulmod(mload(0x3260), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2fe0) + mstore(12256, mulmod(mload(0x3240), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2f80) + mstore(12160, mulmod(mload(0x3220), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2f60) + mstore(12128, mulmod(mload(0x3200), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2f00) + mstore(12032, mulmod(mload(0x31e0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2ea0) + mstore(11936, mulmod(mload(0x31c0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2dc0) + mstore(11712, mulmod(mload(0x31a0), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2e40) + mstore(11840, mulmod(mload(0x3180), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2da0) + mstore(11680, mulmod(mload(0x3160), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2d40) + mstore(11584, mulmod(mload(0x3140), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x2ce0) + mstore(11488, mulmod(mload(0x2c80), inv, f_q)) + inv := mulmod(v, inv, f_q) + mstore(0x2c80, inv) + + } +{ + let result := mload(0x2c80) +result := addmod(mload(0x2ce0), result, f_q) +result := addmod(mload(0x2d40), result, f_q) +result := addmod(mload(0x2da0), result, f_q) +mstore(13312, result) + } +mstore(0x3420, mulmod(mload(0x2e20), mload(0x2dc0), f_q)) +{ + let result := mload(0x2e40) +mstore(13376, result) + } +mstore(0x3460, mulmod(mload(0x2e20), mload(0x2f80), f_q)) +{ + let result := mload(0x2ea0) +result := addmod(mload(0x2f00), result, f_q) +result := addmod(mload(0x2f60), result, f_q) +mstore(13440, result) + } +mstore(0x34a0, mulmod(mload(0x2e20), mload(0x2de0), f_q)) +{ + let result := mload(0x2fe0) +result := addmod(mload(0x3040), result, f_q) +mstore(13504, result) + } +mstore(0x34e0, mulmod(mload(0x2e20), mload(0x3120), f_q)) +{ + let result := mload(0x30a0) +result := addmod(mload(0x3100), result, f_q) +mstore(13568, result) + } +{ + let prod := mload(0x3400) + + prod := mulmod(mload(0x3440), prod, f_q) + mstore(0x3520, prod) + + prod := mulmod(mload(0x3480), prod, f_q) + mstore(0x3540, prod) + + prod := mulmod(mload(0x34c0), prod, f_q) + mstore(0x3560, prod) + + prod := mulmod(mload(0x3500), prod, f_q) + mstore(0x3580, prod) + + } +mstore(0x35c0, 32) +mstore(0x35e0, 32) +mstore(0x3600, 32) +mstore(0x3620, mload(0x3580)) +mstore(0x3640, 21888242871839275222246405745257275088548364400416034343698204186575808495615) +mstore(0x3660, 21888242871839275222246405745257275088548364400416034343698204186575808495617) +success := and(eq(staticcall(gas(), 0x5, 0x35c0, 0xc0, 0x35a0, 0x20), 1), success) +{ + + let inv := mload(0x35a0) + let v + + v := mload(0x3500) + mstore(13568, mulmod(mload(0x3560), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x34c0) + mstore(13504, mulmod(mload(0x3540), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x3480) + mstore(13440, mulmod(mload(0x3520), inv, f_q)) + inv := mulmod(v, inv, f_q) + + v := mload(0x3440) + mstore(13376, mulmod(mload(0x3400), inv, f_q)) + inv := mulmod(v, inv, f_q) + mstore(0x3400, inv) + + } +mstore(0x3680, mulmod(mload(0x3420), mload(0x3440), f_q)) +mstore(0x36a0, mulmod(mload(0x3460), mload(0x3480), f_q)) +mstore(0x36c0, mulmod(mload(0x34a0), mload(0x34c0), f_q)) +mstore(0x36e0, mulmod(mload(0x34e0), mload(0x3500), f_q)) +mstore(0x3700, mulmod(mload(0xb60), mload(0xb60), f_q)) +mstore(0x3720, mulmod(mload(0x3700), mload(0xb60), f_q)) +mstore(0x3740, mulmod(mload(0x3720), mload(0xb60), f_q)) +mstore(0x3760, mulmod(mload(0x3740), mload(0xb60), f_q)) +mstore(0x3780, mulmod(mload(0x3760), mload(0xb60), f_q)) +mstore(0x37a0, mulmod(mload(0x3780), mload(0xb60), f_q)) +mstore(0x37c0, mulmod(mload(0x37a0), mload(0xb60), f_q)) +mstore(0x37e0, mulmod(mload(0x37c0), mload(0xb60), f_q)) +mstore(0x3800, mulmod(mload(0x37e0), mload(0xb60), f_q)) +mstore(0x3820, mulmod(mload(0x3800), mload(0xb60), f_q)) +mstore(0x3840, mulmod(mload(0x3820), mload(0xb60), f_q)) +mstore(0x3860, mulmod(mload(0x3840), mload(0xb60), f_q)) +mstore(0x3880, mulmod(mload(0xbc0), mload(0xbc0), f_q)) +mstore(0x38a0, mulmod(mload(0x3880), mload(0xbc0), f_q)) +mstore(0x38c0, mulmod(mload(0x38a0), mload(0xbc0), f_q)) +mstore(0x38e0, mulmod(mload(0x38c0), mload(0xbc0), f_q)) +{ + let result := mulmod(mload(0x740), mload(0x2c80), f_q) +result := addmod(mulmod(mload(0x760), mload(0x2ce0), f_q), result, f_q) +result := addmod(mulmod(mload(0x780), mload(0x2d40), f_q), result, f_q) +result := addmod(mulmod(mload(0x7a0), mload(0x2da0), f_q), result, f_q) +mstore(14592, result) + } +mstore(0x3920, mulmod(mload(0x3900), mload(0x3400), f_q)) +mstore(0x3940, mulmod(sub(f_q, mload(0x3920)), 1, f_q)) +{ + let result := mulmod(mload(0x7c0), mload(0x2c80), f_q) +result := addmod(mulmod(mload(0x7e0), mload(0x2ce0), f_q), result, f_q) +result := addmod(mulmod(mload(0x800), mload(0x2d40), f_q), result, f_q) +result := addmod(mulmod(mload(0x820), mload(0x2da0), f_q), result, f_q) +mstore(14688, result) + } +mstore(0x3980, mulmod(mload(0x3960), mload(0x3400), f_q)) +mstore(0x39a0, mulmod(sub(f_q, mload(0x3980)), mload(0xb60), f_q)) +mstore(0x39c0, mulmod(1, mload(0xb60), f_q)) +mstore(0x39e0, addmod(mload(0x3940), mload(0x39a0), f_q)) +mstore(0x3a00, mulmod(mload(0x39e0), 1, f_q)) +mstore(0x3a20, mulmod(mload(0x39c0), 1, f_q)) +mstore(0x3a40, mulmod(1, mload(0x3420), f_q)) +{ + let result := mulmod(mload(0x840), mload(0x2e40), f_q) +mstore(14944, result) + } +mstore(0x3a80, mulmod(mload(0x3a60), mload(0x3680), f_q)) +mstore(0x3aa0, mulmod(sub(f_q, mload(0x3a80)), 1, f_q)) +mstore(0x3ac0, mulmod(mload(0x3a40), 1, f_q)) +{ + let result := mulmod(mload(0xb20), mload(0x2e40), f_q) +mstore(15072, result) + } +mstore(0x3b00, mulmod(mload(0x3ae0), mload(0x3680), f_q)) +mstore(0x3b20, mulmod(sub(f_q, mload(0x3b00)), mload(0xb60), f_q)) +mstore(0x3b40, mulmod(mload(0x3a40), mload(0xb60), f_q)) +mstore(0x3b60, addmod(mload(0x3aa0), mload(0x3b20), f_q)) +{ + let result := mulmod(mload(0x860), mload(0x2e40), f_q) +mstore(15232, result) + } +mstore(0x3ba0, mulmod(mload(0x3b80), mload(0x3680), f_q)) +mstore(0x3bc0, mulmod(sub(f_q, mload(0x3ba0)), mload(0x3700), f_q)) +mstore(0x3be0, mulmod(mload(0x3a40), mload(0x3700), f_q)) +mstore(0x3c00, addmod(mload(0x3b60), mload(0x3bc0), f_q)) +{ + let result := mulmod(mload(0x880), mload(0x2e40), f_q) +mstore(15392, result) + } +mstore(0x3c40, mulmod(mload(0x3c20), mload(0x3680), f_q)) +mstore(0x3c60, mulmod(sub(f_q, mload(0x3c40)), mload(0x3720), f_q)) +mstore(0x3c80, mulmod(mload(0x3a40), mload(0x3720), f_q)) +mstore(0x3ca0, addmod(mload(0x3c00), mload(0x3c60), f_q)) +{ + let result := mulmod(mload(0x8a0), mload(0x2e40), f_q) +mstore(15552, result) + } +mstore(0x3ce0, mulmod(mload(0x3cc0), mload(0x3680), f_q)) +mstore(0x3d00, mulmod(sub(f_q, mload(0x3ce0)), mload(0x3740), f_q)) +mstore(0x3d20, mulmod(mload(0x3a40), mload(0x3740), f_q)) +mstore(0x3d40, addmod(mload(0x3ca0), mload(0x3d00), f_q)) +{ + let result := mulmod(mload(0x8c0), mload(0x2e40), f_q) +mstore(15712, result) + } +mstore(0x3d80, mulmod(mload(0x3d60), mload(0x3680), f_q)) +mstore(0x3da0, mulmod(sub(f_q, mload(0x3d80)), mload(0x3760), f_q)) +mstore(0x3dc0, mulmod(mload(0x3a40), mload(0x3760), f_q)) +mstore(0x3de0, addmod(mload(0x3d40), mload(0x3da0), f_q)) +{ + let result := mulmod(mload(0x900), mload(0x2e40), f_q) +mstore(15872, result) + } +mstore(0x3e20, mulmod(mload(0x3e00), mload(0x3680), f_q)) +mstore(0x3e40, mulmod(sub(f_q, mload(0x3e20)), mload(0x3780), f_q)) +mstore(0x3e60, mulmod(mload(0x3a40), mload(0x3780), f_q)) +mstore(0x3e80, addmod(mload(0x3de0), mload(0x3e40), f_q)) +{ + let result := mulmod(mload(0x920), mload(0x2e40), f_q) +mstore(16032, result) + } +mstore(0x3ec0, mulmod(mload(0x3ea0), mload(0x3680), f_q)) +mstore(0x3ee0, mulmod(sub(f_q, mload(0x3ec0)), mload(0x37a0), f_q)) +mstore(0x3f00, mulmod(mload(0x3a40), mload(0x37a0), f_q)) +mstore(0x3f20, addmod(mload(0x3e80), mload(0x3ee0), f_q)) +{ + let result := mulmod(mload(0x940), mload(0x2e40), f_q) +mstore(16192, result) + } +mstore(0x3f60, mulmod(mload(0x3f40), mload(0x3680), f_q)) +mstore(0x3f80, mulmod(sub(f_q, mload(0x3f60)), mload(0x37c0), f_q)) +mstore(0x3fa0, mulmod(mload(0x3a40), mload(0x37c0), f_q)) +mstore(0x3fc0, addmod(mload(0x3f20), mload(0x3f80), f_q)) +{ + let result := mulmod(mload(0x960), mload(0x2e40), f_q) +mstore(16352, result) + } +mstore(0x4000, mulmod(mload(0x3fe0), mload(0x3680), f_q)) +mstore(0x4020, mulmod(sub(f_q, mload(0x4000)), mload(0x37e0), f_q)) +mstore(0x4040, mulmod(mload(0x3a40), mload(0x37e0), f_q)) +mstore(0x4060, addmod(mload(0x3fc0), mload(0x4020), f_q)) +{ + let result := mulmod(mload(0x980), mload(0x2e40), f_q) +mstore(16512, result) + } +mstore(0x40a0, mulmod(mload(0x4080), mload(0x3680), f_q)) +mstore(0x40c0, mulmod(sub(f_q, mload(0x40a0)), mload(0x3800), f_q)) +mstore(0x40e0, mulmod(mload(0x3a40), mload(0x3800), f_q)) +mstore(0x4100, addmod(mload(0x4060), mload(0x40c0), f_q)) +mstore(0x4120, mulmod(mload(0x2a20), mload(0x3420), f_q)) +mstore(0x4140, mulmod(mload(0x2a40), mload(0x3420), f_q)) +{ + let result := mulmod(mload(0x2a60), mload(0x2e40), f_q) +mstore(16736, result) + } +mstore(0x4180, mulmod(mload(0x4160), mload(0x3680), f_q)) +mstore(0x41a0, mulmod(sub(f_q, mload(0x4180)), mload(0x3820), f_q)) +mstore(0x41c0, mulmod(mload(0x3a40), mload(0x3820), f_q)) +mstore(0x41e0, mulmod(mload(0x4120), mload(0x3820), f_q)) +mstore(0x4200, mulmod(mload(0x4140), mload(0x3820), f_q)) +mstore(0x4220, addmod(mload(0x4100), mload(0x41a0), f_q)) +{ + let result := mulmod(mload(0x8e0), mload(0x2e40), f_q) +mstore(16960, result) + } +mstore(0x4260, mulmod(mload(0x4240), mload(0x3680), f_q)) +mstore(0x4280, mulmod(sub(f_q, mload(0x4260)), mload(0x3840), f_q)) +mstore(0x42a0, mulmod(mload(0x3a40), mload(0x3840), f_q)) +mstore(0x42c0, addmod(mload(0x4220), mload(0x4280), f_q)) +mstore(0x42e0, mulmod(mload(0x42c0), mload(0xbc0), f_q)) +mstore(0x4300, mulmod(mload(0x3ac0), mload(0xbc0), f_q)) +mstore(0x4320, mulmod(mload(0x3b40), mload(0xbc0), f_q)) +mstore(0x4340, mulmod(mload(0x3be0), mload(0xbc0), f_q)) +mstore(0x4360, mulmod(mload(0x3c80), mload(0xbc0), f_q)) +mstore(0x4380, mulmod(mload(0x3d20), mload(0xbc0), f_q)) +mstore(0x43a0, mulmod(mload(0x3dc0), mload(0xbc0), f_q)) +mstore(0x43c0, mulmod(mload(0x3e60), mload(0xbc0), f_q)) +mstore(0x43e0, mulmod(mload(0x3f00), mload(0xbc0), f_q)) +mstore(0x4400, mulmod(mload(0x3fa0), mload(0xbc0), f_q)) +mstore(0x4420, mulmod(mload(0x4040), mload(0xbc0), f_q)) +mstore(0x4440, mulmod(mload(0x40e0), mload(0xbc0), f_q)) +mstore(0x4460, mulmod(mload(0x41c0), mload(0xbc0), f_q)) +mstore(0x4480, mulmod(mload(0x41e0), mload(0xbc0), f_q)) +mstore(0x44a0, mulmod(mload(0x4200), mload(0xbc0), f_q)) +mstore(0x44c0, mulmod(mload(0x42a0), mload(0xbc0), f_q)) +mstore(0x44e0, addmod(mload(0x3a00), mload(0x42e0), f_q)) +mstore(0x4500, mulmod(1, mload(0x3460), f_q)) +{ + let result := mulmod(mload(0x9a0), mload(0x2ea0), f_q) +result := addmod(mulmod(mload(0x9c0), mload(0x2f00), f_q), result, f_q) +result := addmod(mulmod(mload(0x9e0), mload(0x2f60), f_q), result, f_q) +mstore(17696, result) + } +mstore(0x4540, mulmod(mload(0x4520), mload(0x36a0), f_q)) +mstore(0x4560, mulmod(sub(f_q, mload(0x4540)), 1, f_q)) +mstore(0x4580, mulmod(mload(0x4500), 1, f_q)) +{ + let result := mulmod(mload(0xa00), mload(0x2ea0), f_q) +result := addmod(mulmod(mload(0xa20), mload(0x2f00), f_q), result, f_q) +result := addmod(mulmod(mload(0xa40), mload(0x2f60), f_q), result, f_q) +mstore(17824, result) + } +mstore(0x45c0, mulmod(mload(0x45a0), mload(0x36a0), f_q)) +mstore(0x45e0, mulmod(sub(f_q, mload(0x45c0)), mload(0xb60), f_q)) +mstore(0x4600, mulmod(mload(0x4500), mload(0xb60), f_q)) +mstore(0x4620, addmod(mload(0x4560), mload(0x45e0), f_q)) +mstore(0x4640, mulmod(mload(0x4620), mload(0x3880), f_q)) +mstore(0x4660, mulmod(mload(0x4580), mload(0x3880), f_q)) +mstore(0x4680, mulmod(mload(0x4600), mload(0x3880), f_q)) +mstore(0x46a0, addmod(mload(0x44e0), mload(0x4640), f_q)) +mstore(0x46c0, mulmod(1, mload(0x34a0), f_q)) +{ + let result := mulmod(mload(0xa60), mload(0x2fe0), f_q) +result := addmod(mulmod(mload(0xa80), mload(0x3040), f_q), result, f_q) +mstore(18144, result) + } +mstore(0x4700, mulmod(mload(0x46e0), mload(0x36c0), f_q)) +mstore(0x4720, mulmod(sub(f_q, mload(0x4700)), 1, f_q)) +mstore(0x4740, mulmod(mload(0x46c0), 1, f_q)) +{ + let result := mulmod(mload(0xaa0), mload(0x2fe0), f_q) +result := addmod(mulmod(mload(0xac0), mload(0x3040), f_q), result, f_q) +mstore(18272, result) + } +mstore(0x4780, mulmod(mload(0x4760), mload(0x36c0), f_q)) +mstore(0x47a0, mulmod(sub(f_q, mload(0x4780)), mload(0xb60), f_q)) +mstore(0x47c0, mulmod(mload(0x46c0), mload(0xb60), f_q)) +mstore(0x47e0, addmod(mload(0x4720), mload(0x47a0), f_q)) +mstore(0x4800, mulmod(mload(0x47e0), mload(0x38a0), f_q)) +mstore(0x4820, mulmod(mload(0x4740), mload(0x38a0), f_q)) +mstore(0x4840, mulmod(mload(0x47c0), mload(0x38a0), f_q)) +mstore(0x4860, addmod(mload(0x46a0), mload(0x4800), f_q)) +mstore(0x4880, mulmod(1, mload(0x34e0), f_q)) +{ + let result := mulmod(mload(0xae0), mload(0x30a0), f_q) +result := addmod(mulmod(mload(0xb00), mload(0x3100), f_q), result, f_q) +mstore(18592, result) + } +mstore(0x48c0, mulmod(mload(0x48a0), mload(0x36e0), f_q)) +mstore(0x48e0, mulmod(sub(f_q, mload(0x48c0)), 1, f_q)) +mstore(0x4900, mulmod(mload(0x4880), 1, f_q)) +mstore(0x4920, mulmod(mload(0x48e0), mload(0x38c0), f_q)) +mstore(0x4940, mulmod(mload(0x4900), mload(0x38c0), f_q)) +mstore(0x4960, addmod(mload(0x4860), mload(0x4920), f_q)) +mstore(0x4980, mulmod(1, mload(0x2e20), f_q)) +mstore(0x49a0, mulmod(1, mload(0xc60), f_q)) +mstore(0x49c0, 0x0000000000000000000000000000000000000000000000000000000000000001) + mstore(0x49e0, 0x0000000000000000000000000000000000000000000000000000000000000002) +mstore(0x4a00, mload(0x4960)) +success := and(eq(staticcall(gas(), 0x7, 0x49c0, 0x60, 0x49c0, 0x40), 1), success) +mstore(0x4a20, mload(0x49c0)) + mstore(0x4a40, mload(0x49e0)) +mstore(0x4a60, mload(0x220)) + mstore(0x4a80, mload(0x240)) +success := and(eq(staticcall(gas(), 0x6, 0x4a20, 0x80, 0x4a20, 0x40), 1), success) +mstore(0x4aa0, mload(0x260)) + mstore(0x4ac0, mload(0x280)) +mstore(0x4ae0, mload(0x3a20)) +success := and(eq(staticcall(gas(), 0x7, 0x4aa0, 0x60, 0x4aa0, 0x40), 1), success) +mstore(0x4b00, mload(0x4a20)) + mstore(0x4b20, mload(0x4a40)) +mstore(0x4b40, mload(0x4aa0)) + mstore(0x4b60, mload(0x4ac0)) +success := and(eq(staticcall(gas(), 0x6, 0x4b00, 0x80, 0x4b00, 0x40), 1), success) +mstore(0x4b80, mload(0x2a0)) + mstore(0x4ba0, mload(0x2c0)) +mstore(0x4bc0, mload(0x4300)) +success := and(eq(staticcall(gas(), 0x7, 0x4b80, 0x60, 0x4b80, 0x40), 1), success) +mstore(0x4be0, mload(0x4b00)) + mstore(0x4c00, mload(0x4b20)) +mstore(0x4c20, mload(0x4b80)) + mstore(0x4c40, mload(0x4ba0)) +success := and(eq(staticcall(gas(), 0x6, 0x4be0, 0x80, 0x4be0, 0x40), 1), success) +mstore(0x4c60, mload(0x380)) + mstore(0x4c80, mload(0x3a0)) +mstore(0x4ca0, mload(0x4320)) +success := and(eq(staticcall(gas(), 0x7, 0x4c60, 0x60, 0x4c60, 0x40), 1), success) +mstore(0x4cc0, mload(0x4be0)) + mstore(0x4ce0, mload(0x4c00)) +mstore(0x4d00, mload(0x4c60)) + mstore(0x4d20, mload(0x4c80)) +success := and(eq(staticcall(gas(), 0x6, 0x4cc0, 0x80, 0x4cc0, 0x40), 1), success) +mstore(0x4d40, 0x0a56bb24bdbd10b2ae380a0f6d2926afe21e55ef423d664a7093bdc47d7a970d) + mstore(0x4d60, 0x3046067f3fbc66fb8322b30a454654489ad23370423a63caeab071e10143c65d) +mstore(0x4d80, mload(0x4340)) +success := and(eq(staticcall(gas(), 0x7, 0x4d40, 0x60, 0x4d40, 0x40), 1), success) +mstore(0x4da0, mload(0x4cc0)) + mstore(0x4dc0, mload(0x4ce0)) +mstore(0x4de0, mload(0x4d40)) + mstore(0x4e00, mload(0x4d60)) +success := and(eq(staticcall(gas(), 0x6, 0x4da0, 0x80, 0x4da0, 0x40), 1), success) +mstore(0x4e20, 0x165f42d12623508ec09f1a14ffe3841e636362840bcfe45fd4f0847a50968d91) + mstore(0x4e40, 0x19664a50abfa10f51e0eb96bf39b959cd2ebd0ed52c60bc0d4e8535272a13ed9) +mstore(0x4e60, mload(0x4360)) +success := and(eq(staticcall(gas(), 0x7, 0x4e20, 0x60, 0x4e20, 0x40), 1), success) +mstore(0x4e80, mload(0x4da0)) + mstore(0x4ea0, mload(0x4dc0)) +mstore(0x4ec0, mload(0x4e20)) + mstore(0x4ee0, mload(0x4e40)) +success := and(eq(staticcall(gas(), 0x6, 0x4e80, 0x80, 0x4e80, 0x40), 1), success) +mstore(0x4f00, 0x0c7dc4e4516515f0050b10e6891a60f39ab7645bbf2134080574b9ae26a3fee2) + mstore(0x4f20, 0x2ee3484a156715514bcc56f95e316bb23031b7460f679ebb427a7f8ad73aead2) +mstore(0x4f40, mload(0x4380)) +success := and(eq(staticcall(gas(), 0x7, 0x4f00, 0x60, 0x4f00, 0x40), 1), success) +mstore(0x4f60, mload(0x4e80)) + mstore(0x4f80, mload(0x4ea0)) +mstore(0x4fa0, mload(0x4f00)) + mstore(0x4fc0, mload(0x4f20)) +success := and(eq(staticcall(gas(), 0x6, 0x4f60, 0x80, 0x4f60, 0x40), 1), success) +mstore(0x4fe0, 0x2fb1bc5dc1a8a163ac673f110c7ced2581955a8d47770fced15a66d8199a5c91) + mstore(0x5000, 0x18f7802cf51055b658637bf93f53fcc4dbe4218c03cb54c9d3e74534e1b9cb8f) +mstore(0x5020, mload(0x43a0)) +success := and(eq(staticcall(gas(), 0x7, 0x4fe0, 0x60, 0x4fe0, 0x40), 1), success) +mstore(0x5040, mload(0x4f60)) + mstore(0x5060, mload(0x4f80)) +mstore(0x5080, mload(0x4fe0)) + mstore(0x50a0, mload(0x5000)) +success := and(eq(staticcall(gas(), 0x6, 0x5040, 0x80, 0x5040, 0x40), 1), success) +mstore(0x50c0, 0x2051ae2329a00ab4684564c9db909204379c6404686b9bb004253a0e87937c1a) + mstore(0x50e0, 0x2228d27991956786c7b7ed829027a4268a8f57d342e507683aaaea7046a1721b) +mstore(0x5100, mload(0x43c0)) +success := and(eq(staticcall(gas(), 0x7, 0x50c0, 0x60, 0x50c0, 0x40), 1), success) +mstore(0x5120, mload(0x5040)) + mstore(0x5140, mload(0x5060)) +mstore(0x5160, mload(0x50c0)) + mstore(0x5180, mload(0x50e0)) +success := and(eq(staticcall(gas(), 0x6, 0x5120, 0x80, 0x5120, 0x40), 1), success) +mstore(0x51a0, 0x144e8b5cd066532d7a019f3061d407aeb922b3a37125d39cee71a336088a8d57) + mstore(0x51c0, 0x0465b8271620ef2988dbb05e0e32f58c14ee4aaec69263d36175afc35b129dc8) +mstore(0x51e0, mload(0x43e0)) +success := and(eq(staticcall(gas(), 0x7, 0x51a0, 0x60, 0x51a0, 0x40), 1), success) +mstore(0x5200, mload(0x5120)) + mstore(0x5220, mload(0x5140)) +mstore(0x5240, mload(0x51a0)) + mstore(0x5260, mload(0x51c0)) +success := and(eq(staticcall(gas(), 0x6, 0x5200, 0x80, 0x5200, 0x40), 1), success) +mstore(0x5280, 0x2c5cb6e96533664432584b4373fc01286cb8aa2c8a7f05eac98fc5bc689e65bf) + mstore(0x52a0, 0x2c6a00e02442db4548c0583842d7c460dfaba5a8ae3d86ca57b0d7c82d7090c8) +mstore(0x52c0, mload(0x4400)) +success := and(eq(staticcall(gas(), 0x7, 0x5280, 0x60, 0x5280, 0x40), 1), success) +mstore(0x52e0, mload(0x5200)) + mstore(0x5300, mload(0x5220)) +mstore(0x5320, mload(0x5280)) + mstore(0x5340, mload(0x52a0)) +success := and(eq(staticcall(gas(), 0x6, 0x52e0, 0x80, 0x52e0, 0x40), 1), success) +mstore(0x5360, 0x2b737ba20cacc46db1394cb36a1cb92566946b943314b7037d038fbb83f233a8) + mstore(0x5380, 0x04dc42ddd6eb4c1c43a1175bc70c5b5c92577f968055708b4beeb22cea5cff99) +mstore(0x53a0, mload(0x4420)) +success := and(eq(staticcall(gas(), 0x7, 0x5360, 0x60, 0x5360, 0x40), 1), success) +mstore(0x53c0, mload(0x52e0)) + mstore(0x53e0, mload(0x5300)) +mstore(0x5400, mload(0x5360)) + mstore(0x5420, mload(0x5380)) +success := and(eq(staticcall(gas(), 0x6, 0x53c0, 0x80, 0x53c0, 0x40), 1), success) +mstore(0x5440, 0x0ff2ba345398269313967c25483b19e5e2de27f76a3a4357408c35dc42ddfec3) + mstore(0x5460, 0x063d5c171abc02e7d09324a4f1bb6493d0584767678901f452ebc7f285037015) +mstore(0x5480, mload(0x4440)) +success := and(eq(staticcall(gas(), 0x7, 0x5440, 0x60, 0x5440, 0x40), 1), success) +mstore(0x54a0, mload(0x53c0)) + mstore(0x54c0, mload(0x53e0)) +mstore(0x54e0, mload(0x5440)) + mstore(0x5500, mload(0x5460)) +success := and(eq(staticcall(gas(), 0x6, 0x54a0, 0x80, 0x54a0, 0x40), 1), success) +mstore(0x5520, mload(0x620)) + mstore(0x5540, mload(0x640)) +mstore(0x5560, mload(0x4460)) +success := and(eq(staticcall(gas(), 0x7, 0x5520, 0x60, 0x5520, 0x40), 1), success) +mstore(0x5580, mload(0x54a0)) + mstore(0x55a0, mload(0x54c0)) +mstore(0x55c0, mload(0x5520)) + mstore(0x55e0, mload(0x5540)) +success := and(eq(staticcall(gas(), 0x6, 0x5580, 0x80, 0x5580, 0x40), 1), success) +mstore(0x5600, mload(0x660)) + mstore(0x5620, mload(0x680)) +mstore(0x5640, mload(0x4480)) +success := and(eq(staticcall(gas(), 0x7, 0x5600, 0x60, 0x5600, 0x40), 1), success) +mstore(0x5660, mload(0x5580)) + mstore(0x5680, mload(0x55a0)) +mstore(0x56a0, mload(0x5600)) + mstore(0x56c0, mload(0x5620)) +success := and(eq(staticcall(gas(), 0x6, 0x5660, 0x80, 0x5660, 0x40), 1), success) +mstore(0x56e0, mload(0x6a0)) + mstore(0x5700, mload(0x6c0)) +mstore(0x5720, mload(0x44a0)) +success := and(eq(staticcall(gas(), 0x7, 0x56e0, 0x60, 0x56e0, 0x40), 1), success) +mstore(0x5740, mload(0x5660)) + mstore(0x5760, mload(0x5680)) +mstore(0x5780, mload(0x56e0)) + mstore(0x57a0, mload(0x5700)) +success := and(eq(staticcall(gas(), 0x6, 0x5740, 0x80, 0x5740, 0x40), 1), success) +mstore(0x57c0, mload(0x580)) + mstore(0x57e0, mload(0x5a0)) +mstore(0x5800, mload(0x44c0)) +success := and(eq(staticcall(gas(), 0x7, 0x57c0, 0x60, 0x57c0, 0x40), 1), success) +mstore(0x5820, mload(0x5740)) + mstore(0x5840, mload(0x5760)) +mstore(0x5860, mload(0x57c0)) + mstore(0x5880, mload(0x57e0)) +success := and(eq(staticcall(gas(), 0x6, 0x5820, 0x80, 0x5820, 0x40), 1), success) +mstore(0x58a0, mload(0x480)) + mstore(0x58c0, mload(0x4a0)) +mstore(0x58e0, mload(0x4660)) +success := and(eq(staticcall(gas(), 0x7, 0x58a0, 0x60, 0x58a0, 0x40), 1), success) +mstore(0x5900, mload(0x5820)) + mstore(0x5920, mload(0x5840)) +mstore(0x5940, mload(0x58a0)) + mstore(0x5960, mload(0x58c0)) +success := and(eq(staticcall(gas(), 0x6, 0x5900, 0x80, 0x5900, 0x40), 1), success) +mstore(0x5980, mload(0x4c0)) + mstore(0x59a0, mload(0x4e0)) +mstore(0x59c0, mload(0x4680)) +success := and(eq(staticcall(gas(), 0x7, 0x5980, 0x60, 0x5980, 0x40), 1), success) +mstore(0x59e0, mload(0x5900)) + mstore(0x5a00, mload(0x5920)) +mstore(0x5a20, mload(0x5980)) + mstore(0x5a40, mload(0x59a0)) +success := and(eq(staticcall(gas(), 0x6, 0x59e0, 0x80, 0x59e0, 0x40), 1), success) +mstore(0x5a60, mload(0x500)) + mstore(0x5a80, mload(0x520)) +mstore(0x5aa0, mload(0x4820)) +success := and(eq(staticcall(gas(), 0x7, 0x5a60, 0x60, 0x5a60, 0x40), 1), success) +mstore(0x5ac0, mload(0x59e0)) + mstore(0x5ae0, mload(0x5a00)) +mstore(0x5b00, mload(0x5a60)) + mstore(0x5b20, mload(0x5a80)) +success := and(eq(staticcall(gas(), 0x6, 0x5ac0, 0x80, 0x5ac0, 0x40), 1), success) +mstore(0x5b40, mload(0x540)) + mstore(0x5b60, mload(0x560)) +mstore(0x5b80, mload(0x4840)) +success := and(eq(staticcall(gas(), 0x7, 0x5b40, 0x60, 0x5b40, 0x40), 1), success) +mstore(0x5ba0, mload(0x5ac0)) + mstore(0x5bc0, mload(0x5ae0)) +mstore(0x5be0, mload(0x5b40)) + mstore(0x5c00, mload(0x5b60)) +success := and(eq(staticcall(gas(), 0x6, 0x5ba0, 0x80, 0x5ba0, 0x40), 1), success) +mstore(0x5c20, mload(0x340)) + mstore(0x5c40, mload(0x360)) +mstore(0x5c60, mload(0x4940)) +success := and(eq(staticcall(gas(), 0x7, 0x5c20, 0x60, 0x5c20, 0x40), 1), success) +mstore(0x5c80, mload(0x5ba0)) + mstore(0x5ca0, mload(0x5bc0)) +mstore(0x5cc0, mload(0x5c20)) + mstore(0x5ce0, mload(0x5c40)) +success := and(eq(staticcall(gas(), 0x6, 0x5c80, 0x80, 0x5c80, 0x40), 1), success) +mstore(0x5d00, mload(0xc00)) + mstore(0x5d20, mload(0xc20)) +mstore(0x5d40, sub(f_q, mload(0x4980))) +success := and(eq(staticcall(gas(), 0x7, 0x5d00, 0x60, 0x5d00, 0x40), 1), success) +mstore(0x5d60, mload(0x5c80)) + mstore(0x5d80, mload(0x5ca0)) +mstore(0x5da0, mload(0x5d00)) + mstore(0x5dc0, mload(0x5d20)) +success := and(eq(staticcall(gas(), 0x6, 0x5d60, 0x80, 0x5d60, 0x40), 1), success) +mstore(0x5de0, mload(0xca0)) + mstore(0x5e00, mload(0xcc0)) +mstore(0x5e20, mload(0x49a0)) +success := and(eq(staticcall(gas(), 0x7, 0x5de0, 0x60, 0x5de0, 0x40), 1), success) +mstore(0x5e40, mload(0x5d60)) + mstore(0x5e60, mload(0x5d80)) +mstore(0x5e80, mload(0x5de0)) + mstore(0x5ea0, mload(0x5e00)) +success := and(eq(staticcall(gas(), 0x6, 0x5e40, 0x80, 0x5e40, 0x40), 1), success) +mstore(0x5ec0, mload(0x5e40)) + mstore(0x5ee0, mload(0x5e60)) +mstore(0x5f00, mload(0xca0)) + mstore(0x5f20, mload(0xcc0)) +mstore(0x5f40, mload(0xce0)) + mstore(0x5f60, mload(0xd00)) +mstore(0x5f80, mload(0xd20)) + mstore(0x5fa0, mload(0xd40)) +mstore(0x5fc0, keccak256(0x5ec0, 256)) +mstore(24544, mod(mload(24512), f_q)) +mstore(0x6000, mulmod(mload(0x5fe0), mload(0x5fe0), f_q)) +mstore(0x6020, mulmod(1, mload(0x5fe0), f_q)) +mstore(0x6040, mload(0x5f40)) + mstore(0x6060, mload(0x5f60)) +mstore(0x6080, mload(0x6020)) +success := and(eq(staticcall(gas(), 0x7, 0x6040, 0x60, 0x6040, 0x40), 1), success) +mstore(0x60a0, mload(0x5ec0)) + mstore(0x60c0, mload(0x5ee0)) +mstore(0x60e0, mload(0x6040)) + mstore(0x6100, mload(0x6060)) +success := and(eq(staticcall(gas(), 0x6, 0x60a0, 0x80, 0x60a0, 0x40), 1), success) +mstore(0x6120, mload(0x5f80)) + mstore(0x6140, mload(0x5fa0)) +mstore(0x6160, mload(0x6020)) +success := and(eq(staticcall(gas(), 0x7, 0x6120, 0x60, 0x6120, 0x40), 1), success) +mstore(0x6180, mload(0x5f00)) + mstore(0x61a0, mload(0x5f20)) +mstore(0x61c0, mload(0x6120)) + mstore(0x61e0, mload(0x6140)) +success := and(eq(staticcall(gas(), 0x6, 0x6180, 0x80, 0x6180, 0x40), 1), success) +mstore(0x6200, mload(0x60a0)) + mstore(0x6220, mload(0x60c0)) +mstore(0x6240, 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2) + mstore(0x6260, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed) + mstore(0x6280, 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b) + mstore(0x62a0, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa) +mstore(0x62c0, mload(0x6180)) + mstore(0x62e0, mload(0x61a0)) +mstore(0x6300, 0x138d5863615c12d3bd7d3fd007776d281a337f9d7f6dce23532100bb4bb5839d) + mstore(0x6320, 0x0a3bb881671ee4e9238366e87f6598f0de356372ed3dc870766ec8ac005211e4) + mstore(0x6340, 0x19c9d7d9c6e7ad2d9a0d5847ebdd2687c668939a202553ded2760d3eb8dbf559) + mstore(0x6360, 0x198adb441818c42721c88c532ed13a5da1ebb78b85574d0b7326d8e6f4c1e25a) +success := and(eq(staticcall(gas(), 0x8, 0x6200, 0x180, 0x6200, 0x20), 1), success) +success := and(eq(mload(0x6200), 1), success) + + // Revert if anything fails + if iszero(success) { revert(0, 0) } + + // Return empty bytes on success + return(0, 0) + + } + } +} + \ No newline at end of file diff --git a/snark-verifier-sdk/examples/k_as_witness.rs b/snark-verifier-sdk/examples/k_as_witness.rs new file mode 100644 index 00000000..3561447f --- /dev/null +++ b/snark-verifier-sdk/examples/k_as_witness.rs @@ -0,0 +1,187 @@ +use halo2_base::gates::circuit::CircuitBuilderStage; +use halo2_base::halo2_proofs; +use halo2_base::halo2_proofs::arithmetic::Field; +use halo2_base::halo2_proofs::halo2curves::bn256::Fr; +use halo2_base::halo2_proofs::poly::commitment::Params; +use halo2_base::utils::fs::gen_srs; +use halo2_proofs::halo2curves as halo2_curves; + +use rand::rngs::StdRng; +use rand::SeedableRng; +use snark_verifier_sdk::halo2::aggregation::{AggregationConfigParams, VerifierUniversality}; +use snark_verifier_sdk::SHPLONK; +use snark_verifier_sdk::{ + gen_pk, + halo2::{aggregation::AggregationCircuit, gen_snark_shplonk}, + Snark, +}; + +mod application { + use super::halo2_curves::bn256::Fr; + use super::halo2_proofs::{ + circuit::{Layouter, SimpleFloorPlanner, Value}, + plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, Instance}, + poly::Rotation, + }; + + use snark_verifier_sdk::CircuitExt; + + #[derive(Clone, Copy)] + pub struct StandardPlonkConfig { + a: Column, + b: Column, + c: Column, + q_a: Column, + q_b: Column, + q_c: Column, + q_ab: Column, + constant: Column, + #[allow(dead_code)] + instance: Column, + } + + impl StandardPlonkConfig { + fn configure(meta: &mut ConstraintSystem) -> Self { + let [a, b, c] = [(); 3].map(|_| meta.advice_column()); + let [q_a, q_b, q_c, q_ab, constant] = [(); 5].map(|_| meta.fixed_column()); + let instance = meta.instance_column(); + + [a, b, c].map(|column| meta.enable_equality(column)); + + meta.create_gate( + "q_a·a + q_b·b + q_c·c + q_ab·a·b + constant + instance = 0", + |meta| { + let [a, b, c] = + [a, b, c].map(|column| meta.query_advice(column, Rotation::cur())); + let [q_a, q_b, q_c, q_ab, constant] = [q_a, q_b, q_c, q_ab, constant] + .map(|column| meta.query_fixed(column, Rotation::cur())); + let instance = meta.query_instance(instance, Rotation::cur()); + Some( + q_a * a.clone() + + q_b * b.clone() + + q_c * c + + q_ab * a * b + + constant + + instance, + ) + }, + ); + + StandardPlonkConfig { a, b, c, q_a, q_b, q_c, q_ab, constant, instance } + } + } + + #[derive(Clone)] + pub struct StandardPlonk(pub Fr, pub usize); + + impl CircuitExt for StandardPlonk { + fn num_instance(&self) -> Vec { + vec![1] + } + + fn instances(&self) -> Vec> { + vec![vec![self.0]] + } + } + + impl Circuit for StandardPlonk { + type Config = StandardPlonkConfig; + type FloorPlanner = SimpleFloorPlanner; + + fn without_witnesses(&self) -> Self { + Self(Fr::zero(), self.1) + } + + fn configure(meta: &mut ConstraintSystem) -> Self::Config { + meta.set_minimum_degree(4); + StandardPlonkConfig::configure(meta) + } + + fn synthesize( + &self, + config: Self::Config, + mut layouter: impl Layouter, + ) -> Result<(), Error> { + layouter.assign_region( + || "", + |mut region| { + region.assign_advice(config.a, 0, Value::known(self.0)); + region.assign_fixed(config.q_a, 0, -Fr::one()); + region.assign_advice(config.a, 1, Value::known(-Fr::from(5u64))); + for (idx, column) in (1..).zip([ + config.q_a, + config.q_b, + config.q_c, + config.q_ab, + config.constant, + ]) { + region.assign_fixed(column, 1, Fr::from(idx as u64)); + } + let a = region.assign_advice(config.a, 2, Value::known(Fr::one())); + a.copy_advice(&mut region, config.b, 3); + a.copy_advice(&mut region, config.c, 4); + + // assuming <= 10 blinding factors + // fill in most of circuit with a computation + let n = self.1; + for offset in 5..n - 10 { + region.assign_advice(config.a, offset, Value::known(-Fr::from(5u64))); + for (idx, column) in (1..).zip([ + config.q_a, + config.q_b, + config.q_c, + config.q_ab, + config.constant, + ]) { + region.assign_fixed(column, offset, Fr::from(idx as u64)); + } + } + + Ok(()) + }, + ) + } + } +} + +fn gen_application_snark(k: u32) -> Snark { + let rng = StdRng::seed_from_u64(0); + let params = gen_srs(k); + let circuit = application::StandardPlonk(Fr::random(rng), params.n() as usize); + + let pk = gen_pk(¶ms, &circuit, None); + gen_snark_shplonk(¶ms, &pk, circuit, None::<&str>) +} + +fn main() { + let dummy_snark = gen_application_snark(8); + + let k = 15u32; + let params = gen_srs(k); + let lookup_bits = k as usize - 1; + let mut agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + AggregationConfigParams { degree: k, lookup_bits, ..Default::default() }, + ¶ms, + vec![dummy_snark], + VerifierUniversality::Full, + ); + let agg_config = agg_circuit.calculate_params(Some(10)); + + let pk = gen_pk(¶ms, &agg_circuit, None); + let break_points = agg_circuit.break_points(); + + let snarks = [8, 12, 15, 20].map(|k| (k, gen_application_snark(k))); + for (k, snark) in snarks { + let agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Prover, + agg_config, + ¶ms, + vec![snark], + VerifierUniversality::Full, + ) + .use_break_points(break_points.clone()); + let _snark = gen_snark_shplonk(¶ms, &pk, agg_circuit, None::<&str>); + println!("snark with k = {k} success"); + } +} diff --git a/snark-verifier-sdk/examples/range_check.rs b/snark-verifier-sdk/examples/range_check.rs new file mode 100644 index 00000000..2beb5a78 --- /dev/null +++ b/snark-verifier-sdk/examples/range_check.rs @@ -0,0 +1,76 @@ +use ark_std::{end_timer, start_timer}; +use halo2_base::gates::circuit::builder::BaseCircuitBuilder; +use halo2_base::gates::circuit::{BaseCircuitParams, CircuitBuilderStage}; +use halo2_base::gates::{GateInstructions, RangeInstructions}; +use halo2_base::halo2_proofs::halo2curves::bn256::Fr; +use halo2_base::utils::fs::gen_srs; + +use itertools::Itertools; +use snark_verifier_sdk::halo2::aggregation::{AggregationConfigParams, VerifierUniversality}; +use snark_verifier_sdk::SHPLONK; +use snark_verifier_sdk::{ + gen_pk, + halo2::{aggregation::AggregationCircuit, gen_snark_shplonk}, + Snark, +}; + +fn generate_circuit(k: u32) -> Snark { + let lookup_bits = k as usize - 1; + let circuit_params = BaseCircuitParams { + k: k as usize, + num_advice_per_phase: vec![10], + num_lookup_advice_per_phase: vec![5], + num_fixed: 1, + lookup_bits: Some(lookup_bits), + num_instance_columns: 1, + }; + let mut builder = BaseCircuitBuilder::new(false).use_params(circuit_params); + let range = builder.range_chip(); + + let ctx = builder.main(0); + + let x = ctx.load_witness(Fr::from(14)); + range.range_check(ctx, x, 2 * lookup_bits + 1); + range.gate().add(ctx, x, x); + + let params = gen_srs(k); + // do not call calculate_params, we want to use fixed params + let pk = gen_pk(¶ms, &builder, None); + // builder now has break_point set + gen_snark_shplonk(¶ms, &pk, builder, None::<&str>) +} + +fn main() { + let dummy_snark = generate_circuit(9); + + let k = 14u32; + let lookup_bits = k as usize - 1; + let params = gen_srs(k); + let mut agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + AggregationConfigParams { degree: k, lookup_bits, ..Default::default() }, + ¶ms, + vec![dummy_snark], + VerifierUniversality::Full, + ); + let agg_config = agg_circuit.calculate_params(Some(10)); + + let start0 = start_timer!(|| "gen vk & pk"); + let pk = gen_pk(¶ms, &agg_circuit, None); + end_timer!(start0); + let break_points = agg_circuit.break_points(); + + let snarks = (10..16).map(generate_circuit).collect_vec(); + for (i, snark) in snarks.into_iter().enumerate() { + let agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Prover, + agg_config, + ¶ms, + vec![snark], + VerifierUniversality::Full, + ) + .use_break_points(break_points.clone()); + let _snark = gen_snark_shplonk(¶ms, &pk, agg_circuit, None::<&str>); + println!("snark {i} success"); + } +} diff --git a/snark-verifier-sdk/examples/standard_plonk.rs b/snark-verifier-sdk/examples/standard_plonk.rs new file mode 100644 index 00000000..fb0e17c1 --- /dev/null +++ b/snark-verifier-sdk/examples/standard_plonk.rs @@ -0,0 +1,219 @@ +use std::path::Path; + +use halo2_base::gates::circuit::CircuitBuilderStage; +use halo2_base::halo2_proofs; +use halo2_base::utils::fs::gen_srs; +use halo2_proofs::halo2curves as halo2_curves; +use halo2_proofs::{halo2curves::bn256::Bn256, poly::kzg::commitment::ParamsKZG}; +use rand::rngs::OsRng; +#[cfg(feature = "revm")] +use snark_verifier_sdk::evm::evm_verify; +use snark_verifier_sdk::evm::{gen_evm_proof_shplonk, gen_evm_verifier_shplonk}; +use snark_verifier_sdk::halo2::aggregation::{AggregationConfigParams, VerifierUniversality}; +use snark_verifier_sdk::{ + gen_pk, + halo2::{aggregation::AggregationCircuit, gen_snark_shplonk}, + Snark, +}; +use snark_verifier_sdk::{CircuitExt, SHPLONK}; + +mod application { + use super::halo2_curves::bn256::Fr; + use super::halo2_proofs::{ + circuit::{Layouter, SimpleFloorPlanner, Value}, + plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, Instance}, + poly::Rotation, + }; + use rand::RngCore; + use snark_verifier_sdk::CircuitExt; + + #[derive(Clone, Copy)] + pub struct StandardPlonkConfig { + a: Column, + b: Column, + c: Column, + q_a: Column, + q_b: Column, + q_c: Column, + q_ab: Column, + constant: Column, + #[allow(dead_code)] + instance: Column, + } + + impl StandardPlonkConfig { + fn configure(meta: &mut ConstraintSystem) -> Self { + let [a, b, c] = [(); 3].map(|_| meta.advice_column()); + let [q_a, q_b, q_c, q_ab, constant] = [(); 5].map(|_| meta.fixed_column()); + let instance = meta.instance_column(); + + [a, b, c].map(|column| meta.enable_equality(column)); + + meta.create_gate( + "q_a·a + q_b·b + q_c·c + q_ab·a·b + constant + instance = 0", + |meta| { + let [a, b, c] = + [a, b, c].map(|column| meta.query_advice(column, Rotation::cur())); + let [q_a, q_b, q_c, q_ab, constant] = [q_a, q_b, q_c, q_ab, constant] + .map(|column| meta.query_fixed(column, Rotation::cur())); + let instance = meta.query_instance(instance, Rotation::cur()); + Some( + q_a * a.clone() + + q_b * b.clone() + + q_c * c + + q_ab * a * b + + constant + + instance, + ) + }, + ); + + StandardPlonkConfig { a, b, c, q_a, q_b, q_c, q_ab, constant, instance } + } + } + + #[derive(Clone, Default)] + pub struct StandardPlonk(Fr); + + impl StandardPlonk { + pub fn rand(mut rng: R) -> Self { + Self(Fr::from(rng.next_u32() as u64)) + } + } + + impl CircuitExt for StandardPlonk { + fn num_instance(&self) -> Vec { + vec![1] + } + + fn instances(&self) -> Vec> { + vec![vec![self.0]] + } + } + + impl Circuit for StandardPlonk { + type Config = StandardPlonkConfig; + type FloorPlanner = SimpleFloorPlanner; + + fn without_witnesses(&self) -> Self { + Self::default() + } + + fn configure(meta: &mut ConstraintSystem) -> Self::Config { + meta.set_minimum_degree(4); + StandardPlonkConfig::configure(meta) + } + + fn synthesize( + &self, + config: Self::Config, + mut layouter: impl Layouter, + ) -> Result<(), Error> { + layouter.assign_region( + || "", + |mut region| { + #[cfg(feature = "halo2-pse")] + { + region.assign_advice(|| "", config.a, 0, || Value::known(self.0))?; + region.assign_fixed(|| "", config.q_a, 0, || Value::known(-Fr::one()))?; + region.assign_advice( + || "", + config.a, + 1, + || Value::known(-Fr::from(5u64)), + )?; + for (idx, column) in (1..).zip([ + config.q_a, + config.q_b, + config.q_c, + config.q_ab, + config.constant, + ]) { + region.assign_fixed( + || "", + column, + 1, + || Value::known(Fr::from(idx as u64)), + )?; + } + let a = + region.assign_advice(|| "", config.a, 2, || Value::known(Fr::one()))?; + a.copy_advice(|| "", &mut region, config.b, 3)?; + a.copy_advice(|| "", &mut region, config.c, 4)?; + } + #[cfg(feature = "halo2-axiom")] + { + region.assign_advice(config.a, 0, Value::known(self.0)); + region.assign_fixed(config.q_a, 0, -Fr::one()); + region.assign_advice(config.a, 1, Value::known(-Fr::from(5u64))); + for (idx, column) in (1..).zip([ + config.q_a, + config.q_b, + config.q_c, + config.q_ab, + config.constant, + ]) { + region.assign_fixed(column, 1, Fr::from(idx as u64)); + } + + let a = region.assign_advice(config.a, 2, Value::known(Fr::one())); + a.copy_advice(&mut region, config.b, 3); + a.copy_advice(&mut region, config.c, 4); + } + + Ok(()) + }, + ) + } + } +} + +fn gen_application_snark(params: &ParamsKZG) -> Snark { + let circuit = application::StandardPlonk::rand(OsRng); + + let pk = gen_pk(params, &circuit, None); + gen_snark_shplonk(params, &pk, circuit, None::<&str>) +} + +fn main() { + let params_app = gen_srs(8); + + let k = 21u32; + let lookup_bits = k as usize - 1; + let params = gen_srs(k); + let snarks = [(); 1].map(|_| gen_application_snark(¶ms_app)); + + let mut agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + AggregationConfigParams { degree: k, lookup_bits, ..Default::default() }, + ¶ms, + snarks.clone(), + VerifierUniversality::Full, + ); + let agg_config = agg_circuit.calculate_params(Some(10)); + + let pk = gen_pk(¶ms, &agg_circuit, None); + let break_points = agg_circuit.break_points(); + drop(agg_circuit); + + let agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Prover, + agg_config, + ¶ms, + snarks.clone(), + VerifierUniversality::Full, + ) + .use_break_points(break_points); + let num_instances = agg_circuit.num_instance(); + let instances = agg_circuit.instances(); + let _proof = gen_evm_proof_shplonk(¶ms, &pk, agg_circuit, instances.clone()); + + let _deployment_code = gen_evm_verifier_shplonk::( + ¶ms, + pk.get_vk(), + num_instances, + Some(Path::new("examples/StandardPlonkVerifier.sol")), + ); + #[cfg(feature = "revm")] + evm_verify(_deployment_code, instances, _proof); +} diff --git a/snark-verifier-sdk/examples/vkey_as_witness.rs b/snark-verifier-sdk/examples/vkey_as_witness.rs new file mode 100644 index 00000000..ca066d80 --- /dev/null +++ b/snark-verifier-sdk/examples/vkey_as_witness.rs @@ -0,0 +1,183 @@ +use application::ComputeFlag; + +use halo2_base::gates::circuit::CircuitBuilderStage; +use halo2_base::halo2_proofs; +use halo2_base::halo2_proofs::arithmetic::Field; +use halo2_base::halo2_proofs::halo2curves::bn256::Fr; +use halo2_base::utils::fs::gen_srs; +use halo2_proofs::halo2curves as halo2_curves; + +use halo2_proofs::{halo2curves::bn256::Bn256, poly::kzg::commitment::ParamsKZG}; +use rand::rngs::OsRng; +use snark_verifier_sdk::halo2::aggregation::{AggregationConfigParams, VerifierUniversality}; +use snark_verifier_sdk::SHPLONK; +use snark_verifier_sdk::{ + gen_pk, + halo2::{aggregation::AggregationCircuit, gen_snark_shplonk}, + Snark, +}; + +mod application { + use super::halo2_curves::bn256::Fr; + use super::halo2_proofs::{ + circuit::{Layouter, SimpleFloorPlanner, Value}, + plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, Instance}, + poly::Rotation, + }; + + use snark_verifier_sdk::CircuitExt; + + #[derive(Clone, Copy)] + pub struct StandardPlonkConfig { + a: Column, + b: Column, + c: Column, + q_a: Column, + q_b: Column, + q_c: Column, + q_ab: Column, + constant: Column, + #[allow(dead_code)] + instance: Column, + } + + impl StandardPlonkConfig { + fn configure(meta: &mut ConstraintSystem) -> Self { + let [a, b, c] = [(); 3].map(|_| meta.advice_column()); + let [q_a, q_b, q_c, q_ab, constant] = [(); 5].map(|_| meta.fixed_column()); + let instance = meta.instance_column(); + + [a, b, c].map(|column| meta.enable_equality(column)); + + meta.create_gate( + "q_a·a + q_b·b + q_c·c + q_ab·a·b + constant + instance = 0", + |meta| { + let [a, b, c] = + [a, b, c].map(|column| meta.query_advice(column, Rotation::cur())); + let [q_a, q_b, q_c, q_ab, constant] = [q_a, q_b, q_c, q_ab, constant] + .map(|column| meta.query_fixed(column, Rotation::cur())); + let instance = meta.query_instance(instance, Rotation::cur()); + Some( + q_a * a.clone() + + q_b * b.clone() + + q_c * c + + q_ab * a * b + + constant + + instance, + ) + }, + ); + + StandardPlonkConfig { a, b, c, q_a, q_b, q_c, q_ab, constant, instance } + } + } + + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum ComputeFlag { + All, + SkipFixed, + SkipCopy, + } + + #[derive(Clone)] + pub struct StandardPlonk(pub Fr, pub ComputeFlag); + + impl CircuitExt for StandardPlonk { + fn num_instance(&self) -> Vec { + vec![1] + } + + fn instances(&self) -> Vec> { + vec![vec![self.0]] + } + } + + impl Circuit for StandardPlonk { + type Config = StandardPlonkConfig; + type FloorPlanner = SimpleFloorPlanner; + + fn without_witnesses(&self) -> Self { + Self(Fr::zero(), self.1) + } + + fn configure(meta: &mut ConstraintSystem) -> Self::Config { + meta.set_minimum_degree(4); + StandardPlonkConfig::configure(meta) + } + + fn synthesize( + &self, + config: Self::Config, + mut layouter: impl Layouter, + ) -> Result<(), Error> { + layouter.assign_region( + || "", + |mut region| { + region.assign_advice(config.a, 0, Value::known(self.0)); + region.assign_fixed(config.q_a, 0, -Fr::one()); + region.assign_advice(config.a, 1, Value::known(-Fr::from(5u64))); + if self.1 != ComputeFlag::SkipFixed { + for (idx, column) in (1..).zip([ + config.q_a, + config.q_b, + config.q_c, + config.q_ab, + config.constant, + ]) { + region.assign_fixed(column, 1, Fr::from(idx as u64)); + } + } + let a = region.assign_advice(config.a, 2, Value::known(Fr::one())); + if self.1 != ComputeFlag::SkipCopy { + a.copy_advice(&mut region, config.b, 3); + a.copy_advice(&mut region, config.c, 4); + } + + Ok(()) + }, + ) + } + } +} + +fn gen_application_snark(params: &ParamsKZG, flag: ComputeFlag) -> Snark { + let circuit = application::StandardPlonk(Fr::random(OsRng), flag); + + let pk = gen_pk(params, &circuit, None); + gen_snark_shplonk(params, &pk, circuit, None::<&str>) +} + +fn main() { + let params_app = gen_srs(8); + let dummy_snark = gen_application_snark(¶ms_app, ComputeFlag::All); + + let k = 15u32; + let params = gen_srs(k); + let lookup_bits = k as usize - 1; + let mut agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + AggregationConfigParams { degree: k, lookup_bits, ..Default::default() }, + ¶ms, + vec![dummy_snark], + VerifierUniversality::PreprocessedAsWitness, + ); + let agg_config = agg_circuit.calculate_params(Some(10)); + + let pk = gen_pk(¶ms, &agg_circuit, None); + let break_points = agg_circuit.break_points(); + + let snarks = [ComputeFlag::All, ComputeFlag::SkipFixed, ComputeFlag::SkipCopy] + .map(|flag| gen_application_snark(¶ms_app, flag)); + for (i, snark) in snarks.into_iter().enumerate() { + let agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Prover, + agg_config, + ¶ms, + vec![snark], + VerifierUniversality::PreprocessedAsWitness, + ) + .use_break_points(break_points.clone()); + let _snark = gen_snark_shplonk(¶ms, &pk, agg_circuit, None::<&str>); + println!("snark {i} success"); + } +} diff --git a/snark-verifier-sdk/src/evm.rs b/snark-verifier-sdk/src/evm.rs index f423d327..6519752a 100644 --- a/snark-verifier-sdk/src/evm.rs +++ b/snark-verifier-sdk/src/evm.rs @@ -3,7 +3,6 @@ use crate::{GWC, SHPLONK}; use super::{CircuitExt, PlonkVerifier}; #[cfg(feature = "display")] use ark_std::{end_timer, start_timer}; -use ethereum_types::Address; use halo2_base::halo2_proofs::{ halo2curves::bn256::{Bn256, Fq, Fr, G1Affine}, plonk::{create_proof, verify_proof, Circuit, ProvingKey, VerifyingKey}, @@ -23,7 +22,7 @@ use itertools::Itertools; use rand::{rngs::StdRng, SeedableRng}; pub use snark_verifier::loader::evm::encode_calldata; use snark_verifier::{ - loader::evm::{compile_yul, EvmLoader, ExecutorBuilder}, + loader::evm::{compile_solidity, EvmLoader}, pcs::{ kzg::{KzgAccumulator, KzgAsVerifyingKey, KzgDecidingKey, KzgSuccinctVerifyingKey}, AccumulationDecider, AccumulationScheme, PolynomialCommitmentScheme, @@ -148,11 +147,11 @@ where PlonkVerifier::::read_proof(&dk, &protocol, &instances, &mut transcript).unwrap(); PlonkVerifier::::verify(&dk, &protocol, &instances, &proof).unwrap(); - let yul_code = loader.yul_code(); - let byte_code = compile_yul(&yul_code); + let sol_code = loader.solidity_code(); + let byte_code = compile_solidity(&sol_code); if let Some(path) = path { path.parent().and_then(|dir| fs::create_dir_all(dir).ok()).unwrap(); - fs::write(path, yul_code).unwrap(); + fs::write(path, sol_code).unwrap(); } byte_code } @@ -175,20 +174,11 @@ pub fn gen_evm_verifier_shplonk>( gen_evm_verifier::(params, vk, num_instance, path) } +#[cfg(feature = "revm")] pub fn evm_verify(deployment_code: Vec, instances: Vec>, proof: Vec) { let calldata = encode_calldata(&instances, &proof); - let success = { - let mut evm = ExecutorBuilder::default().with_gas_limit(u64::MAX.into()).build(); - - let caller = Address::from_low_u64_be(0xfe); - let verifier = evm.deploy(caller, deployment_code.into(), 0.into()).address.unwrap(); - let result = evm.call_raw(caller, verifier, calldata.into(), 0.into()); - - dbg!(result.gas_used); - - !result.reverted - }; - assert!(success); + let gas_cost = snark_verifier::loader::evm::deploy_and_call(deployment_code, calldata).unwrap(); + dbg!(gas_cost); } pub fn write_calldata(instances: &[Vec], proof: &[u8], path: &Path) -> io::Result { diff --git a/snark-verifier-sdk/src/halo2.rs b/snark-verifier-sdk/src/halo2.rs index b0710230..aa5f8810 100644 --- a/snark-verifier-sdk/src/halo2.rs +++ b/snark-verifier-sdk/src/halo2.rs @@ -2,6 +2,7 @@ use super::{read_instances, write_instances, CircuitExt, PlonkSuccinctVerifier, #[cfg(feature = "display")] use ark_std::{end_timer, start_timer}; use halo2_base::halo2_proofs; +pub use halo2_base::poseidon::hasher::spec::OptimizedPoseidonSpec; use halo2_proofs::{ circuit::Layouter, halo2curves::{ @@ -26,7 +27,6 @@ use halo2_proofs::{ use itertools::Itertools; use lazy_static::lazy_static; use rand::{rngs::StdRng, SeedableRng}; -pub use snark_verifier::util::hash::OptimizedPoseidonSpec; use snark_verifier::{ cost::CostEstimation, loader::native::NativeLoader, @@ -35,6 +35,7 @@ use snark_verifier::{ AccumulationScheme, PolynomialCommitmentScheme, Query, }, system::halo2::{compile, Config}, + util::arithmetic::Rotation, util::transcript::TranscriptWrite, verifier::plonk::PlonkProof, }; @@ -122,20 +123,25 @@ where end_timer!(proof_time); // validate proof before caching - assert!({ - let mut transcript_read = - PoseidonTranscript::::from_spec(&proof[..], POSEIDON_SPEC.clone()); - VerificationStrategy::<_, V>::finalize( - verify_proof::<_, V, _, _, _>( - params.verifier_params(), - pk.get_vk(), - AccumulatorStrategy::new(params.verifier_params()), - &[instances.as_slice()], - &mut transcript_read, + assert!( + { + let mut transcript_read = PoseidonTranscript::::from_spec( + &proof[..], + POSEIDON_SPEC.clone(), + ); + VerificationStrategy::<_, V>::finalize( + verify_proof::<_, V, _, _, _>( + params.verifier_params(), + pk.get_vk(), + AccumulatorStrategy::new(params.verifier_params()), + &[instances.as_slice()], + &mut transcript_read, + ) + .unwrap(), ) - .unwrap(), - ) - }); + }, + "SNARK proof failed to verify" + ); if let Some((instance_path, proof_path)) = path { write_instances(&instances, instance_path); @@ -286,7 +292,7 @@ where NativeLoader, Accumulator = KzgAccumulator, VerifyingKey = KzgAsVerifyingKey, - > + CostEstimation>>, + > + CostEstimation>>, { struct CsProxy(PhantomData<(F, C)>); diff --git a/snark-verifier-sdk/src/halo2/aggregation.rs b/snark-verifier-sdk/src/halo2/aggregation.rs index b5dc148d..690a64fc 100644 --- a/snark-verifier-sdk/src/halo2/aggregation.rs +++ b/snark-verifier-sdk/src/halo2/aggregation.rs @@ -1,22 +1,18 @@ use super::PlonkSuccinctVerifier; use crate::{BITS, LIMBS}; +use getset::Getters; use halo2_base::{ gates::{ - builder::{ - CircuitBuilderStage, FlexGateConfigParams, GateThreadBuilder, - MultiPhaseThreadBreakPoints, RangeCircuitBuilder, RangeWithInstanceCircuitBuilder, - RangeWithInstanceConfig, + circuit::{ + builder::BaseCircuitBuilder, BaseCircuitParams, BaseConfig, CircuitBuilderStage, }, - RangeChip, + flex_gate::MultiPhaseThreadBreakPoints, }, halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner}, halo2curves::bn256::{Bn256, Fr, G1Affine}, plonk::{self, Circuit, ConstraintSystem, Selector}, - poly::{ - commitment::{Params, ParamsProver}, - kzg::commitment::ParamsKZG, - }, + poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG}, }, utils::ScalarField, AssignedValue, @@ -38,12 +34,7 @@ use snark_verifier::{ }, verifier::SnarkVerifier, }; -use std::{ - env::{set_var, var}, - fs::File, - path::Path, - rc::Rc, -}; +use std::{fs::File, mem, path::Path, rc::Rc}; use super::{CircuitExt, PoseidonTranscript, Snark, POSEIDON_SPEC}; @@ -51,6 +42,44 @@ pub type Svk = KzgSuccinctVerifyingKey; pub type BaseFieldEccChip<'chip> = halo2_ecc::ecc::BaseFieldEccChip<'chip, G1Affine>; pub type Halo2Loader<'chip> = loader::halo2::Halo2Loader>; +#[derive(Clone, Debug)] +pub struct PreprocessedAndDomainAsWitness { + // this is basically the vkey + pub preprocessed: Vec>, + pub k: AssignedValue, +} + +#[derive(Clone, Debug)] +pub struct SnarkAggregationWitness<'a> { + pub previous_instances: Vec>>, + pub accumulator: KzgAccumulator>>, + /// This returns the assigned `preprocessed` and `transcript_initial_state` values as a vector of assigned values, one for each aggregated snark. + /// These can then be exposed as public instances. + pub preprocessed: Vec, +} + +/// Different possible stages of universality the aggregation circuit can support +#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)] +pub enum VerifierUniversality { + /// Default: verifier is specific to a single circuit + #[default] + None, + /// Preprocessed digest (commitments to fixed columns) is loaded as witness + PreprocessedAsWitness, + /// Preprocessed as witness and log_2(number of rows in the circuit) = k loaded as witness + Full, +} + +impl VerifierUniversality { + pub fn preprocessed_as_witness(&self) -> bool { + self != &VerifierUniversality::None + } + + pub fn k_as_witness(&self) -> bool { + self == &VerifierUniversality::Full + } +} + #[allow(clippy::type_complexity)] /// Core function used in `synthesize` to aggregate multiple `snarks`. /// @@ -58,6 +87,9 @@ pub type Halo2Loader<'chip> = loader::halo2::Halo2Loader( @@ -65,7 +97,8 @@ pub fn aggregate<'a, AS>( loader: &Rc>, snarks: &[Snark], as_proof: &[u8], -) -> (Vec>>, KzgAccumulator>>) + universality: VerifierUniversality, +) -> SnarkAggregationWitness<'a> where AS: PolynomialCommitmentScheme< G1Affine, @@ -90,6 +123,7 @@ where }; let mut previous_instances = Vec::with_capacity(snarks.len()); + let mut preprocessed_witnesses = Vec::with_capacity(snarks.len()); // to avoid re-loading the spec each time, we create one transcript and clear the stream let mut transcript = PoseidonTranscript::>, &[u8]>::from_spec( loader, @@ -97,10 +131,41 @@ where POSEIDON_SPEC.clone(), ); + let preprocessed_as_witness = universality.preprocessed_as_witness(); let mut accumulators = snarks .iter() - .flat_map(|snark| { - let protocol = snark.protocol.loaded(loader); + .flat_map(|snark: &Snark| { + let protocol = if preprocessed_as_witness { + // always load `domain.n` as witness if vkey is witness + snark.protocol.loaded_preprocessed_as_witness(loader, universality.k_as_witness()) + } else { + snark.protocol.loaded(loader) + }; + let preprocessed = protocol + .preprocessed + .iter() + .flat_map(|preprocessed| { + let assigned = preprocessed.assigned(); + [assigned.x(), assigned.y()] + .into_iter() + .flat_map(|coordinate| coordinate.limbs().to_vec()) + .collect_vec() + }) + .chain( + protocol.transcript_initial_state.clone().map(|scalar| scalar.into_assigned()), + ) + .collect_vec(); + // Store `k` as witness. If `k` was fixed, assign it as a constant. + let k = protocol + .domain_as_witness + .as_ref() + .map(|domain| domain.k.clone().into_assigned()) + .unwrap_or_else(|| { + loader.ctx_mut().main().load_constant(Fr::from(protocol.domain.k as u64)) + }); + let preprocessed_and_k = PreprocessedAndDomainAsWitness { preprocessed, k }; + preprocessed_witnesses.push(preprocessed_and_k); + let instances = assign_instances(&snark.instances); // read the transcript and perform Fiat-Shamir @@ -138,12 +203,16 @@ where accumulators.pop().unwrap() }; - (previous_instances, accumulator) + SnarkAggregationWitness { + previous_instances, + accumulator, + preprocessed: preprocessed_witnesses, + } } /// Same as `FlexGateConfigParams` except we assume a single Phase and default 'Vertical' strategy. /// Also adds `lookup_bits` field. -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Copy, Default, Debug, Serialize, Deserialize)] pub struct AggregationConfigParams { pub degree: u32, pub num_advice: usize, @@ -159,14 +228,67 @@ impl AggregationConfigParams { } } -#[derive(Clone, Debug)] +impl From for BaseCircuitParams { + fn from(params: AggregationConfigParams) -> Self { + BaseCircuitParams { + k: params.degree as usize, + num_advice_per_phase: vec![params.num_advice], + num_lookup_advice_per_phase: vec![params.num_lookup_advice], + num_fixed: params.num_fixed, + lookup_bits: Some(params.lookup_bits), + num_instance_columns: 1, + } + } +} + +impl TryFrom<&BaseCircuitParams> for AggregationConfigParams { + type Error = &'static str; + + fn try_from(params: &BaseCircuitParams) -> Result { + if params.num_advice_per_phase.iter().skip(1).any(|&n| n != 0) { + return Err("AggregationConfigParams only supports 1 phase"); + } + if params.num_lookup_advice_per_phase.iter().skip(1).any(|&n| n != 0) { + return Err("AggregationConfigParams only supports 1 phase"); + } + if params.lookup_bits.is_none() { + return Err("AggregationConfigParams requires lookup_bits"); + } + if params.num_instance_columns != 1 { + return Err("AggregationConfigParams only supports 1 instance column"); + } + Ok(Self { + degree: params.k as u32, + num_advice: params.num_advice_per_phase[0], + num_lookup_advice: params.num_lookup_advice_per_phase[0], + num_fixed: params.num_fixed, + lookup_bits: params.lookup_bits.unwrap(), + }) + } +} + +impl TryFrom for AggregationConfigParams { + type Error = &'static str; + + fn try_from(value: BaseCircuitParams) -> Result { + Self::try_from(&value) + } +} + +#[derive(Clone, Debug, Getters)] pub struct AggregationCircuit { - pub inner: RangeWithInstanceCircuitBuilder, + /// Circuit builder consisting of virtual region managers + pub builder: BaseCircuitBuilder, // the public instances from previous snarks that were aggregated, now collected as PRIVATE assigned values // the user can optionally append these to `inner.assigned_instances` to expose them - pub previous_instances: Vec>>, - // accumulation scheme proof, private input - pub as_proof: Vec, // not sure this needs to be stored, keeping for now + #[getset(get = "pub")] + previous_instances: Vec>>, + /// This returns the assigned `preprocessed_digest` (vkey), optional `transcript_initial_state`, `domain.n` (optional), and `omega` (optional) values as a vector of assigned values, one for each aggregated snark. + /// These can then be exposed as public instances. + #[getset(get = "pub")] + preprocessed: Vec, + // accumulation scheme proof, no longer used + // pub as_proof: Vec, } // trait just so we can have a generic that is either SHPLONK or GWC @@ -193,19 +315,25 @@ pub trait Halo2KzgAccumulationScheme<'a> = PolynomialCommitmentScheme< > + AccumulationSchemeProver>; impl AggregationCircuit { - /// Given snarks, this creates a circuit and runs the `GateThreadBuilder` to verify all the snarks. + /// Given snarks, this creates `BaseCircuitBuilder` and populates the circuit builder with the virtual cells and constraints necessary to verify all the snarks. + /// /// By default, the returned circuit has public instances equal to the limbs of the pair of elliptic curve points, referred to as the `accumulator`, that need to be verified in a final pairing check. /// - /// The user can optionally modify the circuit after calling this function to add more instances to `assigned_instances` to expose. + /// # Universality + /// - If `universality` is not `None`, then the verifying keys of each snark in `snarks` is loaded as a witness in the circuit. + /// - Moreover, if `universality` is `Full`, then the number of rows `n` of each snark in `snarks` is also loaded as a witness. In this case the generator `omega` of the order `n` multiplicative subgroup of `F` is also loaded as a witness. + /// - By default, these witnesses are _private_ and returned in `self.preprocessed_digests + /// - The user can optionally modify the circuit after calling this function to add more instances to `assigned_instances` to expose. /// - /// Warning: will fail silently if `snarks` were created using a different multi-open scheme than `AS` + /// # Warning + /// Will fail silently if `snarks` were created using a different multi-open scheme than `AS` /// where `AS` can be either [`crate::SHPLONK`] or [`crate::GWC`] (for original PLONK multi-open scheme) pub fn new( stage: CircuitBuilderStage, - break_points: Option, - lookup_bits: usize, + config_params: AggregationConfigParams, params: &ParamsKZG, snarks: impl IntoIterator, + universality: VerifierUniversality, ) -> Self where AS: for<'a> Halo2KzgAccumulationScheme<'a>, @@ -244,23 +372,24 @@ impl AggregationCircuit { (accumulator, transcript_write.finalize()) }; - // create thread builder and run aggregation witness gen - let builder = match stage { - CircuitBuilderStage::Mock => GateThreadBuilder::mock(), - CircuitBuilderStage::Prover => GateThreadBuilder::prover(), - CircuitBuilderStage::Keygen => GateThreadBuilder::keygen(), - }; + let mut builder = BaseCircuitBuilder::from_stage(stage).use_params(config_params.into()); // create halo2loader - let range = RangeChip::::default(lookup_bits); + let range = builder.range_chip(); let fp_chip = FpChip::::new(&range, BITS, LIMBS); let ecc_chip = BaseFieldEccChip::new(&fp_chip); - let loader = Halo2Loader::new(ecc_chip, builder); - - let (previous_instances, accumulator) = - aggregate::(&svk, &loader, &snarks, as_proof.as_slice()); + // Take the phase 0 pool from `builder`; it needs to be owned by loader. + // We put it back later (below), so it should have same effect as just mutating `builder.pool(0)`. + let pool = mem::take(builder.pool(0)); + // range_chip has shared reference to LookupAnyManager, with shared CopyConstraintManager + // pool has shared reference to CopyConstraintManager + let loader = Halo2Loader::new(ecc_chip, pool); + + // run witness and copy constraint generation + let SnarkAggregationWitness { previous_instances, accumulator, preprocessed } = + aggregate::(&svk, &loader, &snarks, as_proof.as_slice(), universality); let lhs = accumulator.lhs.assigned(); let rhs = accumulator.rhs.assigned(); - let assigned_instances = lhs + let accumulator = lhs .x() .limbs() .iter() @@ -275,74 +404,20 @@ impl AggregationCircuit { let KzgAccumulator { lhs, rhs } = _accumulator; let instances = [lhs.x, lhs.y, rhs.x, rhs.y].map(fe_to_limbs::<_, Fr, LIMBS, BITS>).concat(); - for (lhs, rhs) in instances.iter().zip(assigned_instances.iter()) { + for (lhs, rhs) in instances.iter().zip(accumulator.iter()) { assert_eq!(lhs, rhs.value()); } } - - let builder = loader.take_ctx(); - let circuit = match stage { - CircuitBuilderStage::Mock => RangeCircuitBuilder::mock(builder), - CircuitBuilderStage::Keygen => RangeCircuitBuilder::keygen(builder), - CircuitBuilderStage::Prover => { - RangeCircuitBuilder::prover(builder, break_points.unwrap()) - } - }; - let inner = RangeWithInstanceCircuitBuilder::new(circuit, assigned_instances); - Self { inner, previous_instances, as_proof } - } - - pub fn public( - stage: CircuitBuilderStage, - break_points: Option, - lookup_bits: usize, - params: &ParamsKZG, - snarks: impl IntoIterator, - has_prev_accumulator: bool, - ) -> Self - where - AS: for<'a> Halo2KzgAccumulationScheme<'a>, - { - let mut private = Self::new::(stage, break_points, lookup_bits, params, snarks); - private.expose_previous_instances(has_prev_accumulator); - private - } - - // this function is for convenience - /// `params` should be the universal trusted setup to be used for the aggregation circuit, not the one used to generate the previous snarks, although we assume both use the same generator g[0] - pub fn keygen(params: &ParamsKZG, snarks: impl IntoIterator) -> Self - where - AS: for<'a> Halo2KzgAccumulationScheme<'a>, - { - let lookup_bits = params.k() as usize - 1; // almost always we just use the max lookup bits possible, which is k - 1 because of blinding factors - let circuit = - Self::new::(CircuitBuilderStage::Keygen, None, lookup_bits, params, snarks); - circuit.config(params.k(), Some(10)); - set_var("LOOKUP_BITS", lookup_bits.to_string()); - circuit - } - - // this function is for convenience - pub fn prover( - params: &ParamsKZG, - snarks: impl IntoIterator, - break_points: MultiPhaseThreadBreakPoints, - ) -> Self - where - AS: for<'a> Halo2KzgAccumulationScheme<'a>, - { - let lookup_bits: usize = var("LOOKUP_BITS").expect("LOOKUP_BITS not set").parse().unwrap(); - let circuit = Self::new::( - CircuitBuilderStage::Prover, - Some(break_points), - lookup_bits, - params, - snarks, + // put back `pool` into `builder` + *builder.pool(0) = loader.take_ctx(); + assert_eq!( + builder.assigned_instances.len(), + 1, + "AggregationCircuit must have exactly 1 instance column" ); - let minimum_rows = var("MINIMUM_ROWS").map(|s| s.parse().unwrap_or(10)).unwrap_or(10); - circuit.config(params.k(), Some(minimum_rows)); - set_var("LOOKUP_BITS", lookup_bits.to_string()); - circuit + // expose accumulator as public instances + builder.assigned_instances[0] = accumulator; + Self { builder, previous_instances, preprocessed } } /// Re-expose the previous public instances of aggregated snarks again. @@ -351,55 +426,87 @@ impl AggregationCircuit { pub fn expose_previous_instances(&mut self, has_prev_accumulator: bool) { let start = (has_prev_accumulator as usize) * 4 * LIMBS; for prev in self.previous_instances.iter() { - self.inner.assigned_instances.extend_from_slice(&prev[start..]); + self.builder.assigned_instances[0].extend_from_slice(&prev[start..]); } } - pub fn as_proof(&self) -> &[u8] { - &self.as_proof[..] + /// The log_2 size of the lookup table + pub fn lookup_bits(&self) -> usize { + self.builder.config_params.lookup_bits.unwrap() } - pub fn config(&self, k: u32, minimum_rows: Option) -> FlexGateConfigParams { - self.inner.config(k, minimum_rows) + /// Set config params + pub fn set_params(&mut self, params: AggregationConfigParams) { + self.builder.set_params(params.into()); } + /// Returns new with config params + pub fn use_params(mut self, params: AggregationConfigParams) -> Self { + self.set_params(params); + self + } + + /// The break points of the circuit. pub fn break_points(&self) -> MultiPhaseThreadBreakPoints { - self.inner.break_points() + self.builder.break_points() } - pub fn instance_count(&self) -> usize { - self.inner.instance_count() + /// Sets the break points of the circuit. + pub fn set_break_points(&mut self, break_points: MultiPhaseThreadBreakPoints) { + self.builder.set_break_points(break_points); } - pub fn instance(&self) -> Vec { - self.inner.instance() + /// Returns new with break points + pub fn use_break_points(mut self, break_points: MultiPhaseThreadBreakPoints) -> Self { + self.set_break_points(break_points); + self + } + + /// Auto-configure the circuit and change the circuit's internal configuration parameters. + pub fn calculate_params(&mut self, minimum_rows: Option) -> AggregationConfigParams { + self.builder.calculate_params(minimum_rows).try_into().unwrap() } } -impl CircuitExt for RangeWithInstanceCircuitBuilder { +impl CircuitExt for BaseCircuitBuilder { fn num_instance(&self) -> Vec { - vec![self.instance_count()] + self.assigned_instances.iter().map(|instances| instances.len()).collect() } fn instances(&self) -> Vec> { - vec![self.instance()] + self.assigned_instances + .iter() + .map(|instances| instances.iter().map(|v| *v.value()).collect()) + .collect() } fn selectors(config: &Self::Config) -> Vec { - config.range.gate.basic_gates[0].iter().map(|gate| gate.q_enable).collect() + config.gate().basic_gates[0].iter().map(|gate| gate.q_enable).collect() } } impl Circuit for AggregationCircuit { - type Config = RangeWithInstanceConfig; + type Config = BaseConfig; type FloorPlanner = SimpleFloorPlanner; + type Params = AggregationConfigParams; + + fn params(&self) -> Self::Params { + (&self.builder.config_params).try_into().unwrap() + } fn without_witnesses(&self) -> Self { unimplemented!() } - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - RangeWithInstanceCircuitBuilder::configure(meta) + fn configure_with_params( + meta: &mut ConstraintSystem, + params: Self::Params, + ) -> Self::Config { + BaseCircuitBuilder::configure_with_params(meta, params.into()) + } + + fn configure(_: &mut ConstraintSystem) -> Self::Config { + unreachable!() } fn synthesize( @@ -407,17 +514,17 @@ impl Circuit for AggregationCircuit { config: Self::Config, layouter: impl Layouter, ) -> Result<(), plonk::Error> { - self.inner.synthesize(config, layouter) + self.builder.synthesize(config, layouter) } } impl CircuitExt for AggregationCircuit { fn num_instance(&self) -> Vec { - self.inner.num_instance() + self.builder.num_instance() } fn instances(&self) -> Vec> { - self.inner.instances() + self.builder.instances() } fn accumulator_indices() -> Option> { @@ -425,7 +532,7 @@ impl CircuitExt for AggregationCircuit { } fn selectors(config: &Self::Config) -> Vec { - RangeWithInstanceCircuitBuilder::selectors(config) + BaseCircuitBuilder::selectors(config) } } diff --git a/snark-verifier-sdk/src/lib.rs b/snark-verifier-sdk/src/lib.rs index 9a5833d6..932b20ab 100644 --- a/snark-verifier-sdk/src/lib.rs +++ b/snark-verifier-sdk/src/lib.rs @@ -25,6 +25,8 @@ use std::{ path::Path, }; +pub use snark_verifier; + #[cfg(feature = "loader_evm")] pub mod evm; #[cfg(feature = "loader_halo2")] @@ -33,6 +35,8 @@ pub mod halo2; pub const LIMBS: usize = 3; pub const BITS: usize = 88; +const BUFFER_SIZE: usize = 1024 * 1024; // 1MB + /// AS stands for accumulation scheme. /// AS can be either `Kzg` (the original PLONK KZG multi-open) or `Kzg` (SHPLONK) pub type PlonkVerifier = verifier::plonk::PlonkVerifier>; @@ -76,19 +80,28 @@ pub trait CircuitExt: Circuit { } } -pub fn read_pk>(path: &Path) -> io::Result> { - let f = File::open(path)?; +pub fn read_pk>(path: &Path, params: C::Params) -> io::Result> { + read_pk_with_capacity::(BUFFER_SIZE, path, params) +} + +pub fn read_pk_with_capacity>( + capacity: usize, + path: impl AsRef, + params: C::Params, +) -> io::Result> { + let f = File::open(path.as_ref())?; #[cfg(feature = "display")] - let read_time = start_timer!(|| format!("Reading pkey from {path:?}")); + let read_time = start_timer!(|| format!("Reading pkey from {:?}", path.as_ref())); // BufReader is indeed MUCH faster than Read - let mut bufreader = BufReader::new(f); + let mut bufreader = BufReader::with_capacity(capacity, f); // But it's even faster to load the whole file into memory first and then process, // HOWEVER this requires twice as much memory to initialize // let initial_buffer_size = f.metadata().map(|m| m.len() as usize + 1).unwrap_or(0); // let mut bufreader = Vec::with_capacity(initial_buffer_size); // f.read_to_end(&mut bufreader)?; - let pk = ProvingKey::read::<_, C>(&mut bufreader, SerdeFormat::RawBytesUnchecked).unwrap(); + let pk = + ProvingKey::read::<_, C>(&mut bufreader, SerdeFormat::RawBytesUnchecked, params).unwrap(); #[cfg(feature = "display")] end_timer!(read_time); @@ -103,7 +116,7 @@ pub fn gen_pk>( path: Option<&Path>, ) -> ProvingKey { if let Some(path) = path { - if let Ok(pk) = read_pk::(path) { + if let Ok(pk) = read_pk::(path, circuit.params()) { return pk; } } @@ -121,7 +134,7 @@ pub fn gen_pk>( let write_time = start_timer!(|| format!("Writing pkey to {path:?}")); path.parent().and_then(|dir| fs::create_dir_all(dir).ok()).unwrap(); - let mut f = BufWriter::new(File::create(path).unwrap()); + let mut f = BufWriter::with_capacity(BUFFER_SIZE, File::create(path).unwrap()); pk.write(&mut f, SerdeFormat::RawBytesUnchecked).unwrap(); #[cfg(feature = "display")] diff --git a/snark-verifier/Cargo.toml b/snark-verifier/Cargo.toml index 74bc99fe..6e223f24 100644 --- a/snark-verifier/Cargo.toml +++ b/snark-verifier/Cargo.toml @@ -1,35 +1,40 @@ [package] name = "snark-verifier" -version = "0.1.1" +version = "0.1.6" +authors = ["Privacy Scaling Explorations Team", "Intrinsic Technologies"] +license = "MIT" edition = "2021" +repository = "https://github.com/axiom-crypto/snark-verifier" +readme = "../README.md" +description = "Generic (S)NARK verifier for Rust, halo2, and EVM. This is a fork of PSE's version." +rust-version = "1.73.0" [dependencies] -itertools = "0.10.5" -lazy_static = "1.4.0" -num-bigint = "0.4.3" +itertools = "0.11" +lazy_static = "1.4" +num-bigint = "0.4" num-integer = "0.1.45" num-traits = "0.2.15" hex = "0.4" rand = "0.8" serde = { version = "1.0", features = ["derive"] } +pairing = { version = "0.23" } # Use halo2-base as non-optional dependency because it re-exports halo2_proofs, halo2curves, and poseidon, using different repos based on feature flag "halo2-axiom" or "halo2-pse" -halo2-base = { git = "https://github.com/axiom-crypto/halo2-lib.git", tag = "v0.3.0", default-features = false } -# This is Scroll's audited poseidon circuit. We only use it for the Native Poseidon spec. We do not use the halo2 circuit at all (and it wouldn't even work because the halo2_proofs tag is not compatbile). -poseidon-circuit = { git = "https://github.com/scroll-tech/poseidon-circuit.git", rev = "50015b7" } +halo2-base = { version = "=0.4.0", default-features = false } + +# loader_halo2 +halo2-ecc = { version = "=0.4.0", default-features = false, optional = true } # parallel -rayon = { version = "1.7.0", optional = true } +rayon = { version = "1.8", optional = true } # loader_evm -sha3 = { version = "=0.10.8", optional = true } -bytes = { version = "=1.4.0", default-features = false, optional = true } -primitive-types = { version = "=0.12.1", default-features = false, features = ["std"], optional = true } -rlp = { version = "=0.5.2", default-features = false, features = ["std"], optional = true } -revm = { version = "=2.3.1", optional = true } +sha3 = { version = "=0.10", optional = true } +ruint = { version = "=1.10", optional = true } -# loader_halo2 -halo2-ecc = { git = "https://github.com/axiom-crypto/halo2-lib.git", tag = "v0.3.0", default-features = false, optional = true } +# revm only used for testing smart contract execution +revm = { version = "=3.5.0", optional = true } [dev-dependencies] ark-std = { version = "0.3.0", features = ["print-trace"] } @@ -39,16 +44,17 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" # loader_evm crossterm = { version = "0.25" } -tui = { version = "0.19", default-features = false, features = ["crossterm"] } +ratatui = { version = "0.24", default-features = false, features = ["crossterm"] } [features] default = ["loader_evm", "loader_halo2", "halo2-axiom", "display"] display = ["halo2-base/display", "halo2-ecc?/display"] -loader_evm = ["dep:primitive-types", "dep:sha3", "dep:revm", "dep:bytes", "dep:rlp"] loader_halo2 = ["halo2-ecc"] +loader_evm = ["dep:sha3", "dep:ruint"] +revm = ["loader_evm", "dep:revm"] parallel = ["dep:rayon"] # EXACTLY one of halo2-pse / halo2-axiom should always be turned on; not sure how to enforce this with Cargo -halo2-pse = ["halo2-base/halo2-pse", "halo2-ecc?/halo2-pse"] +#halo2-pse = ["halo2-base/halo2-pse", "halo2-ecc?/halo2-pse"] halo2-axiom = ["halo2-base/halo2-axiom", "halo2-ecc?/halo2-axiom"] [[example]] diff --git a/snark-verifier/examples/evm-verifier-with-accumulator.rs b/snark-verifier/examples/evm-verifier-with-accumulator.rs index dd537880..b18e992d 100644 --- a/snark-verifier/examples/evm-verifier-with-accumulator.rs +++ b/snark-verifier/examples/evm-verifier-with-accumulator.rs @@ -1,5 +1,9 @@ use aggregation::{AggregationCircuit, AggregationConfigParams}; -use halo2_base::{gates::builder::CircuitBuilderStage, halo2_proofs, utils::fs::gen_srs}; +use halo2_base::{ + gates::circuit::{BaseCircuitParams, CircuitBuilderStage}, + halo2_proofs, + utils::fs::gen_srs, +}; use halo2_proofs::{ dev::MockProver, halo2curves::bn256::{Bn256, Fq, Fr, G1Affine}, @@ -17,16 +21,18 @@ use halo2_proofs::{ }; use itertools::Itertools; use rand::rngs::OsRng; +#[cfg(feature = "revm")] +use snark_verifier::loader::evm::{deploy_and_call, encode_calldata}; use snark_verifier::{ loader::{ - evm::{self, encode_calldata, Address, EvmLoader, ExecutorBuilder}, + evm::{self, EvmLoader}, native::NativeLoader, }, pcs::kzg::{Gwc19, KzgAs, LimbsEncoding}, system::halo2::{compile, transcript::evm::EvmTranscript, Config}, verifier::{self, SnarkVerifier}, }; -use std::{env::set_var, fs::File, io::Cursor, rc::Rc}; +use std::{fs::File, io::Cursor, rc::Rc}; const LIMBS: usize = 3; const BITS: usize = 88; @@ -198,22 +204,11 @@ mod application { mod aggregation { use crate::PlonkSuccinctVerifier; - use super::halo2_proofs::{ - circuit::{Layouter, SimpleFloorPlanner}, - plonk::{self, Circuit, Column, Instance}, - }; use super::{As, BITS, LIMBS}; use super::{Fr, G1Affine}; - use halo2_base::{ - gates::{ - builder::{ - assign_threads_in, CircuitBuilderStage, FlexGateConfigParams, GateThreadBuilder, - MultiPhaseThreadBreakPoints, RangeCircuitBuilder, - }, - range::RangeConfig, - RangeChip, - }, - AssignedValue, SKIP_FIRST_PASS, + use halo2_base::gates::{ + circuit::{builder::BaseCircuitBuilder, BaseCircuitParams, CircuitBuilderStage}, + flex_gate::MultiPhaseThreadBreakPoints, }; use halo2_ecc::bn254::FpChip; use itertools::Itertools; @@ -228,7 +223,7 @@ mod aggregation { util::arithmetic::fe_to_limbs, verifier::{plonk::PlonkProtocol, SnarkVerifier}, }; - use std::{collections::HashMap, rc::Rc}; + use std::{mem, rc::Rc}; const T: usize = 3; const RATE: usize = 2; @@ -300,7 +295,7 @@ mod aggregation { As::verify(&Default::default(), &accumulators, &proof).unwrap() } - #[derive(serde::Serialize, serde::Deserialize)] + #[derive(serde::Serialize, serde::Deserialize, Default)] pub struct AggregationConfigParams { pub degree: u32, pub num_advice: usize, @@ -309,24 +304,17 @@ mod aggregation { pub lookup_bits: usize, } - #[derive(Clone)] - pub struct AggregationConfig { - pub range: RangeConfig, - pub instance: Column, - } - #[derive(Clone, Debug)] pub struct AggregationCircuit { - pub circuit: RangeCircuitBuilder, + pub inner: BaseCircuitBuilder, pub as_proof: Vec, - pub assigned_instances: Vec>, } impl AggregationCircuit { pub fn new( stage: CircuitBuilderStage, + circuit_params: BaseCircuitParams, break_points: Option, - lookup_bits: usize, params_g0: G1Affine, snarks: impl IntoIterator, ) -> Self { @@ -361,18 +349,15 @@ mod aggregation { (accumulator, transcript.finalize()) }; - // create thread builder and run aggregation witness gen - let builder = match stage { - CircuitBuilderStage::Mock => GateThreadBuilder::mock(), - CircuitBuilderStage::Prover => GateThreadBuilder::prover(), - CircuitBuilderStage::Keygen => GateThreadBuilder::keygen(), - }; + let mut builder = BaseCircuitBuilder::from_stage(stage).use_params(circuit_params); // create halo2loader - let range = RangeChip::::default(lookup_bits); + let range = builder.range_chip(); let fp_chip = FpChip::::new(&range, BITS, LIMBS); let ecc_chip = BaseFieldEccChip::new(&fp_chip); - let loader = Halo2Loader::new(ecc_chip, builder); + let pool = mem::take(builder.pool(0)); + let loader = Halo2Loader::new(ecc_chip, pool); + // witness generation let KzgAccumulator { lhs, rhs } = aggregate(&svk, &loader, &snarks, as_proof.as_slice()); let lhs = lhs.assigned(); @@ -397,23 +382,12 @@ mod aggregation { } } - let builder = loader.take_ctx(); - let circuit = match stage { - CircuitBuilderStage::Mock => RangeCircuitBuilder::mock(builder), - CircuitBuilderStage::Keygen => RangeCircuitBuilder::keygen(builder), - CircuitBuilderStage::Prover => { - RangeCircuitBuilder::prover(builder, break_points.unwrap()) - } - }; - Self { circuit, as_proof, assigned_instances } - } - - pub fn config(&self, k: u32, minimum_rows: Option) -> FlexGateConfigParams { - self.circuit.0.builder.borrow().config(k as usize, minimum_rows) - } - - pub fn break_points(&self) -> MultiPhaseThreadBreakPoints { - self.circuit.0.break_points.borrow().clone() + *builder.pool(0) = loader.take_ctx(); + builder.assigned_instances[0] = assigned_instances; + if let Some(break_points) = break_points { + builder.set_break_points(break_points); + } + Self { inner: builder, as_proof } } pub fn num_instance() -> Vec { @@ -422,108 +396,17 @@ mod aggregation { } pub fn instances(&self) -> Vec> { - vec![self.assigned_instances.iter().map(|v| *v.value()).collect_vec()] + self.inner + .assigned_instances + .iter() + .map(|v| v.iter().map(|v| *v.value()).collect_vec()) + .collect() } pub fn accumulator_indices() -> Vec<(usize, usize)> { (0..4 * LIMBS).map(|idx| (0, idx)).collect() } } - - impl Circuit for AggregationCircuit { - type Config = AggregationConfig; - type FloorPlanner = SimpleFloorPlanner; - - fn without_witnesses(&self) -> Self { - unimplemented!() - } - - fn configure(meta: &mut plonk::ConstraintSystem) -> Self::Config { - let range = RangeCircuitBuilder::configure(meta); - let instance = meta.instance_column(); - meta.enable_equality(instance); - AggregationConfig { range, instance } - } - - fn synthesize( - &self, - config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), plonk::Error> { - // copied from RangeCircuitBuilder::synthesize but with extra logic to expose public instances - let range = config.range; - let circuit = &self.circuit.0; - range.load_lookup_table(&mut layouter).expect("load lookup table should not fail"); - - // we later `take` the builder, so we need to save this value - let witness_gen_only = circuit.builder.borrow().witness_gen_only(); - let mut assigned_advices = HashMap::new(); - - let mut first_pass = SKIP_FIRST_PASS; - layouter - .assign_region( - || "AggregationCircuit", - |mut region| { - if first_pass { - first_pass = false; - return Ok(()); - } - // only support FirstPhase in this Builder because getting challenge value requires more specialized witness generation during synthesize - if !witness_gen_only { - // clone the builder so we can re-use the circuit for both vk and pk gen - let builder = circuit.builder.borrow(); - let assignments = builder.assign_all( - &range.gate, - &range.lookup_advice, - &range.q_lookup, - &mut region, - Default::default(), - ); - *circuit.break_points.borrow_mut() = assignments.break_points; - assigned_advices = assignments.assigned_advices; - } else { - #[cfg(feature = "display")] - let start0 = std::time::Instant::now(); - let builder = circuit.builder.take(); - let break_points = circuit.break_points.take(); - for (phase, (threads, break_points)) in builder - .threads - .into_iter() - .zip(break_points.into_iter()) - .enumerate() - .take(1) - { - assign_threads_in( - phase, - threads, - &range.gate, - &range.lookup_advice[phase], - &mut region, - break_points, - ); - } - #[cfg(feature = "display")] - println!("assign threads in {:?}", start0.elapsed()); - } - Ok(()) - }, - ) - .unwrap(); - - if !witness_gen_only { - // expose public instances - let mut layouter = layouter.namespace(|| "expose"); - for (i, instance) in self.assigned_instances.iter().enumerate() { - let cell = instance.cell.unwrap(); - let (cell, _) = assigned_advices - .get(&(cell.context_id, cell.offset)) - .expect("instance not assigned"); - layouter.constrain_instance(*cell, config.instance, i); - } - } - Ok(()) - } - } } fn gen_pk>(params: &ParamsKZG, circuit: &C) -> ProvingKey { @@ -620,23 +503,14 @@ fn gen_aggregation_evm_verifier( let proof = PlonkVerifier::read_proof(&vk, &protocol, &instances, &mut transcript).unwrap(); PlonkVerifier::verify(&vk, &protocol, &instances, &proof).unwrap(); - evm::compile_yul(&loader.yul_code()) + evm::compile_solidity(&loader.solidity_code()) } +#[cfg(feature = "revm")] fn evm_verify(deployment_code: Vec, instances: Vec>, proof: Vec) { let calldata = encode_calldata(&instances, &proof); - let success = { - let mut evm = ExecutorBuilder::default().with_gas_limit(u64::MAX.into()).build(); - - let caller = Address::from_low_u64_be(0xfe); - let verifier = evm.deploy(caller, deployment_code.into(), 0.into()).address.unwrap(); - let result = evm.call_raw(caller, verifier, calldata.into(), 0.into()); - - dbg!(result.gas_used); - - !result.reverted - }; - assert!(success); + let gas_cost = deploy_and_call(deployment_code, calldata).unwrap(); + dbg!(gas_cost); } fn main() { @@ -649,48 +523,56 @@ fn main() { File::open(path).unwrap_or_else(|e| panic!("{path} does not exist: {e:?}")), ) .unwrap(); - let agg_circuit = AggregationCircuit::new( + let mut circuit_params = BaseCircuitParams { + k: agg_config.degree as usize, + num_advice_per_phase: vec![agg_config.num_advice], + num_lookup_advice_per_phase: vec![agg_config.num_lookup_advice], + num_fixed: agg_config.num_fixed, + lookup_bits: Some(agg_config.lookup_bits), + num_instance_columns: 1, + }; + let mut agg_circuit = AggregationCircuit::new( CircuitBuilderStage::Mock, + circuit_params, None, - agg_config.lookup_bits, params_app.get_g()[0], snarks.clone(), ); - agg_circuit.config(agg_config.degree, Some(6)); - set_var("LOOKUP_BITS", agg_config.lookup_bits.to_string()); + circuit_params = agg_circuit.inner.calculate_params(Some(9)); #[cfg(debug_assertions)] { - MockProver::run(agg_config.degree, &agg_circuit, agg_circuit.instances()) + MockProver::run(agg_config.degree, &agg_circuit.inner, agg_circuit.instances()) .unwrap() .assert_satisfied(); println!("mock prover passed"); } let params = gen_srs(agg_config.degree); - let pk = gen_pk(¶ms, &agg_circuit); - let deployment_code = gen_aggregation_evm_verifier( + let pk = gen_pk(¶ms, &agg_circuit.inner); + let _deployment_code = gen_aggregation_evm_verifier( ¶ms, pk.get_vk(), aggregation::AggregationCircuit::num_instance(), aggregation::AggregationCircuit::accumulator_indices(), ); - let break_points = agg_circuit.break_points(); + let break_points = agg_circuit.inner.break_points(); drop(agg_circuit); let agg_circuit = AggregationCircuit::new( CircuitBuilderStage::Prover, + circuit_params, Some(break_points), - agg_config.lookup_bits, params_app.get_g()[0], snarks, ); let instances = agg_circuit.instances(); - let proof = gen_proof::<_, _, EvmTranscript, EvmTranscript>( - ¶ms, - &pk, - agg_circuit, - instances.clone(), - ); - evm_verify(deployment_code, instances, proof); + let _proof = gen_proof::< + _, + _, + EvmTranscript, + EvmTranscript, + >(¶ms, &pk, agg_circuit.inner, instances.clone()); + #[cfg(feature = "revm")] + evm_verify(_deployment_code, instances, _proof); } diff --git a/snark-verifier/examples/evm-verifier.rs b/snark-verifier/examples/evm-verifier.rs index 5b2aa802..9bd8c61d 100644 --- a/snark-verifier/examples/evm-verifier.rs +++ b/snark-verifier/examples/evm-verifier.rs @@ -20,8 +20,10 @@ use halo2_proofs::{ }; use itertools::Itertools; use rand::{rngs::OsRng, RngCore}; +#[cfg(feature = "revm")] +use snark_verifier::loader::evm::{deploy_and_call, encode_calldata}; use snark_verifier::{ - loader::evm::{self, encode_calldata, Address, EvmLoader, ExecutorBuilder}, + loader::evm::{self, EvmLoader}, pcs::kzg::{Gwc19, KzgAs}, system::halo2::{compile, transcript::evm::EvmTranscript, Config}, verifier::{self, SnarkVerifier}, @@ -237,23 +239,14 @@ fn gen_evm_verifier( let proof = PlonkVerifier::read_proof(&vk, &protocol, &instances, &mut transcript).unwrap(); PlonkVerifier::verify(&vk, &protocol, &instances, &proof).unwrap(); - evm::compile_yul(&loader.yul_code()) + evm::compile_solidity(&loader.solidity_code()) } +#[cfg(feature = "revm")] fn evm_verify(deployment_code: Vec, instances: Vec>, proof: Vec) { let calldata = encode_calldata(&instances, &proof); - let success = { - let mut evm = ExecutorBuilder::default().with_gas_limit(u64::MAX.into()).build(); - - let caller = Address::from_low_u64_be(0xfe); - let verifier = evm.deploy(caller, deployment_code.into(), 0.into()).address.unwrap(); - let result = evm.call_raw(caller, verifier, calldata.into(), 0.into()); - - dbg!(result.gas_used); - - !result.reverted - }; - assert!(success); + let gas_cost = deploy_and_call(deployment_code, calldata).unwrap(); + dbg!(gas_cost); } fn main() { @@ -261,8 +254,9 @@ fn main() { let circuit = StandardPlonk::rand(OsRng); let pk = gen_pk(¶ms, &circuit); - let deployment_code = gen_evm_verifier(¶ms, pk.get_vk(), StandardPlonk::num_instance()); + let _deployment_code = gen_evm_verifier(¶ms, pk.get_vk(), StandardPlonk::num_instance()); - let proof = gen_proof(¶ms, &pk, circuit.clone(), circuit.instances()); - evm_verify(deployment_code, circuit.instances(), proof); + let _proof = gen_proof(¶ms, &pk, circuit.clone(), circuit.instances()); + #[cfg(feature = "revm")] + evm_verify(_deployment_code, circuit.instances(), _proof); } diff --git a/snark-verifier/examples/recursion.rs b/snark-verifier/examples/recursion.rs index 5829e1b7..da34cb82 100644 --- a/snark-verifier/examples/recursion.rs +++ b/snark-verifier/examples/recursion.rs @@ -2,20 +2,18 @@ use ark_std::{end_timer, start_timer}; use common::*; -use halo2_base::gates::flex_gate::GateStrategy; use halo2_base::utils::fs::gen_srs; -use halo2_base::{gates::builder::FlexGateConfigParams, halo2_proofs}; +use halo2_base::{gates::circuit::BaseCircuitParams, halo2_proofs}; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner}, dev::MockProver, halo2curves::{ bn256::{Bn256, Fr, G1Affine}, group::ff::Field, - FieldExt, }, plonk::{ - self, create_proof, keygen_pk, keygen_vk, Circuit, ConstraintSystem, Error, ProvingKey, - Selector, VerifyingKey, + create_proof, keygen_pk, keygen_vk, Circuit, ConstraintSystem, Error, ProvingKey, Selector, + VerifyingKey, }, poly::{ commitment::ParamsProver, @@ -46,7 +44,7 @@ use snark_verifier::{ SnarkVerifier, }, }; -use std::{env::set_var, fs, iter, marker::PhantomData, rc::Rc}; +use std::{fs, iter, marker::PhantomData, rc::Rc}; use crate::recursion::AggregationConfigParams; @@ -191,19 +189,38 @@ mod common { pub fn gen_dummy_snark>( params: &ParamsKZG, vk: Option<&VerifyingKey>, - ) -> Snark { - struct CsProxy(PhantomData<(F, C)>); + config_params: ConcreteCircuit::Params, + ) -> Snark + where + ConcreteCircuit::Params: Clone, + { + struct CsProxy>(C::Params, PhantomData<(F, C)>); - impl> Circuit for CsProxy { + impl> Circuit for CsProxy + where + C::Params: Clone, + { type Config = C::Config; type FloorPlanner = C::FloorPlanner; + type Params = C::Params; + + fn params(&self) -> Self::Params { + self.0.clone() + } fn without_witnesses(&self) -> Self { - CsProxy(PhantomData) + CsProxy(self.0.clone(), PhantomData) } - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - C::configure(meta) + fn configure_with_params( + meta: &mut ConstraintSystem, + params: Self::Params, + ) -> Self::Config { + C::configure_with_params(meta, params) + } + + fn configure(_: &mut ConstraintSystem) -> Self::Config { + unreachable!() } fn synthesize( @@ -226,9 +243,9 @@ mod common { } } - let dummy_vk = vk - .is_none() - .then(|| keygen_vk(params, &CsProxy::(PhantomData)).unwrap()); + let dummy_vk = vk.is_none().then(|| { + keygen_vk(params, &CsProxy::(config_params, PhantomData)).unwrap() + }); let protocol = compile( params, vk.or(dummy_vk.as_ref()).unwrap(), @@ -323,18 +340,16 @@ mod application { } mod recursion { - use std::{collections::HashMap, env::var}; + use std::mem; use halo2_base::{ gates::{ - builder::{GateThreadBuilder, RangeCircuitBuilder}, - range::RangeConfig, - GateInstructions, RangeChip, RangeInstructions, + circuit::{builder::BaseCircuitBuilder, BaseCircuitParams, BaseConfig}, + GateInstructions, RangeInstructions, }, AssignedValue, }; use halo2_ecc::{bn254::FpChip, ecc::EcPoint}; - use halo2_proofs::plonk::{Column, Instance}; use snark_verifier::loader::halo2::{EccInstructions, IntegerInstructions}; use super::*; @@ -358,7 +373,7 @@ mod recursion { ) -> (Vec>>, Vec>>>) { let protocol = if let Some(preprocessed_digest) = preprocessed_digest { let preprocessed_digest = loader.scalar_from_assigned(preprocessed_digest); - let protocol = snark.protocol.loaded_preprocessed_as_witness(loader); + let protocol = snark.protocol.loaded_preprocessed_as_witness(loader, false); let inputs = protocol .preprocessed .iter() @@ -411,9 +426,9 @@ mod recursion { .zip([rhs.lhs.assigned(), rhs.rhs.assigned()].iter()) .map(|(lhs, rhs)| { loader.ecc_chip().select( - loader.ctx_mut().main(0), - EcPoint::clone(&lhs), - EcPoint::clone(&rhs), + loader.ctx_mut().main(), + EcPoint::clone(lhs), + EcPoint::clone(rhs), *condition, ) }) @@ -446,24 +461,18 @@ mod recursion { pub lookup_bits: usize, } - #[derive(Clone)] - pub struct RecursionConfig { - pub range: RangeConfig, - pub instance: Column, - } - #[derive(Clone)] pub struct RecursionCircuit { svk: Svk, default_accumulator: KzgAccumulator, app: Snark, previous: Snark, + #[allow(dead_code)] round: usize, instances: Vec, as_proof: Vec, - inner: RangeCircuitBuilder, - assigned_instances: Vec>, + inner: BaseCircuitBuilder, } impl RecursionCircuit { @@ -479,6 +488,7 @@ mod recursion { initial_state: Fr, state: Fr, round: usize, + config_params: BaseCircuitParams, ) -> Self { let svk = params.get_g()[0].into(); let default_accumulator = KzgAccumulator::new(params.get_g()[1], params.get_g()[0]); @@ -533,42 +543,30 @@ mod recursion { .chain([preprocessed_digest, initial_state, state, Fr::from(round as u64)]) .collect(); - let builder = GateThreadBuilder::mock(); - let inner = RangeCircuitBuilder::mock(builder); - let mut circuit = Self { - svk, - default_accumulator, - app: app, - previous: previous, - round, - instances, - as_proof, - inner, - assigned_instances: vec![], - }; + let inner = BaseCircuitBuilder::new(false).use_params(config_params); + let mut circuit = + Self { svk, default_accumulator, app, previous, round, instances, as_proof, inner }; circuit.build(); circuit } fn build(&mut self) { - let lookup_bits = var("LOOKUP_BITS").unwrap().parse().unwrap(); - let range = RangeChip::::default(lookup_bits); + let range = self.inner.range_chip(); let main_gate = range.gate(); - let mut builder = GateThreadBuilder::mock(); - let ctx = &mut builder; + let pool = self.inner.pool(0); let [preprocessed_digest, initial_state, state, round] = [ self.instances[Self::PREPROCESSED_DIGEST_ROW], self.instances[Self::INITIAL_STATE_ROW], self.instances[Self::STATE_ROW], self.instances[Self::ROUND_ROW], ] - .map(|instance| main_gate.assign_integer(ctx, instance)); - let first_round = main_gate.is_zero(ctx.main(0), round); - let not_first_round = main_gate.not(ctx.main(0), first_round); + .map(|instance| main_gate.assign_integer(pool, instance)); + let first_round = main_gate.is_zero(pool.main(), round); + let not_first_round = main_gate.not(pool.main(), first_round); let fp_chip = FpChip::::new(&range, BITS, LIMBS); let ecc_chip = BaseFieldEccChip::new(&fp_chip); - let loader = Halo2Loader::new(ecc_chip, builder); + let loader = Halo2Loader::new(ecc_chip, mem::take(self.inner.pool(0))); let (mut app_instances, app_accumulators) = succinct_verify(&self.svk, &loader, &self.app, None); let (mut previous_instances, previous_accumulators) = @@ -599,8 +597,8 @@ mod recursion { let app_instances = app_instances.pop().unwrap(); let previous_instances = previous_instances.pop().unwrap(); - let mut builder = loader.take_ctx(); - let ctx = builder.main(0); + let mut pool = loader.take_ctx(); + let ctx = pool.main(); for (lhs, rhs) in [ // Propagate preprocessed_digest ( @@ -629,9 +627,9 @@ mod recursion { ] { ctx.constrain_equal(lhs, rhs); } - *self.inner.0.builder.borrow_mut() = builder; + *self.inner.pool(0) = pool; - self.assigned_instances.extend( + self.inner.assigned_instances[0].extend( [lhs.x(), lhs.y(), rhs.x(), rhs.y()] .into_iter() .flat_map(|coordinate| coordinate.limbs()) @@ -640,8 +638,12 @@ mod recursion { ); } - fn initial_snark(params: &ParamsKZG, vk: Option<&VerifyingKey>) -> Snark { - let mut snark = gen_dummy_snark::(params, vk); + fn initial_snark( + params: &ParamsKZG, + vk: Option<&VerifyingKey>, + config_params: BaseCircuitParams, + ) -> Snark { + let mut snark = gen_dummy_snark::(params, vk, config_params); let g = params.get_g(); snark.instances = vec![[g[1].x, g[1].y, g[0].x, g[0].y] .into_iter() @@ -670,67 +672,35 @@ mod recursion { } impl Circuit for RecursionCircuit { - type Config = RecursionConfig; + type Config = BaseConfig; type FloorPlanner = SimpleFloorPlanner; + type Params = BaseCircuitParams; + + fn params(&self) -> Self::Params { + self.inner.params() + } fn without_witnesses(&self) -> Self { unimplemented!() } - fn configure(meta: &mut plonk::ConstraintSystem) -> Self::Config { - let range = RangeCircuitBuilder::configure(meta); - let instance = meta.instance_column(); - meta.enable_equality(instance); - RecursionConfig { range, instance } + fn configure_with_params( + meta: &mut ConstraintSystem, + params: Self::Params, + ) -> Self::Config { + BaseCircuitBuilder::configure_with_params(meta, params) + } + + fn configure(_: &mut ConstraintSystem) -> Self::Config { + unreachable!() } fn synthesize( &self, config: Self::Config, - mut layouter: impl Layouter, + layouter: impl Layouter, ) -> Result<(), Error> { - let range = config.range; - range.load_lookup_table(&mut layouter).expect("load lookup table should not fail"); - let circuit = &self.inner.0; - - let mut assigned_advices = HashMap::new(); - // POC so will only do mock prover and not real prover - let mut first_pass = halo2_base::SKIP_FIRST_PASS; // assume using simple floor planner - layouter - .assign_region( - || "Recursion Circuit", - |mut region| { - if first_pass { - first_pass = false; - return Ok(()); - } - // clone the builder so we can re-use the circuit for both vk and pk gen - let builder = circuit.builder.borrow(); - let assignments = builder.assign_all( - &range.gate, - &range.lookup_advice, - &range.q_lookup, - &mut region, - Default::default(), - ); - *circuit.break_points.borrow_mut() = assignments.break_points; - assigned_advices = assignments.assigned_advices; - Ok(()) - }, - ) - .unwrap(); - - // expose public instances - let mut layouter = layouter.namespace(|| "expose"); - for (i, instance) in self.assigned_instances.iter().enumerate() { - let cell = instance.cell.unwrap(); - let (cell, _) = assigned_advices - .get(&(cell.context_id, cell.offset)) - .expect("instance not assigned"); - layouter.constrain_instance(*cell, config.instance, i); - } - - Ok(()) + self.inner.synthesize(config, layouter) } } @@ -749,7 +719,7 @@ mod recursion { } fn selectors(config: &Self::Config) -> Vec { - config.range.gate.basic_gates[0].iter().map(|gate| gate.q_enable).collect() + config.gate().basic_gates[0].iter().map(|gate| gate.q_enable).collect() } } @@ -757,14 +727,20 @@ mod recursion { recursion_params: &ParamsKZG, app_params: &ParamsKZG, app_vk: &VerifyingKey, - ) -> ProvingKey { + recursion_config: BaseCircuitParams, + app_config: ConcreteCircuit::Params, + ) -> ProvingKey + where + ConcreteCircuit::Params: Clone, + { let recursion = RecursionCircuit::new( recursion_params, - gen_dummy_snark::(app_params, Some(app_vk)), - RecursionCircuit::initial_snark(recursion_params, None), + gen_dummy_snark::(app_params, Some(app_vk), app_config), + RecursionCircuit::initial_snark(recursion_params, None, recursion_config.clone()), Fr::zero(), Fr::zero(), 0, + recursion_config, ); // we cannot auto-configure the circuit because dummy_snark must know the configuration beforehand // uncomment the following line only in development to test and print out the optimal configuration ahead of time @@ -779,11 +755,15 @@ mod recursion { recursion_pk: &ProvingKey, initial_state: Fr, inputs: Vec, + config_params: BaseCircuitParams, ) -> (Fr, Snark) { let mut state = initial_state; let mut app = ConcreteCircuit::new(state); - let mut previous = - RecursionCircuit::initial_snark(recursion_params, Some(recursion_pk.get_vk())); + let mut previous = RecursionCircuit::initial_snark( + recursion_params, + Some(recursion_pk.get_vk()), + config_params.clone(), + ); for (round, input) in inputs.into_iter().enumerate() { state = app.state_transition(input); println!("Generate app snark"); @@ -795,6 +775,7 @@ mod recursion { initial_state, state, round, + config_params.clone(), ); println!("Generate recursion snark"); previous = gen_snark(recursion_params, recursion_pk, recursion); @@ -805,20 +786,19 @@ mod recursion { } fn main() { - let app_params = gen_srs(3); + let app_params = gen_srs(5); let recursion_config: AggregationConfigParams = serde_json::from_reader(fs::File::open("configs/example_recursion.json").unwrap()).unwrap(); let k = recursion_config.degree; let recursion_params = gen_srs(k); - let flex_gate_config = FlexGateConfigParams { - strategy: GateStrategy::Vertical, + let config_params = BaseCircuitParams { k: k as usize, num_advice_per_phase: vec![recursion_config.num_advice], num_lookup_advice_per_phase: vec![recursion_config.num_lookup_advice], num_fixed: recursion_config.num_fixed, + lookup_bits: Some(recursion_config.lookup_bits), + num_instance_columns: 1, }; - set_var("FLEX_GATE_CONFIG_PARAMS", serde_json::to_string(&flex_gate_config).unwrap()); - set_var("LOOKUP_BITS", recursion_config.lookup_bits.to_string()); let app_pk = gen_pk(&app_params, &application::Square::default()); @@ -827,6 +807,8 @@ fn main() { &recursion_params, &app_params, app_pk.get_vk(), + config_params.clone(), + (), ); end_timer!(pk_time); @@ -839,9 +821,10 @@ fn main() { &recursion_pk, Fr::from(2u64), vec![(); num_round], + config_params.clone(), ); end_timer!(pf_time); - assert_eq!(final_state, Fr::from(2u64).pow(&[1 << num_round, 0, 0, 0])); + assert_eq!(final_state, Fr::from(2u64).pow([1 << num_round])); { let dk = diff --git a/snark-verifier/src/lib.rs b/snark-verifier/src/lib.rs index e9866167..8dab89c9 100644 --- a/snark-verifier/src/lib.rs +++ b/snark-verifier/src/lib.rs @@ -13,6 +13,10 @@ pub mod verifier; pub(crate) use halo2_base::halo2_proofs; pub(crate) use halo2_proofs::halo2curves as halo2_curves; +pub use halo2_base; +#[cfg(feature = "loader_halo2")] +pub use halo2_ecc; + /// Error that could happen while verification. #[derive(Clone, Debug)] pub enum Error { diff --git a/snark-verifier/src/loader.rs b/snark-verifier/src/loader.rs index 77a8f54b..26450e1a 100644 --- a/snark-verifier/src/loader.rs +++ b/snark-verifier/src/loader.rs @@ -67,6 +67,12 @@ pub trait LoadedScalar: Clone + Debug + PartialEq + FieldOps { acc } + /// Returns power to exponent, where exponent is also [`LoadedScalar`]. + /// If `Loader` is for Halo2, then `exp` must have at most `exp_max_bits` bits (otherwise constraints will fail). + /// + /// Currently **unimplemented** for EvmLoader + fn pow_var(&self, exp: &Self, exp_max_bits: usize) -> Self; + /// Returns powers up to exponent `n-1`. fn powers(&self, n: usize) -> Vec { iter::once(self.loader().load_one()) @@ -122,12 +128,12 @@ pub trait ScalarLoader { /// Load `zero` as constant. fn load_zero(&self) -> Self::LoadedScalar { - self.load_const(&F::zero()) + self.load_const(&F::ZERO) } /// Load `one` as constant. fn load_one(&self) -> Self::LoadedScalar { - self.load_const(&F::one()) + self.load_const(&F::ONE) } /// Assert lhs and rhs field elements are equal. @@ -145,13 +151,13 @@ pub trait ScalarLoader { let loader = values.first().unwrap().1.loader(); iter::empty() - .chain(if constant == F::zero() { + .chain(if constant == F::ZERO { None } else { Some(Cow::Owned(loader.load_const(&constant))) }) .chain(values.iter().map(|&(coeff, value)| { - if coeff == F::one() { + if coeff == F::ONE { Cow::Borrowed(value) } else { Cow::Owned(loader.load_const(&coeff) * value) @@ -174,9 +180,9 @@ pub trait ScalarLoader { let loader = values.first().unwrap().1.loader(); iter::empty() - .chain(if constant == F::zero() { None } else { Some(loader.load_const(&constant)) }) + .chain(if constant == F::ZERO { None } else { Some(loader.load_const(&constant)) }) .chain(values.iter().map(|&(coeff, lhs, rhs)| { - if coeff == F::one() { + if coeff == F::ONE { lhs.clone() * rhs } else { loader.load_const(&coeff) * lhs * rhs @@ -188,20 +194,20 @@ pub trait ScalarLoader { /// Sum field elements with coefficients. fn sum_with_coeff(&self, values: &[(F, &Self::LoadedScalar)]) -> Self::LoadedScalar { - self.sum_with_coeff_and_const(values, F::zero()) + self.sum_with_coeff_and_const(values, F::ZERO) } /// Sum field elements and constant. fn sum_with_const(&self, values: &[&Self::LoadedScalar], constant: F) -> Self::LoadedScalar { self.sum_with_coeff_and_const( - &values.iter().map(|&value| (F::one(), value)).collect_vec(), + &values.iter().map(|&value| (F::ONE, value)).collect_vec(), constant, ) } /// Sum field elements. fn sum(&self, values: &[&Self::LoadedScalar]) -> Self::LoadedScalar { - self.sum_with_const(values, F::zero()) + self.sum_with_const(values, F::ZERO) } /// Sum product of field elements with coefficients. @@ -209,7 +215,7 @@ pub trait ScalarLoader { &self, values: &[(F, &Self::LoadedScalar, &Self::LoadedScalar)], ) -> Self::LoadedScalar { - self.sum_products_with_coeff_and_const(values, F::zero()) + self.sum_products_with_coeff_and_const(values, F::ZERO) } /// Sum product of field elements and constant. @@ -219,7 +225,7 @@ pub trait ScalarLoader { constant: F, ) -> Self::LoadedScalar { self.sum_products_with_coeff_and_const( - &values.iter().map(|&(lhs, rhs)| (F::one(), lhs, rhs)).collect_vec(), + &values.iter().map(|&(lhs, rhs)| (F::ONE, lhs, rhs)).collect_vec(), constant, ) } @@ -229,7 +235,7 @@ pub trait ScalarLoader { &self, values: &[(&Self::LoadedScalar, &Self::LoadedScalar)], ) -> Self::LoadedScalar { - self.sum_products_with_const(values, F::zero()) + self.sum_products_with_const(values, F::ZERO) } /// Product of field elements. diff --git a/snark-verifier/src/loader/evm.rs b/snark-verifier/src/loader/evm.rs index e942b4a3..9ab472db 100644 --- a/snark-verifier/src/loader/evm.rs +++ b/snark-verifier/src/loader/evm.rs @@ -4,14 +4,10 @@ mod code; pub(crate) mod loader; pub(crate) mod util; -#[cfg(test)] -mod test; - pub use loader::{EcPoint, EvmLoader, Scalar}; pub use util::{ - compile_yul, encode_calldata, estimate_gas, fe_to_u256, modulus, u256_to_fe, Address, - ExecutorBuilder, H256, U256, U512, + compile_solidity, encode_calldata, estimate_gas, fe_to_u256, modulus, + u256_to_fe, Address, B256, U256, U512, }; - -#[cfg(test)] -pub use test::execute; +#[cfg(feature = "revm")] +pub use util::deploy_and_call; diff --git a/snark-verifier/src/loader/evm/code.rs b/snark-verifier/src/loader/evm/code.rs index 2fec71d2..eee4fb3e 100644 --- a/snark-verifier/src/loader/evm/code.rs +++ b/snark-verifier/src/loader/evm/code.rs @@ -6,57 +6,55 @@ pub enum Precompiled { } #[derive(Clone, Debug)] -pub struct YulCode { +pub struct SolidityAssemblyCode { // runtime code area runtime: String, } -impl YulCode { +impl SolidityAssemblyCode { pub fn new() -> Self { - YulCode { - runtime: String::new(), - } + Self { runtime: String::new() } } pub fn code(&self, base_modulus: String, scalar_modulus: String) -> String { format!( " - object \"plonk_verifier\" {{ - code {{ - function allocate(size) -> ptr {{ - ptr := mload(0x40) - if eq(ptr, 0) {{ ptr := 0x60 }} - mstore(0x40, add(ptr, size)) - }} - let size := datasize(\"Runtime\") - let offset := allocate(size) - datacopy(offset, dataoffset(\"Runtime\"), size) - return(offset, size) +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.19; + +contract Halo2Verifier {{ + fallback(bytes calldata) external returns (bytes memory) {{ + assembly (\"memory-safe\") {{ + // Enforce that Solidity memory layout is respected + let data := mload(0x40) + if iszero(eq(data, 0x80)) {{ + revert(0, 0) }} - object \"Runtime\" {{ - code {{ - let success:bool := true - let f_p := {base_modulus} - let f_q := {scalar_modulus} - function validate_ec_point(x, y) -> valid:bool {{ - {{ - let x_lt_p:bool := lt(x, {base_modulus}) - let y_lt_p:bool := lt(y, {base_modulus}) - valid := and(x_lt_p, y_lt_p) - }} - {{ - let y_square := mulmod(y, y, {base_modulus}) - let x_square := mulmod(x, x, {base_modulus}) - let x_cube := mulmod(x_square, x, {base_modulus}) - let x_cube_plus_3 := addmod(x_cube, 3, {base_modulus}) - let is_affine:bool := eq(x_cube_plus_3, y_square) - valid := and(valid, is_affine) - }} - }} - {} + + let success := true + let f_p := {base_modulus} + let f_q := {scalar_modulus} + function validate_ec_point(x, y) -> valid {{ + {{ + let x_lt_p := lt(x, {base_modulus}) + let y_lt_p := lt(y, {base_modulus}) + valid := and(x_lt_p, y_lt_p) + }} + {{ + let y_square := mulmod(y, y, {base_modulus}) + let x_square := mulmod(x, x, {base_modulus}) + let x_cube := mulmod(x_square, x, {base_modulus}) + let x_cube_plus_3 := addmod(x_cube, 3, {base_modulus}) + let is_affine := eq(x_cube_plus_3, y_square) + valid := and(valid, is_affine) }} }} - }}", + {} + }} + }} +}} + ", self.runtime ) } diff --git a/snark-verifier/src/loader/evm/loader.rs b/snark-verifier/src/loader/evm/loader.rs index 98ca5ca4..af2795c1 100644 --- a/snark-verifier/src/loader/evm/loader.rs +++ b/snark-verifier/src/loader/evm/loader.rs @@ -1,7 +1,7 @@ use crate::{ loader::{ evm::{ - code::{Precompiled, YulCode}, + code::{Precompiled, SolidityAssemblyCode}, fe_to_u256, modulus, u256_to_fe, U256, U512, }, EcPointLoader, LoadedEcPoint, LoadedScalar, Loader, ScalarLoader, @@ -21,6 +21,9 @@ use std::{ rc::Rc, }; +/// Memory pointer starts at 0x80, which is the end of the Solidity memory layout scratch space. +pub const MEM_PTR_START: usize = 0x80; + #[derive(Clone, Debug)] pub enum Value { Constant(T), @@ -52,17 +55,13 @@ impl Value { pub struct EvmLoader { base_modulus: U256, scalar_modulus: U256, - code: RefCell, + code: RefCell, ptr: RefCell, cache: RefCell>, - #[cfg(test)] - gas_metering_ids: RefCell>, } fn hex_encode_u256(value: &U256) -> String { - let mut bytes = [0; 32]; - value.to_big_endian(&mut bytes); - format!("0x{}", hex::encode(bytes)) + format!("0x{}", hex::encode(value.to_be_bytes::<32>())) } impl EvmLoader { @@ -74,23 +73,25 @@ impl EvmLoader { { let base_modulus = modulus::(); let scalar_modulus = modulus::(); - let code = YulCode::new(); + let code = SolidityAssemblyCode::new(); Rc::new(Self { base_modulus, scalar_modulus, code: RefCell::new(code), - ptr: Default::default(), + ptr: RefCell::new(MEM_PTR_START), cache: Default::default(), - #[cfg(test)] - gas_metering_ids: RefCell::new(Vec::new()), }) } - /// Returns generated yul code. - pub fn yul_code(self: &Rc) -> String { + /// Returns generated Solidity code. This is "Solidity" code that is wrapped in an assembly block. + /// In other words, it's basically just assembly (equivalently, Yul). + pub fn solidity_code(self: &Rc) -> String { let code = " - if not(success) { revert(0, 0) } + // Revert if anything fails + if iszero(success) { revert(0, 0) } + + // Return empty bytes on success return(0, 0)" .to_string(); self.code.borrow_mut().runtime_append(code); @@ -110,7 +111,7 @@ impl EvmLoader { *self.ptr.borrow() } - pub(crate) fn code_mut(&self) -> impl DerefMut + '_ { + pub(crate) fn code_mut(&self) -> impl DerefMut + '_ { self.code.borrow_mut() } @@ -308,11 +309,11 @@ impl EvmLoader { fn invert(self: &Rc, scalar: &Scalar) -> Scalar { let rd_ptr = self.allocate(0x20); let [cd_ptr, ..] = [ - &self.scalar(Value::Constant(0x20.into())), - &self.scalar(Value::Constant(0x20.into())), - &self.scalar(Value::Constant(0x20.into())), + &self.scalar(Value::Constant(U256::from(0x20))), + &self.scalar(Value::Constant(U256::from(0x20))), + &self.scalar(Value::Constant(U256::from(0x20))), scalar, - &self.scalar(Value::Constant(self.scalar_modulus - 2)), + &self.scalar(Value::Constant(self.scalar_modulus - U256::from(2))), &self.scalar(Value::Constant(self.scalar_modulus)), ] .map(|value| self.dup_scalar(value).ptr()); @@ -383,8 +384,8 @@ impl EvmLoader { fn add(self: &Rc, lhs: &Scalar, rhs: &Scalar) -> Scalar { if let (Value::Constant(lhs), Value::Constant(rhs)) = (&lhs.value, &rhs.value) { - let out = (U512::from(lhs) + U512::from(rhs)) % U512::from(self.scalar_modulus); - return self.scalar(Value::Constant(out.try_into().unwrap())); + let out = (U512::from(*lhs) + U512::from(*rhs)) % U512::from(self.scalar_modulus); + return self.scalar(Value::Constant(U256::from(out))); } self.scalar(Value::Sum(Box::new(lhs.value.clone()), Box::new(rhs.value.clone()))) @@ -403,8 +404,8 @@ impl EvmLoader { fn mul(self: &Rc, lhs: &Scalar, rhs: &Scalar) -> Scalar { if let (Value::Constant(lhs), Value::Constant(rhs)) = (&lhs.value, &rhs.value) { - let out = (U512::from(lhs) * U512::from(rhs)) % U512::from(self.scalar_modulus); - return self.scalar(Value::Constant(out.try_into().unwrap())); + let out = (U512::from(*lhs) * U512::from(*rhs)) % U512::from(self.scalar_modulus); + return self.scalar(Value::Constant(U256::from(out))); } self.scalar(Value::Product(Box::new(lhs.value.clone()), Box::new(rhs.value.clone()))) @@ -421,22 +422,16 @@ impl EvmLoader { #[cfg(test)] impl EvmLoader { - fn start_gas_metering(self: &Rc, identifier: &str) { - self.gas_metering_ids.borrow_mut().push(identifier.to_string()); - let code = format!("let {identifier} := gas()"); - self.code.borrow_mut().runtime_append(code); + fn start_gas_metering(self: &Rc, _: &str) { + // unimplemented } fn end_gas_metering(self: &Rc) { - let code = - format!("log1(0, 0, sub({}, gas()))", self.gas_metering_ids.borrow().last().unwrap()); - self.code.borrow_mut().runtime_append(code); + // unimplemented } - pub fn print_gas_metering(self: &Rc, costs: Vec) { - for (identifier, cost) in self.gas_metering_ids.borrow().iter().zip(costs) { - println!("{identifier}: {cost}"); - } + pub fn print_gas_metering(self: &Rc, _: Vec) { + // unimplemented } } @@ -632,6 +627,10 @@ impl> LoadedScalar for Scalar { fn loader(&self) -> &Self::Loader { &self.loader } + + fn pow_var(&self, _exp: &Self, _exp_max_bits: usize) -> Self { + todo!() + } } impl EcPointLoader for Rc @@ -644,7 +643,7 @@ where fn ec_point_load_const(&self, value: &C) -> EcPoint { let coordinates = value.coordinates().unwrap(); let [x, y] = [coordinates.x(), coordinates.y()] - .map(|coordinate| U256::from_little_endian(coordinate.to_repr().as_ref())); + .map(|coordinate| U256::try_from_le_slice(coordinate.to_repr().as_ref()).unwrap()); self.ec_point(Value::Constant((x, y))) } @@ -659,7 +658,7 @@ where .iter() .cloned() .map(|(scalar, ec_point)| match scalar.value { - Value::Constant(constant) if U256::one() == constant => ec_point.clone(), + Value::Constant(constant) if U256::from(1) == constant => ec_point.clone(), _ => ec_point.loader.ec_point_scalar_mul(ec_point, scalar), }) .reduce(|acc, ec_point| acc.loader.ec_point_add(&acc, &ec_point)) @@ -684,8 +683,8 @@ impl> ScalarLoader for Rc { } let push_addend = |(coeff, value): &(F, &Scalar)| { - assert_ne!(*coeff, F::zero()); - match (*coeff == F::one(), &value.value) { + assert_ne!(*coeff, F::ZERO); + match (*coeff == F::ONE, &value.value) { (true, _) => self.push(value), (false, Value::Constant(value)) => self.push( &self.scalar(Value::Constant(fe_to_u256(*coeff * u256_to_fe::(*value)))), @@ -699,7 +698,7 @@ impl> ScalarLoader for Rc { }; let mut values = values.iter(); - let initial_value = if constant == F::zero() { + let initial_value = if constant == F::ZERO { push_addend(values.next().unwrap()) } else { self.push(&self.scalar(Value::Constant(fe_to_u256(constant)))) @@ -733,8 +732,8 @@ impl> ScalarLoader for Rc { } let push_addend = |(coeff, lhs, rhs): &(F, &Scalar, &Scalar)| { - assert_ne!(*coeff, F::zero()); - match (*coeff == F::one(), &lhs.value, &rhs.value) { + assert_ne!(*coeff, F::ZERO); + match (*coeff == F::ONE, &lhs.value, &rhs.value) { (_, Value::Constant(lhs), Value::Constant(rhs)) => { self.push(&self.scalar(Value::Constant(fe_to_u256( *coeff * u256_to_fe::(*lhs) * u256_to_fe::(*rhs), @@ -764,7 +763,7 @@ impl> ScalarLoader for Rc { }; let mut values = values.iter(); - let initial_value = if constant == F::zero() { + let initial_value = if constant == F::ZERO { push_addend(values.next().unwrap()) } else { self.push(&self.scalar(Value::Constant(fe_to_u256(constant)))) diff --git a/snark-verifier/src/loader/evm/test.rs b/snark-verifier/src/loader/evm/test.rs deleted file mode 100644 index e3467408..00000000 --- a/snark-verifier/src/loader/evm/test.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::{ - loader::evm::{test::tui::Tui, Address, ExecutorBuilder, U256}, - util::Itertools, -}; -use std::env::var_os; - -mod tui; - -fn debug() -> bool { - matches!( - var_os("DEBUG"), - Some(value) if value.to_str() == Some("1") - ) -} - -pub fn execute(deployment_code: Vec, calldata: Vec) -> (bool, u64, Vec) { - assert!( - deployment_code.len() <= 0x6000, - "Contract size {} exceeds the limit 24576", - deployment_code.len() - ); - - let debug = debug(); - let caller = Address::from_low_u64_be(0xfe); - - let mut evm = ExecutorBuilder::default() - .with_gas_limit(u64::MAX.into()) - .set_debugger(debug) - .build(); - - let contract = evm - .deploy(caller, deployment_code.into(), 0.into()) - .address - .unwrap(); - let result = evm.call_raw(caller, contract, calldata.into(), 0.into()); - - let costs = result - .logs - .into_iter() - .map(|log| U256::from_big_endian(log.topics[0].as_bytes()).as_u64()) - .collect_vec(); - - if debug { - Tui::new(result.debug.unwrap().flatten(0), 0).start(); - } - - (!result.reverted, result.gas_used, costs) -} diff --git a/snark-verifier/src/loader/evm/test/tui.rs b/snark-verifier/src/loader/evm/test/tui.rs deleted file mode 100644 index 328082c7..00000000 --- a/snark-verifier/src/loader/evm/test/tui.rs +++ /dev/null @@ -1,943 +0,0 @@ -//! Copied and modified from https://github.com/foundry-rs/foundry/blob/master/ui/src/lib.rs - -use crate::loader::evm::{ - util::executor::{CallKind, DebugStep}, - Address, -}; -use crossterm::{ - event::{ - self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyModifiers, - MouseEvent, MouseEventKind, - }, - execute, - terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, -}; -use revm::opcode; -use std::{ - cmp::{max, min}, - io, - sync::mpsc, - thread, - time::{Duration, Instant}, -}; -use tui::{ - backend::{Backend, CrosstermBackend}, - layout::{Alignment, Constraint, Direction, Layout, Rect}, - style::{Color, Modifier, Style}, - terminal::Frame, - text::{Span, Spans, Text}, - widgets::{Block, Borders, Paragraph, Wrap}, - Terminal, -}; - -pub struct Tui { - debug_arena: Vec<(Address, Vec, CallKind)>, - terminal: Terminal>, - key_buffer: String, - current_step: usize, -} - -impl Tui { - pub fn new(debug_arena: Vec<(Address, Vec, CallKind)>, current_step: usize) -> Self { - enable_raw_mode().unwrap(); - let mut stdout = io::stdout(); - execute!(stdout, EnterAlternateScreen, EnableMouseCapture).unwrap(); - let backend = CrosstermBackend::new(stdout); - let mut terminal = Terminal::new(backend).unwrap(); - terminal.hide_cursor().unwrap(); - Tui { - debug_arena, - terminal, - key_buffer: String::new(), - current_step, - } - } - - pub fn start(mut self) { - std::panic::set_hook(Box::new(|e| { - disable_raw_mode().expect("Unable to disable raw mode"); - execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture) - .expect("unable to execute disable mouse capture"); - println!("{e}"); - })); - let tick_rate = Duration::from_millis(60); - - let (tx, rx) = mpsc::channel(); - thread::spawn(move || { - let mut last_tick = Instant::now(); - loop { - if event::poll(tick_rate - last_tick.elapsed()).unwrap() { - let event = event::read().unwrap(); - if let Event::Key(key) = event { - if tx.send(Interrupt::KeyPressed(key)).is_err() { - return; - } - } else if let Event::Mouse(mouse) = event { - if tx.send(Interrupt::MouseEvent(mouse)).is_err() { - return; - } - } - } - if last_tick.elapsed() > tick_rate { - if tx.send(Interrupt::IntervalElapsed).is_err() { - return; - } - last_tick = Instant::now(); - } - } - }); - - self.terminal.clear().unwrap(); - let mut draw_memory: DrawMemory = DrawMemory::default(); - - let debug_call = &self.debug_arena; - let mut opcode_list: Vec = debug_call[0] - .1 - .iter() - .map(|step| step.pretty_opcode()) - .collect(); - let mut last_index = 0; - - let mut stack_labels = false; - let mut mem_utf = false; - loop { - if last_index != draw_memory.inner_call_index { - opcode_list = debug_call[draw_memory.inner_call_index] - .1 - .iter() - .map(|step| step.pretty_opcode()) - .collect(); - last_index = draw_memory.inner_call_index; - } - match rx.recv().unwrap() { - Interrupt::KeyPressed(event) => match event.code { - KeyCode::Char('q') => { - disable_raw_mode().unwrap(); - execute!( - self.terminal.backend_mut(), - LeaveAlternateScreen, - DisableMouseCapture - ) - .unwrap(); - return; - } - KeyCode::Char('j') | KeyCode::Down => { - for _ in 0..Tui::buffer_as_number(&self.key_buffer, 1) { - if event.modifiers.contains(KeyModifiers::CONTROL) { - let max_mem = (debug_call[draw_memory.inner_call_index].1 - [self.current_step] - .memory - .len() - / 32) - .saturating_sub(1); - let step = if event.modifiers.contains(KeyModifiers::ALT) { - 20 - } else { - 1 - }; - if draw_memory.current_mem_startline + step < max_mem { - draw_memory.current_mem_startline += step; - } - } else if self.current_step < opcode_list.len() - 1 { - self.current_step += 1; - } else if draw_memory.inner_call_index < debug_call.len() - 1 { - draw_memory.inner_call_index += 1; - self.current_step = 0; - } - } - self.key_buffer.clear(); - } - KeyCode::Char('J') => { - for _ in 0..Tui::buffer_as_number(&self.key_buffer, 1) { - let max_stack = debug_call[draw_memory.inner_call_index].1 - [self.current_step] - .stack - .len() - .saturating_sub(1); - if draw_memory.current_stack_startline < max_stack { - draw_memory.current_stack_startline += 1; - } - } - self.key_buffer.clear(); - } - KeyCode::Char('k') | KeyCode::Up => { - for _ in 0..Tui::buffer_as_number(&self.key_buffer, 1) { - if event.modifiers.contains(KeyModifiers::CONTROL) { - draw_memory.current_mem_startline = - draw_memory.current_mem_startline.saturating_sub(1); - } else if self.current_step > 0 { - self.current_step -= 1; - } else if draw_memory.inner_call_index > 0 { - draw_memory.inner_call_index -= 1; - self.current_step = - debug_call[draw_memory.inner_call_index].1.len() - 1; - } - } - self.key_buffer.clear(); - } - KeyCode::Char('K') => { - for _ in 0..Tui::buffer_as_number(&self.key_buffer, 1) { - draw_memory.current_stack_startline = - draw_memory.current_stack_startline.saturating_sub(1); - } - self.key_buffer.clear(); - } - KeyCode::Char('g') => { - draw_memory.inner_call_index = 0; - self.current_step = 0; - self.key_buffer.clear(); - } - KeyCode::Char('G') => { - draw_memory.inner_call_index = debug_call.len() - 1; - self.current_step = debug_call[draw_memory.inner_call_index].1.len() - 1; - self.key_buffer.clear(); - } - KeyCode::Char('c') => { - draw_memory.inner_call_index = - draw_memory.inner_call_index.saturating_sub(1); - self.current_step = debug_call[draw_memory.inner_call_index].1.len() - 1; - self.key_buffer.clear(); - } - KeyCode::Char('C') => { - if debug_call.len() > draw_memory.inner_call_index + 1 { - draw_memory.inner_call_index += 1; - self.current_step = 0; - } - self.key_buffer.clear(); - } - KeyCode::Char('s') => { - for _ in 0..Tui::buffer_as_number(&self.key_buffer, 1) { - let remaining_ops = &opcode_list[self.current_step..]; - self.current_step += remaining_ops - .iter() - .enumerate() - .find_map(|(i, op)| { - if i < remaining_ops.len() - 1 { - match ( - op.contains("JUMP") && op != "JUMPDEST", - &*remaining_ops[i + 1], - ) { - (true, "JUMPDEST") => Some(i + 1), - _ => None, - } - } else { - None - } - }) - .unwrap_or(opcode_list.len() - 1); - if self.current_step > opcode_list.len() { - self.current_step = opcode_list.len() - 1 - }; - } - self.key_buffer.clear(); - } - KeyCode::Char('a') => { - for _ in 0..Tui::buffer_as_number(&self.key_buffer, 1) { - let prev_ops = &opcode_list[..self.current_step]; - self.current_step = prev_ops - .iter() - .enumerate() - .rev() - .find_map(|(i, op)| { - if i > 0 { - match ( - prev_ops[i - 1].contains("JUMP") - && prev_ops[i - 1] != "JUMPDEST", - &**op, - ) { - (true, "JUMPDEST") => Some(i - 1), - _ => None, - } - } else { - None - } - }) - .unwrap_or_default(); - } - self.key_buffer.clear(); - } - KeyCode::Char('t') => { - stack_labels = !stack_labels; - } - KeyCode::Char('m') => { - mem_utf = !mem_utf; - } - KeyCode::Char(other) => match other { - '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => { - self.key_buffer.push(other); - } - _ => { - self.key_buffer.clear(); - } - }, - _ => { - self.key_buffer.clear(); - } - }, - Interrupt::MouseEvent(event) => match event.kind { - MouseEventKind::ScrollUp => { - if self.current_step > 0 { - self.current_step -= 1; - } else if draw_memory.inner_call_index > 0 { - draw_memory.inner_call_index -= 1; - draw_memory.current_mem_startline = 0; - draw_memory.current_stack_startline = 0; - self.current_step = - debug_call[draw_memory.inner_call_index].1.len() - 1; - } - } - MouseEventKind::ScrollDown => { - if self.current_step < opcode_list.len() - 1 { - self.current_step += 1; - } else if draw_memory.inner_call_index < debug_call.len() - 1 { - draw_memory.inner_call_index += 1; - draw_memory.current_mem_startline = 0; - draw_memory.current_stack_startline = 0; - self.current_step = 0; - } - } - _ => {} - }, - Interrupt::IntervalElapsed => {} - } - let current_step = self.current_step; - self.terminal - .draw(|f| { - Tui::draw_layout( - f, - debug_call[draw_memory.inner_call_index].0, - &debug_call[draw_memory.inner_call_index].1[..], - &opcode_list, - current_step, - &mut draw_memory, - stack_labels, - mem_utf, - ) - }) - .unwrap(); - } - } - - fn buffer_as_number(buffer: &str, default_value: usize) -> usize { - if let Ok(num) = buffer.parse() { - if num >= 1 { - num - } else { - default_value - } - } else { - default_value - } - } - - fn draw_layout( - f: &mut Frame, - address: Address, - debug_steps: &[DebugStep], - opcode_list: &[String], - current_step: usize, - draw_memory: &mut DrawMemory, - stack_labels: bool, - mem_utf: bool, - ) { - let total_size = f.size(); - if total_size.width < 225 { - Tui::vertical_layout( - f, - address, - debug_steps, - opcode_list, - current_step, - draw_memory, - stack_labels, - mem_utf, - ); - } else { - Tui::square_layout( - f, - address, - debug_steps, - opcode_list, - current_step, - draw_memory, - stack_labels, - mem_utf, - ); - } - } - - fn vertical_layout( - f: &mut Frame, - address: Address, - debug_steps: &[DebugStep], - opcode_list: &[String], - current_step: usize, - draw_memory: &mut DrawMemory, - stack_labels: bool, - mem_utf: bool, - ) { - let total_size = f.size(); - if let [app, footer] = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Ratio(98, 100), Constraint::Ratio(2, 100)].as_ref()) - .split(total_size)[..] - { - if let [op_pane, stack_pane, memory_pane] = Layout::default() - .direction(Direction::Vertical) - .constraints( - [ - Constraint::Ratio(1, 3), - Constraint::Ratio(1, 3), - Constraint::Ratio(1, 3), - ] - .as_ref(), - ) - .split(app)[..] - { - Tui::draw_footer(f, footer); - Tui::draw_op_list( - f, - address, - debug_steps, - opcode_list, - current_step, - draw_memory, - op_pane, - ); - Tui::draw_stack( - f, - debug_steps, - current_step, - stack_pane, - stack_labels, - draw_memory, - ); - Tui::draw_memory( - f, - debug_steps, - current_step, - memory_pane, - mem_utf, - draw_memory, - ); - } else { - panic!("unable to create vertical panes") - } - } else { - panic!("unable to create footer / app") - } - } - - fn square_layout( - f: &mut Frame, - address: Address, - debug_steps: &[DebugStep], - opcode_list: &[String], - current_step: usize, - draw_memory: &mut DrawMemory, - stack_labels: bool, - mem_utf: bool, - ) { - let total_size = f.size(); - - if let [app, footer] = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Ratio(98, 100), Constraint::Ratio(2, 100)].as_ref()) - .split(total_size)[..] - { - if let [left_pane, right_pane] = Layout::default() - .direction(Direction::Horizontal) - .constraints([Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)].as_ref()) - .split(app)[..] - { - if let [stack_pane, memory_pane] = Layout::default() - .direction(Direction::Vertical) - .constraints([Constraint::Ratio(2, 5), Constraint::Ratio(3, 5)].as_ref()) - .split(right_pane)[..] - { - Tui::draw_footer(f, footer); - Tui::draw_op_list( - f, - address, - debug_steps, - opcode_list, - current_step, - draw_memory, - left_pane, - ); - Tui::draw_stack( - f, - debug_steps, - current_step, - stack_pane, - stack_labels, - draw_memory, - ); - Tui::draw_memory( - f, - debug_steps, - current_step, - memory_pane, - mem_utf, - draw_memory, - ); - } else { - panic!("Couldn't generate horizontal split layout 1:2."); - } - } else { - panic!("Couldn't generate vertical split layout 1:2."); - } - } else { - panic!("Couldn't generate application & footer") - } - } - - fn draw_footer(f: &mut Frame, area: Rect) { - let block_controls = Block::default(); - - let text_output = Text::from(Span::styled( - "[q]: quit | [k/j]: prev/next op | [a/s]: prev/next jump | [c/C]: prev/next call | [g/G]: start/end | [t]: toggle stack labels | [m]: toggle memory decoding | [shift + j/k]: scroll stack | [ctrl + j/k]: scroll memory", - Style::default().add_modifier(Modifier::DIM) - )); - let paragraph = Paragraph::new(text_output) - .block(block_controls) - .alignment(Alignment::Center) - .wrap(Wrap { trim: false }); - f.render_widget(paragraph, area); - } - - fn draw_op_list( - f: &mut Frame, - address: Address, - debug_steps: &[DebugStep], - opcode_list: &[String], - current_step: usize, - draw_memory: &mut DrawMemory, - area: Rect, - ) { - let block_source_code = Block::default() - .title(format!( - "Address: {:?} | PC: {} | Gas used in call: {}", - address, - if let Some(step) = debug_steps.get(current_step) { - step.pc.to_string() - } else { - "END".to_string() - }, - debug_steps[current_step].total_gas_used, - )) - .borders(Borders::ALL); - let mut text_output: Vec = Vec::new(); - - let display_start; - - let height = area.height as i32; - let extra_top_lines = height / 2; - let prev_start = draw_memory.current_startline; - let abs_min_start = 0; - let abs_max_start = (opcode_list.len() as i32 - 1) - (height / 2); - let mut min_start = max( - current_step as i32 - height + extra_top_lines, - abs_min_start, - ) as usize; - - let mut max_start = max( - min(current_step as i32 - extra_top_lines, abs_max_start), - abs_min_start, - ) as usize; - - if min_start > max_start { - std::mem::swap(&mut min_start, &mut max_start); - } - - if prev_start < min_start { - display_start = min_start; - } else if prev_start > max_start { - display_start = max_start; - } else { - display_start = prev_start; - } - draw_memory.current_startline = display_start; - - let max_pc_len = debug_steps - .iter() - .fold(0, |max_val, val| val.pc.max(max_val)) - .to_string() - .len(); - - let mut add_new_line = |line_number| { - let bg_color = if line_number == current_step { - Color::DarkGray - } else { - Color::Reset - }; - - let line_number_format = if line_number == current_step { - let step: &DebugStep = &debug_steps[line_number]; - format!("{:0>max_pc_len$x}|▶", step.pc) - } else if line_number < debug_steps.len() { - let step: &DebugStep = &debug_steps[line_number]; - format!("{:0>max_pc_len$x}| ", step.pc) - } else { - "END CALL".to_string() - }; - - if let Some(op) = opcode_list.get(line_number) { - text_output.push(Spans::from(Span::styled( - format!("{line_number_format}{op}"), - Style::default().fg(Color::White).bg(bg_color), - ))); - } else { - text_output.push(Spans::from(Span::styled( - line_number_format, - Style::default().fg(Color::White).bg(bg_color), - ))); - } - }; - for number in display_start..opcode_list.len() { - add_new_line(number); - } - add_new_line(opcode_list.len()); - let paragraph = Paragraph::new(text_output) - .block(block_source_code) - .wrap(Wrap { trim: true }); - f.render_widget(paragraph, area); - } - - fn draw_stack( - f: &mut Frame, - debug_steps: &[DebugStep], - current_step: usize, - area: Rect, - stack_labels: bool, - draw_memory: &mut DrawMemory, - ) { - let stack = &debug_steps[current_step].stack; - let stack_space = Block::default() - .title(format!("Stack: {}", stack.len())) - .borders(Borders::ALL); - let min_len = usize::max(format!("{}", stack.len()).len(), 2); - - let indices_affected = stack_indices_affected(debug_steps[current_step].instruction.0); - - let text: Vec = stack - .iter() - .rev() - .enumerate() - .skip(draw_memory.current_stack_startline) - .map(|(i, stack_item)| { - let affected = indices_affected - .iter() - .find(|(affected_index, _name)| *affected_index == i); - - let mut words: Vec = (0..32) - .into_iter() - .rev() - .map(|i| stack_item.byte(i)) - .map(|byte| { - Span::styled( - format!("{byte:02x} "), - if affected.is_some() { - Style::default().fg(Color::Cyan) - } else if byte == 0 { - Style::default().add_modifier(Modifier::DIM) - } else { - Style::default().fg(Color::White) - }, - ) - }) - .collect(); - - if stack_labels { - if let Some((_, name)) = affected { - words.push(Span::raw(format!("| {name}"))); - } else { - words.push(Span::raw("| ".to_string())); - } - } - - let mut spans = vec![Span::styled( - format!("{i:0min_len$}| "), - Style::default().fg(Color::White), - )]; - spans.extend(words); - spans.push(Span::raw("\n")); - - Spans::from(spans) - }) - .collect(); - - let paragraph = Paragraph::new(text) - .block(stack_space) - .wrap(Wrap { trim: true }); - f.render_widget(paragraph, area); - } - - fn draw_memory( - f: &mut Frame, - debug_steps: &[DebugStep], - current_step: usize, - area: Rect, - mem_utf8: bool, - draw_mem: &mut DrawMemory, - ) { - let memory = &debug_steps[current_step].memory; - let stack_space = Block::default() - .title(format!( - "Memory (max expansion: {} bytes)", - memory.effective_len() - )) - .borders(Borders::ALL); - let memory = memory.data(); - let max_i = memory.len() / 32; - let min_len = format!("{:x}", max_i * 32).len(); - - let mut word = None; - let mut color = None; - let stack_len = debug_steps[current_step].stack.len(); - if stack_len > 0 { - let w = debug_steps[current_step].stack[stack_len - 1]; - match debug_steps[current_step].instruction.0 { - opcode::MLOAD => { - word = Some(w.as_usize() / 32); - color = Some(Color::Cyan); - } - opcode::MSTORE => { - word = Some(w.as_usize() / 32); - color = Some(Color::Red); - } - _ => {} - } - } - - if current_step > 0 { - let prev_step = current_step - 1; - let stack_len = debug_steps[prev_step].stack.len(); - if debug_steps[prev_step].instruction.0 == opcode::MSTORE { - let prev_top = debug_steps[prev_step].stack[stack_len - 1]; - word = Some(prev_top.as_usize() / 32); - color = Some(Color::Green); - } - } - - let text: Vec = memory - .chunks(32) - .enumerate() - .skip(draw_mem.current_mem_startline) - .map(|(i, mem_word)| { - let words: Vec = mem_word - .iter() - .map(|byte| { - Span::styled( - format!("{byte:02x} "), - if let (Some(w), Some(color)) = (word, color) { - if i == w { - Style::default().fg(color) - } else if *byte == 0 { - Style::default().add_modifier(Modifier::DIM) - } else { - Style::default().fg(Color::White) - } - } else if *byte == 0 { - Style::default().add_modifier(Modifier::DIM) - } else { - Style::default().fg(Color::White) - }, - ) - }) - .collect(); - - let mut spans = vec![Span::styled( - format!("{:0min_len$x}| ", i * 32), - Style::default().fg(Color::White), - )]; - spans.extend(words); - - if mem_utf8 { - let chars: Vec = mem_word - .chunks(4) - .map(|utf| { - if let Ok(utf_str) = std::str::from_utf8(utf) { - Span::raw(utf_str.replace(char::from(0), ".")) - } else { - Span::raw(".") - } - }) - .collect(); - spans.push(Span::raw("|")); - spans.extend(chars); - } - - spans.push(Span::raw("\n")); - - Spans::from(spans) - }) - .collect(); - let paragraph = Paragraph::new(text) - .block(stack_space) - .wrap(Wrap { trim: true }); - f.render_widget(paragraph, area); - } -} - -enum Interrupt { - KeyPressed(KeyEvent), - MouseEvent(MouseEvent), - IntervalElapsed, -} - -struct DrawMemory { - pub current_startline: usize, - pub inner_call_index: usize, - pub current_mem_startline: usize, - pub current_stack_startline: usize, -} - -impl DrawMemory { - fn default() -> Self { - DrawMemory { - current_startline: 0, - inner_call_index: 0, - current_mem_startline: 0, - current_stack_startline: 0, - } - } -} - -fn stack_indices_affected(op: u8) -> Vec<(usize, &'static str)> { - match op { - 0x01 => vec![(0, "a"), (1, "b")], - 0x02 => vec![(0, "a"), (1, "b")], - 0x03 => vec![(0, "a"), (1, "b")], - 0x04 => vec![(0, "a"), (1, "b")], - 0x05 => vec![(0, "a"), (1, "b")], - 0x06 => vec![(0, "a"), (1, "b")], - 0x07 => vec![(0, "a"), (1, "b")], - 0x08 => vec![(0, "a"), (1, "b"), (2, "mod")], - 0x09 => vec![(0, "a"), (1, "b"), (2, "mod")], - 0x0a => vec![(0, "base"), (1, "exp")], - 0x0b => vec![(0, "i"), (1, "a")], - 0x10 => vec![(0, "a"), (1, "b")], - 0x11 => vec![(0, "a"), (1, "b")], - 0x12 => vec![(0, "a"), (1, "b")], - 0x13 => vec![(0, "a"), (1, "b")], - 0x14 => vec![(0, "a"), (1, "b")], - 0x15 => vec![(0, "a")], - 0x16 => vec![(0, "a"), (1, "b")], - 0x17 => vec![(0, "a"), (1, "b")], - 0x18 => vec![(0, "a"), (1, "b")], - 0x19 => vec![(0, "a")], - 0x1a => vec![(0, "i"), (1, "a")], - 0x1b => vec![(0, "shift"), (1, "a")], - 0x1c => vec![(0, "shift"), (1, "a")], - 0x1d => vec![(0, "shift"), (1, "a")], - 0x20 => vec![(0, "offset"), (1, "length")], - 0x31 => vec![(0, "address")], - 0x35 => vec![(0, "offset")], - 0x37 => vec![(0, "dst"), (1, "src"), (2, "length")], - 0x39 => vec![(0, "dst"), (1, "src"), (2, "length")], - 0x3b => vec![(0, "address")], - 0x3c => vec![(0, "address"), (1, "dst"), (2, "src"), (3, "length")], - 0x3e => vec![(0, "dst"), (1, "src"), (2, "length")], - 0x3f => vec![(0, "address")], - 0x40 => vec![(0, "number")], - 0x50 => vec![(0, "a")], - 0x51 => vec![(0, "offset")], - 0x52 => vec![(0, "offset"), (1, "a")], - 0x53 => vec![(0, "offset"), (1, "a")], - 0x54 => vec![(0, "key")], - 0x55 => vec![(0, "key"), (1, "a")], - 0x56 => vec![(0, "dst")], - 0x57 => vec![(0, "dst"), (1, "cond")], - 0x80 => vec![(0, "a")], - 0x81 => vec![(1, "a")], - 0x82 => vec![(2, "a")], - 0x83 => vec![(3, "a")], - 0x84 => vec![(4, "a")], - 0x85 => vec![(5, "a")], - 0x86 => vec![(6, "a")], - 0x87 => vec![(7, "a")], - 0x88 => vec![(8, "a")], - 0x89 => vec![(9, "a")], - 0x8a => vec![(10, "a")], - 0x8b => vec![(11, "a")], - 0x8c => vec![(12, "a")], - 0x8d => vec![(13, "a")], - 0x8e => vec![(14, "a")], - 0x8f => vec![(15, "a")], - 0x90 => vec![(0, "a"), (1, "a")], - 0x91 => vec![(0, "a"), (2, "a")], - 0x92 => vec![(0, "a"), (3, "a")], - 0x93 => vec![(0, "a"), (4, "a")], - 0x94 => vec![(0, "a"), (5, "a")], - 0x95 => vec![(0, "a"), (6, "a")], - 0x96 => vec![(0, "a"), (7, "a")], - 0x97 => vec![(0, "a"), (8, "a")], - 0x98 => vec![(0, "a"), (9, "a")], - 0x99 => vec![(0, "a"), (10, "a")], - 0x9a => vec![(0, "a"), (11, "a")], - 0x9b => vec![(0, "a"), (12, "a")], - 0x9c => vec![(0, "a"), (13, "a")], - 0x9d => vec![(0, "a"), (14, "a")], - 0x9e => vec![(0, "a"), (15, "a")], - 0x9f => vec![(0, "a"), (16, "a")], - 0xa0 => vec![(0, "offset"), (1, "length")], - 0xa1 => vec![(0, "offset"), (1, "length"), (2, "topic")], - 0xa2 => vec![(0, "offset"), (1, "length"), (2, "topic1"), (3, "topic2")], - 0xa3 => vec![ - (0, "offset"), - (1, "length"), - (2, "topic1"), - (3, "topic2"), - (4, "topic3"), - ], - 0xa4 => vec![ - (0, "offset"), - (1, "length"), - (2, "topic1"), - (3, "topic2"), - (4, "topic3"), - (5, "topic4"), - ], - 0xf0 => vec![(0, "value"), (1, "offset"), (2, "length")], - 0xf1 => vec![ - (0, "gas"), - (1, "address"), - (2, "value"), - (3, "cd_offset"), - (4, "cd_length"), - (5, "rd_offset"), - (6, "rd_length"), - ], - 0xf2 => vec![ - (0, "gas"), - (1, "address"), - (2, "value"), - (3, "cd_offset"), - (4, "cd_length"), - (5, "rd_offset"), - (6, "rd_length"), - ], - 0xf3 => vec![(0, "offset"), (1, "length")], - 0xf4 => vec![ - (0, "gas"), - (1, "address"), - (2, "cd_offset"), - (3, "cd_length"), - (4, "rd_offset"), - (5, "rd_length"), - ], - 0xf5 => vec![(0, "value"), (1, "offset"), (2, "length"), (3, "salt")], - 0xfa => vec![ - (0, "gas"), - (1, "address"), - (2, "cd_offset"), - (3, "cd_length"), - (4, "rd_offset"), - (5, "rd_length"), - ], - 0xfd => vec![(0, "offset"), (1, "length")], - 0xff => vec![(0, "address")], - _ => vec![], - } -} diff --git a/snark-verifier/src/loader/evm/util.rs b/snark-verifier/src/loader/evm/util.rs index a84df4c3..8bf92dd1 100644 --- a/snark-verifier/src/loader/evm/util.rs +++ b/snark-verifier/src/loader/evm/util.rs @@ -8,12 +8,13 @@ use std::{ process::{Command, Stdio}, }; -pub use primitive_types::{H160 as Address, H256, U256, U512}; +#[cfg(feature = "revm")] +pub use executor::deploy_and_call; +pub use ruint::aliases::{B160 as Address, B256, U256, U512}; +#[cfg(feature = "revm")] pub(crate) mod executor; -pub use executor::ExecutorBuilder; - /// Memory chunk in EVM. #[derive(Debug)] pub struct MemoryChunk { @@ -55,7 +56,7 @@ pub fn fe_to_u256(f: F) -> U256 where F: PrimeField, { - U256::from_little_endian(f.to_repr().as_ref()) + U256::from_le_bytes(f.to_repr()) } /// Convert a [`U256`] into a [`PrimeField`]. @@ -64,9 +65,7 @@ where F: PrimeField, { let value = value % modulus::(); - let mut repr = F::Repr::default(); - value.to_little_endian(repr.as_mut()); - F::from_repr(repr).unwrap() + F::from_repr(value.to_le_bytes::<32>()).unwrap() } /// Returns modulus of [`PrimeField`] as [`U256`]. @@ -74,7 +73,7 @@ pub fn modulus() -> U256 where F: PrimeField, { - U256::from_little_endian((-F::one()).to_repr().as_ref()) + 1 + U256::from_le_bytes((-F::ONE).to_repr()) + U256::from(1) } /// Encode instances and proof into calldata. @@ -104,13 +103,12 @@ pub fn estimate_gas(cost: Cost) -> usize { intrinsic_cost + calldata_cost + ec_operation_cost } -/// Compile given yul `code` into deployment bytecode. -pub fn compile_yul(code: &str) -> Vec { +/// Compile given Solidity `code` into deployment bytecode. +pub fn compile_solidity(code: &str) -> Vec { let mut cmd = Command::new("solc") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .arg("--bin") - .arg("--yul") .arg("-") .spawn() .unwrap(); diff --git a/snark-verifier/src/loader/evm/util/executor.rs b/snark-verifier/src/loader/evm/util/executor.rs index a7697a0e..e2c5bb2c 100644 --- a/snark-verifier/src/loader/evm/util/executor.rs +++ b/snark-verifier/src/loader/evm/util/executor.rs @@ -1,875 +1,59 @@ -//! Copied and modified from -//! - -use crate::loader::evm::{Address, H256, U256}; -use bytes::Bytes; use revm::{ - evm_inner, opcode, spec_opcode_gas, Account, BlockEnv, CallInputs, CallScheme, CreateInputs, - CreateScheme, Database, DatabaseCommit, EVMData, Env, ExecutionResult, Gas, GasInspector, - InMemoryDB, Inspector, Interpreter, Memory, OpCode, Return, TransactOut, TransactTo, TxEnv, + primitives::{CreateScheme, ExecutionResult, Output, TransactTo, TxEnv}, + InMemoryDB, EVM, }; -use sha3::{Digest, Keccak256}; -use std::{cell::RefCell, collections::HashMap, fmt::Display, rc::Rc}; -macro_rules! return_ok { - () => { - Return::Continue | Return::Stop | Return::Return | Return::SelfDestruct +/// Deploy contract and then call with calldata. +/// Returns gas_used of call to deployed contract if both transactions are successful. +pub fn deploy_and_call(deployment_code: Vec, calldata: Vec) -> Result { + let mut evm = EVM { + env: Default::default(), + db: Some(InMemoryDB::default()), }; -} - -fn keccak256(data: impl AsRef<[u8]>) -> [u8; 32] { - Keccak256::digest(data.as_ref()).into() -} - -fn get_contract_address(sender: impl Into
, nonce: impl Into) -> Address { - let mut stream = rlp::RlpStream::new(); - stream.begin_list(2); - stream.append(&sender.into()); - stream.append(&nonce.into()); - - let hash = keccak256(&stream.out()); - - let mut bytes = [0u8; 20]; - bytes.copy_from_slice(&hash[12..]); - Address::from(bytes) -} - -fn get_create2_address( - from: impl Into
, - salt: [u8; 32], - init_code: impl Into, -) -> Address { - get_create2_address_from_hash(from, salt, keccak256(init_code.into().as_ref()).to_vec()) -} - -fn get_create2_address_from_hash( - from: impl Into
, - salt: [u8; 32], - init_code_hash: impl Into, -) -> Address { - let bytes = [ - &[0xff], - from.into().as_bytes(), - salt.as_slice(), - init_code_hash.into().as_ref(), - ] - .concat(); - - let hash = keccak256(bytes); - - let mut bytes = [0u8; 20]; - bytes.copy_from_slice(&hash[12..]); - Address::from(bytes) -} - -fn get_create_address(call: &CreateInputs, nonce: u64) -> Address { - match call.scheme { - CreateScheme::Create => get_contract_address(call.caller, nonce), - CreateScheme::Create2 { salt } => { - let mut buffer: [u8; 4 * 8] = [0; 4 * 8]; - salt.to_big_endian(&mut buffer); - get_create2_address(call.caller, buffer, call.init_code.clone()) - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct Log { - pub address: Address, - pub topics: Vec, - pub data: Bytes, -} - -#[derive(Clone, Debug, Default)] -struct LogCollector { - logs: Vec, -} - -impl Inspector for LogCollector { - fn log(&mut self, _: &mut EVMData<'_, DB>, address: &Address, topics: &[H256], data: &Bytes) { - self.logs.push(Log { - address: *address, - topics: topics.to_vec(), - data: data.clone(), - }); - } - - fn call( - &mut self, - _: &mut EVMData<'_, DB>, - call: &mut CallInputs, - _: bool, - ) -> (Return, Gas, Bytes) { - (Return::Continue, Gas::new(call.gas_limit), Bytes::new()) - } -} - -#[derive(Clone, Debug, Copy)] -pub enum CallKind { - Call, - StaticCall, - CallCode, - DelegateCall, - Create, - Create2, -} - -impl Default for CallKind { - fn default() -> Self { - CallKind::Call - } -} - -impl From for CallKind { - fn from(scheme: CallScheme) -> Self { - match scheme { - CallScheme::Call => CallKind::Call, - CallScheme::StaticCall => CallKind::StaticCall, - CallScheme::CallCode => CallKind::CallCode, - CallScheme::DelegateCall => CallKind::DelegateCall, - } - } -} - -impl From for CallKind { - fn from(create: CreateScheme) -> Self { - match create { - CreateScheme::Create => CallKind::Create, - CreateScheme::Create2 { .. } => CallKind::Create2, - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct DebugArena { - pub arena: Vec, -} - -impl DebugArena { - fn push_node(&mut self, mut new_node: DebugNode) -> usize { - fn recursively_push( - arena: &mut Vec, - entry: usize, - mut new_node: DebugNode, - ) -> usize { - match new_node.depth { - _ if arena[entry].depth == new_node.depth - 1 => { - let id = arena.len(); - new_node.location = arena[entry].children.len(); - new_node.parent = Some(entry); - arena[entry].children.push(id); - arena.push(new_node); - id - } - _ => { - let child = *arena[entry].children.last().unwrap(); - recursively_push(arena, child, new_node) - } - } - } - - if self.arena.is_empty() { - self.arena.push(new_node); - 0 - } else if new_node.depth == 0 { - let id = self.arena.len(); - new_node.location = self.arena[0].children.len(); - new_node.parent = Some(0); - self.arena[0].children.push(id); - self.arena.push(new_node); - id - } else { - recursively_push(&mut self.arena, 0, new_node) - } - } - - #[cfg(test)] - pub fn flatten(&self, entry: usize) -> Vec<(Address, Vec, CallKind)> { - let node = &self.arena[entry]; - - let mut flattened = vec![]; - if !node.steps.is_empty() { - flattened.push((node.address, node.steps.clone(), node.kind)); - } - flattened.extend(node.children.iter().flat_map(|child| self.flatten(*child))); - - flattened - } -} - -#[derive(Clone, Debug, Default)] -pub struct DebugNode { - pub parent: Option, - pub children: Vec, - pub location: usize, - pub address: Address, - pub kind: CallKind, - pub depth: usize, - pub steps: Vec, -} - -#[derive(Clone, Debug)] -pub struct DebugStep { - pub stack: Vec, - pub memory: Memory, - pub instruction: Instruction, - pub push_bytes: Option>, - pub pc: usize, - pub total_gas_used: u64, -} - -impl Default for DebugStep { - fn default() -> Self { - Self { - stack: vec![], - memory: Memory::new(), - instruction: Instruction(revm::opcode::INVALID), - push_bytes: None, - pc: 0, - total_gas_used: 0, - } - } -} - -impl DebugStep { - #[cfg(test)] - pub fn pretty_opcode(&self) -> String { - if let Some(push_bytes) = &self.push_bytes { - format!("{}(0x{})", self.instruction, hex::encode(push_bytes)) - } else { - self.instruction.to_string() - } - } -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct Instruction(pub u8); - -impl From for Instruction { - fn from(op: u8) -> Instruction { - Instruction(op) - } -} - -impl Display for Instruction { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{}", - OpCode::try_from_u8(self.0).map_or_else( - || format!("UNDEFINED(0x{:02x})", self.0), - |opcode| opcode.as_str().to_string(), - ) - ) - } -} - -#[derive(Clone, Debug)] -struct Debugger { - arena: DebugArena, - head: usize, - context: Address, - gas_inspector: Rc>, -} - -impl Debugger { - fn new(gas_inspector: Rc>) -> Self { - Self { - arena: Default::default(), - head: Default::default(), - context: Default::default(), - gas_inspector, - } - } - - fn enter(&mut self, depth: usize, address: Address, kind: CallKind) { - self.context = address; - self.head = self.arena.push_node(DebugNode { - depth, - address, - kind, - ..Default::default() - }); - } - - fn exit(&mut self) { - if let Some(parent_id) = self.arena.arena[self.head].parent { - let DebugNode { - depth, - address, - kind, - .. - } = self.arena.arena[parent_id]; - self.context = address; - self.head = self.arena.push_node(DebugNode { - depth, - address, - kind, - ..Default::default() - }); - } - } -} - -impl Inspector for Debugger { - fn step( - &mut self, - interpreter: &mut Interpreter, - data: &mut EVMData<'_, DB>, - _is_static: bool, - ) -> Return { - let pc = interpreter.program_counter(); - let op = interpreter.contract.bytecode.bytecode()[pc]; - - let opcode_infos = spec_opcode_gas(data.env.cfg.spec_id); - let opcode_info = &opcode_infos[op as usize]; - - let push_size = if opcode_info.is_push() { - (op - opcode::PUSH1 + 1) as usize - } else { - 0 - }; - let push_bytes = match push_size { - 0 => None, - n => { - let start = pc + 1; - let end = start + n; - Some(interpreter.contract.bytecode.bytecode()[start..end].to_vec()) - } - }; - - let spent = interpreter.gas.limit() - self.gas_inspector.borrow().gas_remaining(); - let total_gas_used = spent - (interpreter.gas.refunded() as u64).min(spent / 5); - - self.arena.arena[self.head].steps.push(DebugStep { - pc, - stack: interpreter.stack().data().clone(), - memory: interpreter.memory.clone(), - instruction: Instruction(op), - push_bytes, - total_gas_used, - }); - - Return::Continue - } - - fn call( - &mut self, - data: &mut EVMData<'_, DB>, - call: &mut CallInputs, - _: bool, - ) -> (Return, Gas, Bytes) { - self.enter( - data.journaled_state.depth() as usize, - call.context.code_address, - call.context.scheme.into(), - ); - - (Return::Continue, Gas::new(call.gas_limit), Bytes::new()) - } - - fn call_end( - &mut self, - _: &mut EVMData<'_, DB>, - _: &CallInputs, - gas: Gas, - status: Return, - retdata: Bytes, - _: bool, - ) -> (Return, Gas, Bytes) { - self.exit(); - (status, gas, retdata) - } - - fn create( - &mut self, - data: &mut EVMData<'_, DB>, - call: &mut CreateInputs, - ) -> (Return, Option
, Gas, Bytes) { - let nonce = data.journaled_state.account(call.caller).info.nonce; - self.enter( - data.journaled_state.depth() as usize, - get_create_address(call, nonce), - CallKind::Create, - ); - - ( - Return::Continue, - None, - Gas::new(call.gas_limit), - Bytes::new(), - ) - } - - fn create_end( - &mut self, - _: &mut EVMData<'_, DB>, - _: &CreateInputs, - status: Return, - address: Option
, - gas: Gas, - retdata: Bytes, - ) -> (Return, Option
, Gas, Bytes) { - self.exit(); - - (status, address, gas, retdata) - } -} - -macro_rules! call_inspectors { - ($id:ident, [ $($inspector:expr),+ ], $call:block) => { - $({ - if let Some($id) = $inspector { - $call; - } - })+ - } -} - -struct InspectorData { - logs: Vec, - debug: Option, -} - -#[derive(Default)] -struct InspectorStack { - gas: Option>>, - logs: Option, - debugger: Option, -} - -impl InspectorStack { - fn collect_inspector_states(self) -> InspectorData { - InspectorData { - logs: self.logs.map(|logs| logs.logs).unwrap_or_default(), - debug: self.debugger.map(|debugger| debugger.arena), - } - } -} - -impl Inspector for InspectorStack { - fn initialize_interp( - &mut self, - interpreter: &mut Interpreter, - data: &mut EVMData<'_, DB>, - is_static: bool, - ) -> Return { - call_inspectors!( - inspector, - [ - &mut self.gas.as_deref().map(|gas| gas.borrow_mut()), - &mut self.logs, - &mut self.debugger - ], - { - let status = inspector.initialize_interp(interpreter, data, is_static); - - if status != Return::Continue { - return status; - } - } - ); - - Return::Continue - } - - fn step( - &mut self, - interpreter: &mut Interpreter, - data: &mut EVMData<'_, DB>, - is_static: bool, - ) -> Return { - call_inspectors!( - inspector, - [ - &mut self.gas.as_deref().map(|gas| gas.borrow_mut()), - &mut self.logs, - &mut self.debugger - ], - { - let status = inspector.step(interpreter, data, is_static); - - if status != Return::Continue { - return status; - } - } - ); - - Return::Continue - } - - fn log( - &mut self, - evm_data: &mut EVMData<'_, DB>, - address: &Address, - topics: &[H256], - data: &Bytes, - ) { - call_inspectors!(inspector, [&mut self.logs], { - inspector.log(evm_data, address, topics, data); - }); - } - - fn step_end( - &mut self, - interpreter: &mut Interpreter, - data: &mut EVMData<'_, DB>, - is_static: bool, - status: Return, - ) -> Return { - call_inspectors!( - inspector, - [ - &mut self.gas.as_deref().map(|gas| gas.borrow_mut()), - &mut self.logs, - &mut self.debugger - ], - { - let status = inspector.step_end(interpreter, data, is_static, status); - - if status != Return::Continue { - return status; - } - } - ); - - Return::Continue - } - - fn call( - &mut self, - data: &mut EVMData<'_, DB>, - call: &mut CallInputs, - is_static: bool, - ) -> (Return, Gas, Bytes) { - call_inspectors!( - inspector, - [ - &mut self.gas.as_deref().map(|gas| gas.borrow_mut()), - &mut self.logs, - &mut self.debugger - ], - { - let (status, gas, retdata) = inspector.call(data, call, is_static); - - if status != Return::Continue { - return (status, gas, retdata); - } - } - ); - - (Return::Continue, Gas::new(call.gas_limit), Bytes::new()) - } - - fn call_end( - &mut self, - data: &mut EVMData<'_, DB>, - call: &CallInputs, - remaining_gas: Gas, - status: Return, - retdata: Bytes, - is_static: bool, - ) -> (Return, Gas, Bytes) { - call_inspectors!( - inspector, - [ - &mut self.gas.as_deref().map(|gas| gas.borrow_mut()), - &mut self.logs, - &mut self.debugger - ], - { - let (new_status, new_gas, new_retdata) = inspector.call_end( - data, - call, - remaining_gas, - status, - retdata.clone(), - is_static, - ); - - if new_status != status || (new_status == Return::Revert && new_retdata != retdata) - { - return (new_status, new_gas, new_retdata); - } - } - ); - - (status, remaining_gas, retdata) - } - - fn create( - &mut self, - data: &mut EVMData<'_, DB>, - call: &mut CreateInputs, - ) -> (Return, Option
, Gas, Bytes) { - call_inspectors!( - inspector, - [ - &mut self.gas.as_deref().map(|gas| gas.borrow_mut()), - &mut self.logs, - &mut self.debugger - ], - { - let (status, addr, gas, retdata) = inspector.create(data, call); - - if status != Return::Continue { - return (status, addr, gas, retdata); - } - } - ); - - ( - Return::Continue, - None, - Gas::new(call.gas_limit), - Bytes::new(), - ) - } - - fn create_end( - &mut self, - data: &mut EVMData<'_, DB>, - call: &CreateInputs, - status: Return, - address: Option
, - remaining_gas: Gas, - retdata: Bytes, - ) -> (Return, Option
, Gas, Bytes) { - call_inspectors!( - inspector, - [ - &mut self.gas.as_deref().map(|gas| gas.borrow_mut()), - &mut self.logs, - &mut self.debugger - ], - { - let (new_status, new_address, new_gas, new_retdata) = inspector.create_end( - data, - call, - status, - address, - remaining_gas, - retdata.clone(), - ); - - if new_status != status { - return (new_status, new_address, new_gas, new_retdata); - } - } - ); - - (status, address, remaining_gas, retdata) - } - - fn selfdestruct(&mut self) { - call_inspectors!(inspector, [&mut self.logs, &mut self.debugger], { - Inspector::::selfdestruct(inspector); - }); - } -} - -/// Call result. -#[derive(Debug)] -pub struct RawCallResult { - /// Exit reason - pub exit_reason: Return, - /// If the call is reverted or not. - pub reverted: bool, - /// Returndata - pub result: Bytes, - /// Gas used - pub gas_used: u64, - /// Gas refunded - pub gas_refunded: u64, - /// Logs emitted during the call - pub logs: Vec, - /// Debug information if any - pub debug: Option, - /// State changes if any - pub state_changeset: Option>, - /// Environment - pub env: Env, - /// Output - pub out: TransactOut, -} - -#[derive(Clone, Debug)] -pub struct DeployResult { - pub exit_reason: Return, - pub reverted: bool, - pub address: Option
, - pub gas_used: u64, - pub gas_refunded: u64, - pub logs: Vec, - pub debug: Option, - pub env: Env, -} - -/// Executor builder. -#[derive(Debug, Default)] -pub struct ExecutorBuilder { - debugger: bool, - gas_limit: Option, -} - -impl ExecutorBuilder { - /// Set `debugger`. - pub fn set_debugger(mut self, enable: bool) -> Self { - self.debugger = enable; - self - } - - /// Set `gas_limit`. - pub fn with_gas_limit(mut self, gas_limit: U256) -> Self { - self.gas_limit = Some(gas_limit); - self - } - - /// Initialize an `Executor`. - pub fn build(self) -> Executor { - Executor::new(self.debugger, self.gas_limit.unwrap_or(U256::MAX)) - } -} - -#[derive(Clone, Debug)] -pub struct Executor { - db: InMemoryDB, - debugger: bool, - gas_limit: U256, -} - -impl Executor { - fn new(debugger: bool, gas_limit: U256) -> Self { - Executor { - db: InMemoryDB::default(), - debugger, - gas_limit, - } - } - - pub fn db_mut(&mut self) -> &mut InMemoryDB { - &mut self.db - } - - pub fn deploy(&mut self, from: Address, code: Bytes, value: U256) -> DeployResult { - let env = self.build_test_env(from, TransactTo::Create(CreateScheme::Create), code, value); - let result = self.call_raw_with_env(env); - self.commit(&result); - - let RawCallResult { - exit_reason, - out, - gas_used, - gas_refunded, - logs, - debug, - env, - .. - } = result; - - let address = match (exit_reason, out) { - (return_ok!(), TransactOut::Create(_, Some(address))) => Some(address), - _ => None, - }; - - DeployResult { - exit_reason, - reverted: !matches!(exit_reason, return_ok!()), - address, - gas_used, - gas_refunded, - logs, - debug, - env, - } - } - - pub fn call_raw( - &self, - from: Address, - to: Address, - calldata: Bytes, - value: U256, - ) -> RawCallResult { - let env = self.build_test_env(from, TransactTo::Call(to), calldata, value); - self.call_raw_with_env(env) - } + evm.env.tx = TxEnv { + gas_limit: u64::MAX, + transact_to: TransactTo::Create(CreateScheme::Create), + data: deployment_code.into(), + ..Default::default() + }; - fn call_raw_with_env(&self, mut env: Env) -> RawCallResult { - let mut inspector = self.inspector(); - let result = - evm_inner::<_, true>(&mut env, &mut self.db.clone(), &mut inspector).transact(); - let (exec_result, state_changeset) = result; - let ExecutionResult { - exit_reason, - gas_refunded, - gas_used, - out, + let result = evm.transact_commit().unwrap(); + let contract = match result { + ExecutionResult::Success { + output: Output::Create(_, Some(contract)), .. - } = exec_result; - - let result = match out { - TransactOut::Call(ref data) => data.to_owned(), - _ => Bytes::default(), - }; - let InspectorData { logs, debug } = inspector.collect_inspector_states(); - - RawCallResult { - exit_reason, - reverted: !matches!(exit_reason, return_ok!()), - result, - gas_used, - gas_refunded, - logs: logs.to_vec(), - debug, - state_changeset: Some(state_changeset.into_iter().collect()), - env, - out, - } - } - - fn commit(&mut self, result: &RawCallResult) { - if let Some(state_changeset) = result.state_changeset.as_ref() { - self.db - .commit(state_changeset.clone().into_iter().collect()); - } - } + } => contract, + ExecutionResult::Revert { gas_used, output } => { + return Err(format!( + "Contract deployment transaction reverts with gas_used {gas_used} and output {:#x}", + output + )) + } + ExecutionResult::Halt { reason, gas_used } => return Err(format!( + "Contract deployment transaction halts unexpectedly with gas_used {gas_used} and reason {:?}", + reason + )), + _ => unreachable!(), + }; - fn inspector(&self) -> InspectorStack { - let mut stack = InspectorStack { - logs: Some(LogCollector::default()), - ..Default::default() - }; - if self.debugger { - let gas_inspector = Rc::new(RefCell::new(GasInspector::default())); - stack.gas = Some(gas_inspector.clone()); - stack.debugger = Some(Debugger::new(gas_inspector)); - } - stack - } + evm.env.tx = TxEnv { + gas_limit: u64::MAX, + transact_to: TransactTo::Call(contract), + data: calldata.into(), + ..Default::default() + }; - fn build_test_env( - &self, - caller: Address, - transact_to: TransactTo, - data: Bytes, - value: U256, - ) -> Env { - Env { - block: BlockEnv { - gas_limit: self.gas_limit, - ..BlockEnv::default() - }, - tx: TxEnv { - caller, - transact_to, - data, - value, - gas_limit: self.gas_limit.as_u64(), - ..TxEnv::default() - }, - ..Env::default() - } + let result = evm.transact_commit().unwrap(); + match result { + ExecutionResult::Success { gas_used, .. } => Ok(gas_used), + ExecutionResult::Revert { gas_used, output } => Err(format!( + "Contract call transaction reverts with gas_used {gas_used} and output {:#x}", + output + )), + ExecutionResult::Halt { reason, gas_used } => Err(format!( + "Contract call transaction halts unexpectedly with gas_used {gas_used} and reason {:?}", + reason + )), } } diff --git a/snark-verifier/src/loader/halo2.rs b/snark-verifier/src/loader/halo2.rs index 4d37c5ce..814fbda3 100644 --- a/snark-verifier/src/loader/halo2.rs +++ b/snark-verifier/src/loader/halo2.rs @@ -1,4 +1,4 @@ -//! `Loader` implementation for generating verifier in [`halo2_proofs`] circuit. +//! `Loader` implementation for generating verifier in [`halo2_proofs`](crate::halo2_proofs) circuit. pub(crate) mod loader; mod shim; diff --git a/snark-verifier/src/loader/halo2/loader.rs b/snark-verifier/src/loader/halo2/loader.rs index 31be9841..ecb8af19 100644 --- a/snark-verifier/src/loader/halo2/loader.rs +++ b/snark-verifier/src/loader/halo2/loader.rs @@ -16,7 +16,7 @@ use std::{ rc::Rc, }; -/// `Loader` implementation for generating verifier in [`halo2_proofs`] circuit. +/// `Loader` implementation for generating verifier in [`halo2_proofs`](crate::halo2_proofs) circuit. #[derive(Debug)] pub struct Halo2Loader> { ecc_chip: RefCell, @@ -136,15 +136,15 @@ impl> Halo2Loader { | (Value::Constant(constant), Value::Assigned(assigned)) => { Value::Assigned(self.scalar_chip().sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), assigned)], + &[(C::Scalar::ONE, assigned)], *constant, )) } (Value::Assigned(lhs), Value::Assigned(rhs)) => { Value::Assigned(self.scalar_chip().sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), lhs), (C::Scalar::one(), rhs)], - C::Scalar::zero(), + &[(C::Scalar::ONE, lhs), (C::Scalar::ONE, rhs)], + C::Scalar::ZERO, )) } }; @@ -161,14 +161,14 @@ impl> Halo2Loader { (Value::Constant(constant), Value::Assigned(assigned)) => { Value::Assigned(self.scalar_chip().sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(-C::Scalar::one(), assigned)], + &[(-C::Scalar::ONE, assigned)], *constant, )) } (Value::Assigned(assigned), Value::Constant(constant)) => { Value::Assigned(self.scalar_chip().sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), assigned)], + &[(C::Scalar::ONE, assigned)], -*constant, )) } @@ -191,14 +191,14 @@ impl> Halo2Loader { Value::Assigned(self.scalar_chip().sum_with_coeff_and_const( &mut self.ctx_mut(), &[(*constant, assigned)], - C::Scalar::zero(), + C::Scalar::ZERO, )) } (Value::Assigned(lhs), Value::Assigned(rhs)) => { Value::Assigned(self.scalar_chip().sum_products_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), lhs, rhs)], - C::Scalar::zero(), + &[(C::Scalar::ONE, lhs, rhs)], + C::Scalar::ZERO, )) } }; @@ -306,6 +306,14 @@ impl> LoadedScalar for Sc fn loader(&self) -> &Self::Loader { &self.loader } + + fn pow_var(&self, exp: &Self, max_bits: usize) -> Self { + let loader = self.loader(); + let base = self.clone().into_assigned(); + let exp = exp.clone().into_assigned(); + let res = loader.scalar_chip().pow_var(&mut loader.ctx_mut(), &base, &exp, max_bits); + loader.scalar_from_assigned(res) + } } impl> Debug for Scalar { @@ -557,7 +565,7 @@ impl> EcPointLoader for Rc + if scalar.eq(&C::Scalar::ONE) => { variable_base_non_scaled.push(base); } diff --git a/snark-verifier/src/loader/halo2/shim.rs b/snark-verifier/src/loader/halo2/shim.rs index 790c9e22..80d5eae2 100644 --- a/snark-verifier/src/loader/halo2/shim.rs +++ b/snark-verifier/src/loader/halo2/shim.rs @@ -1,8 +1,8 @@ -use crate::util::arithmetic::{CurveAffine, FieldExt}; +use crate::util::arithmetic::{CurveAffine, PrimeField}; use std::{fmt::Debug, ops::Deref}; /// Instructions to handle field element operations. -pub trait IntegerInstructions: Clone + Debug { +pub trait IntegerInstructions: Clone + Debug { /// Context (either enhanced `region` or some kind of builder). type Context: Debug; /// Assigned cell. @@ -24,8 +24,8 @@ pub trait IntegerInstructions: Clone + Debug { fn sum_with_coeff_and_const( &self, ctx: &mut Self::Context, - values: &[(F::Scalar, impl Deref)], - constant: F::Scalar, + values: &[(F, impl Deref)], + constant: F, ) -> Self::AssignedInteger; /// Sum product of integers with coefficients and constant. @@ -33,11 +33,11 @@ pub trait IntegerInstructions: Clone + Debug { &self, ctx: &mut Self::Context, values: &[( - F::Scalar, + F, impl Deref, impl Deref, )], - constant: F::Scalar, + constant: F, ) -> Self::AssignedInteger; /// Returns `lhs - rhs`. @@ -65,6 +65,15 @@ pub trait IntegerInstructions: Clone + Debug { lhs: &Self::AssignedInteger, rhs: &Self::AssignedInteger, ); + + /// Returns `base^exponent` and constrains that `exponent` has at most `max_bits` bits. + fn pow_var( + &self, + ctx: &mut Self::Context, + base: &Self::AssignedInteger, + exponent: &Self::AssignedInteger, + max_bits: usize, + ) -> Self::AssignedInteger; } /// Instructions to handle elliptic curve point operations. @@ -132,68 +141,70 @@ mod halo2_lib { use crate::halo2_proofs::halo2curves::CurveAffineExt; use crate::{ loader::halo2::{EccInstructions, IntegerInstructions}, - util::arithmetic::CurveAffine, + util::arithmetic::{CurveAffine, PrimeField}, }; + use halo2_base::gates::flex_gate::threads::SinglePhaseCoreManager; use halo2_base::{ self, - gates::{builder::GateThreadBuilder, GateChip, GateInstructions, RangeInstructions}, + gates::{GateChip, GateInstructions, RangeInstructions}, + utils::BigPrimeField, AssignedValue, QuantumCell::{Constant, Existing}, }; use halo2_ecc::bigint::ProperCrtUint; use halo2_ecc::{ ecc::{BaseFieldEccChip, EcPoint}, - fields::{FieldChip, PrimeField}, + fields::FieldChip, }; use std::ops::Deref; type AssignedInteger = ProperCrtUint<::ScalarExt>; type AssignedEcPoint = EcPoint<::ScalarExt, AssignedInteger>; - impl IntegerInstructions for GateChip { - type Context = GateThreadBuilder; + impl IntegerInstructions for GateChip { + type Context = SinglePhaseCoreManager; type AssignedCell = AssignedValue; type AssignedInteger = AssignedValue; fn assign_integer(&self, ctx: &mut Self::Context, integer: F) -> Self::AssignedInteger { - ctx.main(0).load_witness(integer) + ctx.main().load_witness(integer) } fn assign_constant(&self, ctx: &mut Self::Context, integer: F) -> Self::AssignedInteger { - ctx.main(0).load_constant(integer) + ctx.main().load_constant(integer) } fn sum_with_coeff_and_const( &self, ctx: &mut Self::Context, - values: &[(F::Scalar, impl Deref)], + values: &[(F, impl Deref)], constant: F, ) -> Self::AssignedInteger { let mut a = Vec::with_capacity(values.len() + 1); let mut b = Vec::with_capacity(values.len() + 1); - if constant != F::zero() { + if constant != F::ZERO { a.push(Constant(constant)); - b.push(Constant(F::one())); + b.push(Constant(F::ONE)); } a.extend(values.iter().map(|(_, a)| Existing(*a.deref()))); b.extend(values.iter().map(|(c, _)| Constant(*c))); - self.inner_product(ctx.main(0), a, b) + self.inner_product(ctx.main(), a, b) } fn sum_products_with_coeff_and_const( &self, ctx: &mut Self::Context, values: &[( - F::Scalar, + F, impl Deref, impl Deref, )], constant: F, ) -> Self::AssignedInteger { match values.len() { - 0 => ctx.main(0).load_constant(constant), + 0 => ctx.main().load_constant(constant), _ => self.sum_products_with_coeff_and_var( - ctx.main(0), + ctx.main(), values.iter().map(|(c, a, b)| (*c, Existing(*a.deref()), Existing(*b.deref()))), Constant(constant), ), @@ -206,11 +217,11 @@ mod halo2_lib { a: &Self::AssignedInteger, b: &Self::AssignedInteger, ) -> Self::AssignedInteger { - GateInstructions::sub(self, ctx.main(0), Existing(*a), Existing(*b)) + GateInstructions::sub(self, ctx.main(), Existing(*a), Existing(*b)) } fn neg(&self, ctx: &mut Self::Context, a: &Self::AssignedInteger) -> Self::AssignedInteger { - GateInstructions::neg(self, ctx.main(0), Existing(*a)) + GateInstructions::neg(self, ctx.main(), Existing(*a)) } fn invert( @@ -219,9 +230,9 @@ mod halo2_lib { a: &Self::AssignedInteger, ) -> Self::AssignedInteger { // make sure scalar != 0 - let is_zero = self.is_zero(ctx.main(0), *a); - self.assert_is_const(ctx.main(0), &is_zero, &F::zero()); - GateInstructions::div_unsafe(self, ctx.main(0), Constant(F::one()), Existing(*a)) + let is_zero = self.is_zero(ctx.main(), *a); + self.assert_is_const(ctx.main(), &is_zero, &F::ZERO); + GateInstructions::div_unsafe(self, ctx.main(), Constant(F::ONE), Existing(*a)) } fn assert_equal( @@ -230,16 +241,26 @@ mod halo2_lib { a: &Self::AssignedInteger, b: &Self::AssignedInteger, ) { - ctx.main(0).constrain_equal(a, b); + ctx.main().constrain_equal(a, b); + } + + fn pow_var( + &self, + ctx: &mut Self::Context, + base: &Self::AssignedInteger, + exponent: &Self::AssignedInteger, + max_bits: usize, + ) -> Self::AssignedInteger { + GateInstructions::pow_var(self, ctx.main(), *base, *exponent, max_bits) } } impl<'chip, C: CurveAffineExt> EccInstructions for BaseFieldEccChip<'chip, C> where - C::ScalarExt: PrimeField, - C::Base: PrimeField, + C::ScalarExt: BigPrimeField, + C::Base: BigPrimeField, { - type Context = GateThreadBuilder; + type Context = SinglePhaseCoreManager; type ScalarChip = GateChip; type AssignedCell = AssignedValue; type AssignedScalar = AssignedValue; @@ -250,11 +271,11 @@ mod halo2_lib { } fn assign_constant(&self, ctx: &mut Self::Context, point: C) -> Self::AssignedEcPoint { - self.assign_constant_point(ctx.main(0), point) + self.assign_constant_point(ctx.main(), point) } fn assign_point(&self, ctx: &mut Self::Context, point: C) -> Self::AssignedEcPoint { - self.assign_point(ctx.main(0), point) + self.assign_point(ctx.main(), point) } fn sum_with_const( @@ -270,7 +291,7 @@ mod halo2_lib { Some(constant) }; self.sum::( - ctx.main(0), + ctx.main(), constant.into_iter().chain(values.iter().map(|v| v.deref().clone())), ) } @@ -326,7 +347,7 @@ mod halo2_lib { a: &Self::AssignedEcPoint, b: &Self::AssignedEcPoint, ) { - self.assert_equal(ctx.main(0), a.clone(), b.clone()); + self.assert_equal(ctx.main(), a.clone(), b.clone()); } } } diff --git a/snark-verifier/src/loader/native.rs b/snark-verifier/src/loader/native.rs index 783aaa89..a9aa86ff 100644 --- a/snark-verifier/src/loader/native.rs +++ b/snark-verifier/src/loader/native.rs @@ -2,7 +2,7 @@ use crate::{ loader::{EcPointLoader, LoadedEcPoint, LoadedScalar, Loader, ScalarLoader}, - util::arithmetic::{Curve, CurveAffine, FieldOps, PrimeField}, + util::arithmetic::{fe_to_big, Curve, CurveAffine, FieldOps, PrimeField}, Error, }; use lazy_static::lazy_static; @@ -38,6 +38,11 @@ impl LoadedScalar for F { fn loader(&self) -> &NativeLoader { &LOADER } + + fn pow_var(&self, exp: &Self, _: usize) -> Self { + let exp = fe_to_big(*exp).to_u64_digits(); + self.pow_vartime(exp) + } } impl EcPointLoader for NativeLoader { diff --git a/snark-verifier/src/pcs.rs b/snark-verifier/src/pcs.rs index 65b1325b..1ca9eedc 100644 --- a/snark-verifier/src/pcs.rs +++ b/snark-verifier/src/pcs.rs @@ -3,7 +3,7 @@ use crate::{ loader::{native::NativeLoader, Loader}, util::{ - arithmetic::{CurveAffine, PrimeField}, + arithmetic::{CurveAffine, Rotation}, msm::Msm, transcript::{TranscriptRead, TranscriptWrite}, }, @@ -18,24 +18,26 @@ pub mod kzg; /// Query to an oracle. /// It assumes all queries are based on the same point, but with some `shift`. #[derive(Clone, Debug)] -pub struct Query { +pub struct Query { /// Index of polynomial to query pub poly: usize, /// Shift of the query point. - pub shift: F, + pub shift: S, + /// Shift loaded as either constant or witness. It is user's job to ensure this is correctly constrained to have value equal to `shift` + pub loaded_shift: T, /// Evaluation read from transcript. pub eval: T, } -impl Query { +impl Query { /// Initialize [`Query`] without evaluation. - pub fn new(poly: usize, shift: F) -> Self { - Self { poly, shift, eval: () } + pub fn new(poly: usize, shift: S) -> Self { + Self { poly, shift, loaded_shift: (), eval: () } } - /// Returns [`Query`] with evaluation. - pub fn with_evaluation(self, eval: T) -> Query { - Query { poly: self.poly, shift: self.shift, eval } + /// Returns [`Query`] with evaluation and optionally the shift are loaded as. + pub fn with_evaluation(self, loaded_shift: T, eval: T) -> Query { + Query { poly: self.poly, shift: self.shift, loaded_shift, eval } } } @@ -55,7 +57,7 @@ where /// Read [`PolynomialCommitmentScheme::Proof`] from transcript. fn read_proof( vk: &Self::VerifyingKey, - queries: &[Query], + queries: &[Query], transcript: &mut T, ) -> Result where @@ -66,7 +68,7 @@ where vk: &Self::VerifyingKey, commitments: &[Msm], point: &L::LoadedScalar, - queries: &[Query], + queries: &[Query], proof: &Self::Proof, ) -> Result; } diff --git a/snark-verifier/src/pcs/ipa.rs b/snark-verifier/src/pcs/ipa.rs index 6358e15d..288745d7 100644 --- a/snark-verifier/src/pcs/ipa.rs +++ b/snark-verifier/src/pcs/ipa.rs @@ -379,7 +379,7 @@ fn h_eval>(xi: &[T], z: &T) -> T { fn h_coeffs(xi: &[F], scalar: F) -> Vec { assert!(!xi.is_empty()); - let mut coeffs = vec![F::zero(); 1 << xi.len()]; + let mut coeffs = vec![F::ZERO; 1 << xi.len()]; coeffs[0] = scalar; for (len, xi) in xi.iter().rev().enumerate().map(|(i, xi)| (1 << i, xi)) { diff --git a/snark-verifier/src/pcs/ipa/accumulation.rs b/snark-verifier/src/pcs/ipa/accumulation.rs index 56d61aa7..51434541 100644 --- a/snark-verifier/src/pcs/ipa/accumulation.rs +++ b/snark-verifier/src/pcs/ipa/accumulation.rs @@ -186,13 +186,13 @@ where let (u, h) = instances .iter() - .map(|IpaAccumulator { u, xi }| (*u, h_coeffs(xi, C::Scalar::one()))) + .map(|IpaAccumulator { u, xi }| (*u, h_coeffs(xi, C::Scalar::ONE))) .chain(a_b_u.map(|(a, b, u)| { ( u, iter::empty() .chain([b, a]) - .chain(iter::repeat_with(C::Scalar::zero).take(pk.domain.n - 2)) + .chain(iter::repeat(C::Scalar::ZERO).take(pk.domain.n - 2)) .collect(), ) })) diff --git a/snark-verifier/src/pcs/ipa/decider.rs b/snark-verifier/src/pcs/ipa/decider.rs index 5235a857..6fd7026b 100644 --- a/snark-verifier/src/pcs/ipa/decider.rs +++ b/snark-verifier/src/pcs/ipa/decider.rs @@ -48,7 +48,7 @@ mod native { dk: &Self::DecidingKey, IpaAccumulator { u, xi }: IpaAccumulator, ) -> Result<(), Error> { - let h = h_coeffs(&xi, C::Scalar::one()); + let h = h_coeffs(&xi, C::Scalar::ONE); (u == multi_scalar_multiplication(&h, &dk.g).to_affine()) .then_some(()) .ok_or_else(|| Error::AssertionFailure("U == commit(G, h)".to_string())) diff --git a/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs b/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs index cae77a5f..5ea93c99 100644 --- a/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs +++ b/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs @@ -5,7 +5,7 @@ use crate::{ PolynomialCommitmentScheme, Query, }, util::{ - arithmetic::{CurveAffine, FieldExt, Fraction}, + arithmetic::{CurveAffine, Fraction, PrimeField, Rotation}, msm::Msm, transcript::TranscriptRead, Itertools, @@ -19,7 +19,7 @@ use std::{ }; /// Verifier of multi-open inner product argument. It is for the implementation -/// in [`halo2_proofs`], which is previously +/// in [`halo2_proofs`](crate::halo2_proofs), which is previously /// . #[derive(Clone, Debug)] pub struct Bgh19; @@ -35,7 +35,7 @@ where fn read_proof( svk: &Self::VerifyingKey, - queries: &[Query], + queries: &[Query], transcript: &mut T, ) -> Result where @@ -48,7 +48,7 @@ where svk: &Self::VerifyingKey, commitments: &[Msm], x: &L::LoadedScalar, - queries: &[Query], + queries: &[Query], proof: &Self::Proof, ) -> Result { let loader = x.loader(); @@ -119,7 +119,7 @@ where { fn read>( svk: &IpaSuccinctVerifyingKey, - queries: &[Query], + queries: &[Query], transcript: &mut T, ) -> Result { // Multiopen @@ -157,28 +157,33 @@ where } } -fn query_sets(queries: &[Query]) -> Vec> +fn query_sets(queries: &[Query]) -> Vec> where - F: FieldExt, + S: PartialEq + Ord + Copy, T: Clone, { let poly_shifts = - queries.iter().fold(Vec::<(usize, Vec, Vec<&T>)>::new(), |mut poly_shifts, query| { + queries.iter().fold(Vec::<(usize, Vec<_>, Vec<&T>)>::new(), |mut poly_shifts, query| { if let Some(pos) = poly_shifts.iter().position(|(poly, _, _)| *poly == query.poly) { let (_, shifts, evals) = &mut poly_shifts[pos]; - if !shifts.contains(&query.shift) { - shifts.push(query.shift); + if !shifts.iter().map(|(shift, _)| shift).contains(&query.shift) { + shifts.push((query.shift, query.loaded_shift.clone())); evals.push(&query.eval); } } else { - poly_shifts.push((query.poly, vec![query.shift], vec![&query.eval])); + poly_shifts.push(( + query.poly, + vec![(query.shift, query.loaded_shift.clone())], + vec![&query.eval], + )); } poly_shifts }); - poly_shifts.into_iter().fold(Vec::>::new(), |mut sets, (poly, shifts, evals)| { + poly_shifts.into_iter().fold(Vec::>::new(), |mut sets, (poly, shifts, evals)| { if let Some(pos) = sets.iter().position(|set| { - BTreeSet::from_iter(set.shifts.iter()) == BTreeSet::from_iter(shifts.iter()) + BTreeSet::from_iter(set.shifts.iter().map(|(shift, _)| shift)) + == BTreeSet::from_iter(shifts.iter().map(|(shift, _)| shift)) }) { let set = &mut sets[pos]; if !set.polys.contains(&poly) { @@ -187,7 +192,7 @@ where set.shifts .iter() .map(|lhs| { - let idx = shifts.iter().position(|rhs| lhs == rhs).unwrap(); + let idx = shifts.iter().position(|rhs| lhs.0 == rhs.0).unwrap(); evals[idx] }) .collect(), @@ -201,18 +206,23 @@ where }) } -fn query_set_coeffs(sets: &[QuerySet], x: &T, x_3: &T) -> Vec> +fn query_set_coeffs( + sets: &[QuerySet], + x: &T, + x_3: &T, +) -> Vec> where - F: FieldExt, + F: PrimeField + Ord, T: LoadedScalar, { - let loader = x.loader(); - let superset = sets.iter().flat_map(|set| set.shifts.clone()).sorted().dedup(); + let superset = BTreeMap::from_iter(sets.iter().flat_map(|set| set.shifts.clone())); let size = sets.iter().map(|set| set.shifts.len()).chain(Some(2)).max().unwrap(); let powers_of_x = x.powers(size); let x_3_minus_x_shift_i = BTreeMap::from_iter( - superset.map(|shift| (shift, x_3.clone() - x.clone() * loader.load_const(&shift))), + superset + .into_iter() + .map(|(shift, loaded_shift)| (shift, x_3.clone() - x.clone() * loaded_shift)), ); let mut coeffs = sets @@ -228,23 +238,22 @@ where } #[derive(Clone, Debug)] -struct QuerySet<'a, F, T> { - shifts: Vec, +struct QuerySet<'a, S, T> { + shifts: Vec<(S, T)>, polys: Vec, evals: Vec>, } -impl<'a, F, T> QuerySet<'a, F, T> -where - F: FieldExt, - T: LoadedScalar, -{ +impl<'a, S, T> QuerySet<'a, S, T> { fn msm>( &self, commitments: &[Msm<'a, C, L>], q_eval: &T, powers_of_x_1: &[T], - ) -> Msm { + ) -> Msm + where + T: LoadedScalar, + { self.polys .iter() .rev() @@ -254,7 +263,15 @@ where - Msm::constant(q_eval.clone()) } - fn f_eval(&self, coeff: &QuerySetCoeff, q_eval: &T, powers_of_x_1: &[T]) -> T { + fn f_eval( + &self, + coeff: &QuerySetCoeff, + q_eval: &T, + powers_of_x_1: &[T], + ) -> T + where + T: LoadedScalar, + { let loader = q_eval.loader(); let r_eval = { let r_evals = self @@ -288,10 +305,15 @@ struct QuerySetCoeff { impl QuerySetCoeff where - F: FieldExt, + F: PrimeField + Ord, T: LoadedScalar, { - fn new(shifts: &[F], powers_of_x: &[T], x_3: &T, x_3_minus_x_shift_i: &BTreeMap) -> Self { + fn new( + shifts: &[(Rotation, T)], + powers_of_x: &[T], + x_3: &T, + x_3_minus_x_shift_i: &BTreeMap, + ) -> Self { let loader = x_3.loader(); let normalized_ell_primes = shifts .iter() @@ -301,9 +323,9 @@ where .iter() .enumerate() .filter(|&(i, _)| i != j) - .map(|(_, shift_i)| (*shift_j - shift_i)) + .map(|(_, shift_i)| (shift_j.1.clone() - &shift_i.1)) .reduce(|acc, value| acc * value) - .unwrap_or_else(|| F::one()) + .unwrap_or_else(|| loader.load_const(&F::ONE)) }) .collect_vec(); @@ -313,17 +335,15 @@ where let barycentric_weights = shifts .iter() .zip(normalized_ell_primes.iter()) - .map(|(shift, normalized_ell_prime)| { - loader.sum_products_with_coeff(&[ - (*normalized_ell_prime, x_pow_k_minus_one, x_3), - (-(*normalized_ell_prime * shift), x_pow_k_minus_one, x), - ]) + .map(|((_, loaded_shift), normalized_ell_prime)| { + let tmp = normalized_ell_prime.clone() * x_pow_k_minus_one; + loader.sum_products(&[(&tmp, x_3), (&-(tmp.clone() * loaded_shift), x)]) }) .map(Fraction::one_over) .collect_vec(); let f_eval_coeff = Fraction::one_over(loader.product( - &shifts.iter().map(|shift| x_3_minus_x_shift_i.get(shift).unwrap()).collect_vec(), + &shifts.iter().map(|(shift, _)| x_3_minus_x_shift_i.get(shift).unwrap()).collect_vec(), )); Self { diff --git a/snark-verifier/src/pcs/kzg.rs b/snark-verifier/src/pcs/kzg.rs index 8f416ee3..387a108c 100644 --- a/snark-verifier/src/pcs/kzg.rs +++ b/snark-verifier/src/pcs/kzg.rs @@ -18,7 +18,7 @@ pub use accumulator::LimbsEncodingInstructions; /// KZG succinct verifying key. #[derive(Clone, Copy, Debug)] -pub struct KzgSuccinctVerifyingKey { +pub struct KzgSuccinctVerifyingKey { /// Generator. pub g: C, } diff --git a/snark-verifier/src/pcs/kzg/accumulation.rs b/snark-verifier/src/pcs/kzg/accumulation.rs index 1f901568..d71e366e 100644 --- a/snark-verifier/src/pcs/kzg/accumulation.rs +++ b/snark-verifier/src/pcs/kzg/accumulation.rs @@ -19,6 +19,7 @@ pub struct KzgAs(PhantomData<(M, MOS)>); impl AccumulationScheme for KzgAs where M: MultiMillerLoop, + M::G1Affine: CurveAffine, L: Loader, MOS: Clone + Debug, { @@ -139,6 +140,7 @@ where impl AccumulationSchemeProver for KzgAs where M: MultiMillerLoop, + M::G1Affine: CurveAffine, MOS: Clone + Debug, { type ProvingKey = KzgAsProvingKey; @@ -163,7 +165,7 @@ where let blind = pk .zk() .then(|| { - let s = M::Scalar::random(rng); + let s = M::Fr::random(rng); let (g, s_g) = pk.0.unwrap(); let lhs = (s_g * s).to_affine(); let rhs = (g * s).to_affine(); diff --git a/snark-verifier/src/pcs/kzg/accumulator.rs b/snark-verifier/src/pcs/kzg/accumulator.rs index 82d1454b..37cb493f 100644 --- a/snark-verifier/src/pcs/kzg/accumulator.rs +++ b/snark-verifier/src/pcs/kzg/accumulator.rs @@ -59,7 +59,6 @@ mod native { let [lhs_x, lhs_y, rhs_x, rhs_y]: [_; 4] = limbs .chunks(LIMBS) - .into_iter() .map(|limbs| { fe_from_limbs::<_, _, LIMBS, BITS>( limbs.iter().map(|limb| **limb).collect_vec().try_into().unwrap(), @@ -109,7 +108,6 @@ mod evm { let [lhs_x, lhs_y, rhs_x, rhs_y]: [[_; LIMBS]; 4] = limbs .chunks(LIMBS) - .into_iter() .map(|limbs| limbs.to_vec().try_into().unwrap()) .collect_vec() .try_into() @@ -204,14 +202,15 @@ mod halo2 { mod halo2_lib { use super::*; use halo2_base::halo2_proofs::halo2curves::CurveAffineExt; - use halo2_ecc::{ecc::BaseFieldEccChip, fields::PrimeField}; + use halo2_base::utils::BigPrimeField; + use halo2_ecc::ecc::BaseFieldEccChip; impl<'chip, C, const LIMBS: usize, const BITS: usize> LimbsEncodingInstructions for BaseFieldEccChip<'chip, C> where C: CurveAffineExt, - C::ScalarExt: PrimeField, - C::Base: PrimeField, + C::ScalarExt: BigPrimeField, + C::Base: BigPrimeField, { fn assign_ec_point_from_limbs( &self, @@ -221,7 +220,7 @@ mod halo2 { assert_eq!(limbs.len(), 2 * LIMBS); let ec_point = self.assign_point::( - ctx.main(0), + ctx.main(), ec_point_from_limbs::<_, LIMBS, BITS>( &limbs.iter().map(|limb| limb.value()).collect_vec(), ), @@ -231,7 +230,7 @@ mod halo2 { .iter() .zip_eq(iter::empty().chain(ec_point.x().limbs()).chain(ec_point.y().limbs())) { - ctx.main(0).constrain_equal(src, dst); + ctx.main().constrain_equal(src, dst); } ec_point diff --git a/snark-verifier/src/pcs/kzg/decider.rs b/snark-verifier/src/pcs/kzg/decider.rs index 59f1afbf..d55e0a57 100644 --- a/snark-verifier/src/pcs/kzg/decider.rs +++ b/snark-verifier/src/pcs/kzg/decider.rs @@ -1,4 +1,7 @@ -use crate::{pcs::kzg::KzgSuccinctVerifyingKey, util::arithmetic::MultiMillerLoop}; +use crate::{ + pcs::kzg::KzgSuccinctVerifyingKey, + util::arithmetic::{CurveAffine, MultiMillerLoop}, +}; use std::marker::PhantomData; /// KZG deciding key. @@ -23,7 +26,10 @@ impl KzgDecidingKey { } } -impl From<(M::G1Affine, M::G2Affine, M::G2Affine)> for KzgDecidingKey { +impl From<(M::G1Affine, M::G2Affine, M::G2Affine)> for KzgDecidingKey +where + M::G1Affine: CurveAffine, +{ fn from((g1, g2, s_g2): (M::G1Affine, M::G2Affine, M::G2Affine)) -> KzgDecidingKey { KzgDecidingKey::new(g1, g2, s_g2) } @@ -43,7 +49,7 @@ mod native { AccumulationDecider, }, util::{ - arithmetic::{Group, MillerLoopResult, MultiMillerLoop}, + arithmetic::{CurveAffine, Group, MillerLoopResult, MultiMillerLoop}, Itertools, }, Error, @@ -53,6 +59,7 @@ mod native { impl AccumulationDecider for KzgAs where M: MultiMillerLoop, + M::G1Affine: CurveAffine, MOS: Clone + Debug, { type DecidingKey = KzgDecidingKey; @@ -103,7 +110,9 @@ mod evm { impl AccumulationDecider> for KzgAs where M: MultiMillerLoop, - M::Scalar: PrimeField, + M::G1Affine: CurveAffine, + M::G2Affine: CurveAffine, + M::Fr: PrimeField, MOS: Clone + Debug, { type DecidingKey = KzgDecidingKey; @@ -118,10 +127,10 @@ mod evm { let x = coordinates.x().to_repr(); let y = coordinates.y().to_repr(); ( - U256::from_little_endian(&x.as_ref()[32..]), - U256::from_little_endian(&x.as_ref()[..32]), - U256::from_little_endian(&y.as_ref()[32..]), - U256::from_little_endian(&y.as_ref()[..32]), + U256::try_from_le_slice(&x.as_ref()[32..]).unwrap(), + U256::try_from_le_slice(&x.as_ref()[..32]).unwrap(), + U256::try_from_le_slice(&y.as_ref()[32..]).unwrap(), + U256::try_from_le_slice(&y.as_ref()[..32]).unwrap(), ) }); loader.pairing(&lhs, g2, &rhs, minus_s_g2); @@ -152,7 +161,7 @@ mod evm { loader.code_mut().runtime_append(code); let challenge = loader.scalar(Value::Memory(challenge_ptr)); - let powers_of_challenge = LoadedScalar::::powers(&challenge, lhs.len()); + let powers_of_challenge = LoadedScalar::::powers(&challenge, lhs.len()); let [lhs, rhs] = [lhs, rhs].map(|msms| { msms.iter() .zip(powers_of_challenge.iter()) diff --git a/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs b/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs index 3a448056..f3f60b8d 100644 --- a/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs +++ b/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs @@ -6,7 +6,7 @@ use crate::{ PolynomialCommitmentScheme, Query, }, util::{ - arithmetic::{CurveAffine, FieldExt, Fraction, MultiMillerLoop}, + arithmetic::{CurveAffine, Fraction, MultiMillerLoop, PrimeField, Rotation}, msm::Msm, transcript::TranscriptRead, Itertools, @@ -19,7 +19,7 @@ use std::{ }; /// Verifier of multi-open KZG. It is for the SHPLONK implementation -/// in [`halo2_proofs`]. +/// in [`halo2_proofs`](crate::halo2_proofs). /// Notations are following . #[derive(Clone, Debug)] pub struct Bdfg21; @@ -27,6 +27,8 @@ pub struct Bdfg21; impl PolynomialCommitmentScheme for KzgAs where M: MultiMillerLoop, + M::G1Affine: CurveAffine, + M::Fr: Ord, L: Loader, { type VerifyingKey = KzgSuccinctVerifyingKey; @@ -35,7 +37,7 @@ where fn read_proof( _: &KzgSuccinctVerifyingKey, - _: &[Query], + _: &[Query], transcript: &mut T, ) -> Result, Error> where @@ -48,22 +50,21 @@ where svk: &KzgSuccinctVerifyingKey, commitments: &[Msm], z: &L::LoadedScalar, - queries: &[Query], + queries: &[Query], proof: &Bdfg21Proof, ) -> Result { let sets = query_sets(queries); let f = { let coeffs = query_set_coeffs(&sets, z, &proof.z_prime); - let powers_of_mu = proof - .mu - .powers(sets.iter().map(|set| set.polys.len()).max().unwrap()); + let powers_of_mu = + proof.mu.powers(sets.iter().map(|set| set.polys.len()).max().unwrap()); let msms = sets .iter() .zip(coeffs.iter()) .map(|(set, coeff)| set.msm(coeff, commitments, &powers_of_mu)); - msms.zip(proof.gamma.powers(sets.len()).into_iter()) + msms.zip(proof.gamma.powers(sets.len())) .map(|(msm, power_of_gamma)| msm * &power_of_gamma) .sum::>() - Msm::base(&proof.w) * &coeffs[0].z_s @@ -72,10 +73,7 @@ where let rhs = Msm::base(&proof.w_prime); let lhs = f + rhs.clone() * &proof.z_prime; - Ok(KzgAccumulator::new( - lhs.evaluate(Some(svk.g)), - rhs.evaluate(Some(svk.g)), - )) + Ok(KzgAccumulator::new(lhs.evaluate(Some(svk.g)), rhs.evaluate(Some(svk.g)))) } } @@ -104,94 +102,71 @@ where let w = transcript.read_ec_point()?; let z_prime = transcript.squeeze_challenge(); let w_prime = transcript.read_ec_point()?; - Ok(Bdfg21Proof { - mu, - gamma, - w, - z_prime, - w_prime, - }) + Ok(Bdfg21Proof { mu, gamma, w, z_prime, w_prime }) } } -fn query_sets(queries: &[Query]) -> Vec> { - let poly_shifts = queries.iter().fold( - Vec::<(usize, Vec, Vec<&T>)>::new(), - |mut poly_shifts, query| { - if let Some(pos) = poly_shifts - .iter() - .position(|(poly, _, _)| *poly == query.poly) - { +fn query_sets(queries: &[Query]) -> Vec> { + let poly_shifts = + queries.iter().fold(Vec::<(usize, Vec<_>, Vec<&T>)>::new(), |mut poly_shifts, query| { + if let Some(pos) = poly_shifts.iter().position(|(poly, _, _)| *poly == query.poly) { let (_, shifts, evals) = &mut poly_shifts[pos]; - if !shifts.contains(&query.shift) { - shifts.push(query.shift); + if !shifts.iter().map(|(shift, _)| shift).contains(&query.shift) { + shifts.push((query.shift, query.loaded_shift.clone())); evals.push(&query.eval); } } else { - poly_shifts.push((query.poly, vec![query.shift], vec![&query.eval])); + poly_shifts.push(( + query.poly, + vec![(query.shift, query.loaded_shift.clone())], + vec![&query.eval], + )); } poly_shifts - }, - ); - - poly_shifts.into_iter().fold( - Vec::>::new(), - |mut sets, (poly, shifts, evals)| { - if let Some(pos) = sets.iter().position(|set| { - BTreeSet::from_iter(set.shifts.iter()) == BTreeSet::from_iter(shifts.iter()) - }) { - let set = &mut sets[pos]; - if !set.polys.contains(&poly) { - set.polys.push(poly); - set.evals.push( - set.shifts - .iter() - .map(|lhs| { - let idx = shifts.iter().position(|rhs| lhs == rhs).unwrap(); - evals[idx] - }) - .collect(), - ); - } - } else { - let set = QuerySet { - shifts, - polys: vec![poly], - evals: vec![evals], - }; - sets.push(set); + }); + + poly_shifts.into_iter().fold(Vec::>::new(), |mut sets, (poly, shifts, evals)| { + if let Some(pos) = sets.iter().position(|set| { + BTreeSet::from_iter(set.shifts.iter().map(|(shift, _)| shift)) + == BTreeSet::from_iter(shifts.iter().map(|(shift, _)| shift)) + }) { + let set = &mut sets[pos]; + if !set.polys.contains(&poly) { + set.polys.push(poly); + set.evals.push( + set.shifts + .iter() + .map(|lhs| { + let idx = shifts.iter().position(|rhs| lhs.0 == rhs.0).unwrap(); + evals[idx] + }) + .collect(), + ); } - sets - }, - ) + } else { + let set = QuerySet { shifts, polys: vec![poly], evals: vec![evals] }; + sets.push(set); + } + sets + }) } -fn query_set_coeffs<'a, F: FieldExt, T: LoadedScalar>( - sets: &[QuerySet<'a, F, T>], +fn query_set_coeffs>( + sets: &[QuerySet], z: &T, z_prime: &T, ) -> Vec> { - let loader = z.loader(); + // map of shift => loaded_shift, removing duplicate `shift` values + // shift is the rotation, not omega^rotation, to ensure BTreeMap does not depend on omega (otherwise ordering can change) + let superset = BTreeMap::from_iter(sets.iter().flat_map(|set| set.shifts.clone())); - let superset = sets - .iter() - .flat_map(|set| set.shifts.clone()) - .sorted() - .dedup(); - - let size = sets - .iter() - .map(|set| set.shifts.len()) - .chain(Some(2)) - .max() - .unwrap(); + let size = sets.iter().map(|set| set.shifts.len()).chain(Some(2)).max().unwrap(); let powers_of_z = z.powers(size); - let z_prime_minus_z_shift_i = BTreeMap::from_iter(superset.map(|shift| { - ( - shift, - z_prime.clone() - z.clone() * loader.load_const(&shift), - ) - })); + let z_prime_minus_z_shift_i = BTreeMap::from_iter( + superset + .into_iter() + .map(|(shift, loaded_shift)| (shift, z_prime.clone() - z.clone() * loaded_shift)), + ); let mut z_s_1 = None; let mut coeffs = sets @@ -219,19 +194,22 @@ fn query_set_coeffs<'a, F: FieldExt, T: LoadedScalar>( } #[derive(Clone, Debug)] -struct QuerySet<'a, F, T> { - shifts: Vec, +struct QuerySet<'a, S, T> { + shifts: Vec<(S, T)>, // vec of (shift, loaded_shift) polys: Vec, evals: Vec>, } -impl<'a, F: FieldExt, T: LoadedScalar> QuerySet<'a, F, T> { +impl<'a, S, T> QuerySet<'a, S, T> { fn msm>( &self, - coeff: &QuerySetCoeff, + coeff: &QuerySetCoeff, commitments: &[Msm<'a, C, L>], powers_of_mu: &[T], - ) -> Msm { + ) -> Msm + where + T: LoadedScalar, + { self.polys .iter() .zip(self.evals.iter()) @@ -270,14 +248,14 @@ struct QuerySetCoeff { impl QuerySetCoeff where - F: FieldExt, + F: PrimeField + Ord, T: LoadedScalar, { fn new( - shifts: &[F], + shifts: &[(Rotation, T)], powers_of_z: &[T], z_prime: &T, - z_prime_minus_z_shift_i: &BTreeMap, + z_prime_minus_z_shift_i: &BTreeMap, z_s_1: &Option, ) -> Self { let loader = z_prime.loader(); @@ -290,9 +268,9 @@ where .iter() .enumerate() .filter(|&(i, _)| i != j) - .map(|(_, shift_i)| (*shift_j - shift_i)) + .map(|(_, shift_i)| (shift_j.1.clone() - &shift_i.1)) .reduce(|acc, value| acc * value) - .unwrap_or_else(|| F::one()) + .unwrap_or_else(|| loader.load_const(&F::ONE)) }) .collect_vec(); @@ -302,11 +280,9 @@ where let barycentric_weights = shifts .iter() .zip(normalized_ell_primes.iter()) - .map(|(shift, normalized_ell_prime)| { - loader.sum_products_with_coeff(&[ - (*normalized_ell_prime, z_pow_k_minus_one, z_prime), - (-(*normalized_ell_prime * shift), z_pow_k_minus_one, z), - ]) + .map(|((_, loaded_shift), normalized_ell_prime)| { + let tmp = normalized_ell_prime.clone() * z_pow_k_minus_one; + loader.sum_products(&[(&tmp, z_prime), (&-(tmp.clone() * loaded_shift), z)]) }) .map(Fraction::one_over) .collect_vec(); @@ -314,7 +290,7 @@ where let z_s = loader.product( &shifts .iter() - .map(|shift| z_prime_minus_z_shift_i.get(shift).unwrap()) + .map(|(shift, _)| z_prime_minus_z_shift_i.get(shift).unwrap()) .collect_vec(), ); let z_s_1_over_z_s = z_s_1.clone().map(|z_s_1| Fraction::new(z_s_1, z_s.clone())); @@ -344,13 +320,8 @@ where .iter_mut() .chain(self.commitment_coeff.as_mut()) .for_each(Fraction::evaluate); - let barycentric_weights_sum = loader.sum( - &self - .eval_coeffs - .iter() - .map(Fraction::evaluated) - .collect_vec(), - ); + let barycentric_weights_sum = + loader.sum(&self.eval_coeffs.iter().map(Fraction::evaluated).collect_vec()); self.r_eval_coeff = Some(match self.commitment_coeff.as_ref() { Some(coeff) => Fraction::new(coeff.evaluated().clone(), barycentric_weights_sum), None => Fraction::one_over(barycentric_weights_sum), @@ -370,13 +341,9 @@ impl CostEstimation for KzgAs where M: MultiMillerLoop, { - type Input = Vec>; + type Input = Vec>; - fn estimate_cost(_: &Vec>) -> Cost { - Cost { - num_commitment: 2, - num_msm: 2, - ..Default::default() - } + fn estimate_cost(_: &Vec>) -> Cost { + Cost { num_commitment: 2, num_msm: 2, ..Default::default() } } } diff --git a/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs b/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs index e5741163..b8bd4bf9 100644 --- a/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs +++ b/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs @@ -6,7 +6,7 @@ use crate::{ PolynomialCommitmentScheme, Query, }, util::{ - arithmetic::{CurveAffine, MultiMillerLoop, PrimeField}, + arithmetic::{CurveAffine, MultiMillerLoop, Rotation}, msm::Msm, transcript::TranscriptRead, Itertools, @@ -15,7 +15,7 @@ use crate::{ }; /// Verifier of multi-open KZG. It is for the GWC implementation -/// in [`halo2_proofs`]. +/// in [`halo2_proofs`](crate::halo2_proofs). /// Notations are following . #[derive(Clone, Debug)] pub struct Gwc19; @@ -23,6 +23,7 @@ pub struct Gwc19; impl PolynomialCommitmentScheme for KzgAs where M: MultiMillerLoop, + M::G1Affine: CurveAffine, L: Loader, { type VerifyingKey = KzgSuccinctVerifyingKey; @@ -31,7 +32,7 @@ where fn read_proof( _: &Self::VerifyingKey, - queries: &[Query], + queries: &[Query], transcript: &mut T, ) -> Result where @@ -44,22 +45,23 @@ where svk: &Self::VerifyingKey, commitments: &[Msm], z: &L::LoadedScalar, - queries: &[Query], + queries: &[Query], proof: &Self::Proof, ) -> Result { let sets = query_sets(queries); let powers_of_u = &proof.u.powers(sets.len()); let f = { - let powers_of_v = proof - .v - .powers(sets.iter().map(|set| set.polys.len()).max().unwrap()); + let powers_of_v = proof.v.powers(sets.iter().map(|set| set.polys.len()).max().unwrap()); sets.iter() .map(|set| set.msm(commitments, &powers_of_v)) .zip(powers_of_u.iter()) .map(|(msm, power_of_u)| msm * power_of_u) .sum::>() }; - let z_omegas = sets.iter().map(|set| z.loader().load_const(&set.shift) * z); + let z_omegas = sets.iter().map(|set| { + let loaded_shift = set.loaded_shift.clone(); + loaded_shift * z + }); let rhs = proof .ws @@ -67,11 +69,7 @@ where .zip(powers_of_u.iter()) .map(|(w, power_of_u)| Msm::base(w) * power_of_u) .collect_vec(); - let lhs = f + rhs - .iter() - .zip(z_omegas) - .map(|(uw, z_omega)| uw.clone() * &z_omega) - .sum(); + let lhs = f + rhs.iter().zip(z_omegas).map(|(uw, z_omega)| uw.clone() * &z_omega).sum(); Ok(KzgAccumulator::new( lhs.evaluate(Some(svk.g)), @@ -97,7 +95,7 @@ where C: CurveAffine, L: Loader, { - fn read(queries: &[Query], transcript: &mut T) -> Result + fn read(queries: &[Query], transcript: &mut T) -> Result where T: TranscriptRead, { @@ -108,22 +106,25 @@ where } } -struct QuerySet<'a, F, T> { - shift: F, +struct QuerySet<'a, S, T> { + shift: S, + loaded_shift: T, polys: Vec, evals: Vec<&'a T>, } -impl<'a, F, T> QuerySet<'a, F, T> +impl<'a, S, T> QuerySet<'a, S, T> where - F: PrimeField, T: Clone, { fn msm>( &self, commitments: &[Msm<'a, C, L>], powers_of_v: &[L::LoadedScalar], - ) -> Msm { + ) -> Msm + where + T: LoadedScalar, + { self.polys .iter() .zip(self.evals.iter().cloned()) @@ -137,9 +138,9 @@ where } } -fn query_sets(queries: &[Query]) -> Vec> +fn query_sets(queries: &[Query]) -> Vec> where - F: PrimeField, + S: PartialEq + Copy, T: Clone + PartialEq, { queries.iter().fold(Vec::new(), |mut sets, query| { @@ -149,6 +150,7 @@ where } else { sets.push(QuerySet { shift: query.shift, + loaded_shift: query.loaded_shift.clone(), polys: vec![query.poly], evals: vec![&query.eval], }); @@ -161,14 +163,10 @@ impl CostEstimation for KzgAs where M: MultiMillerLoop, { - type Input = Vec>; + type Input = Vec>; - fn estimate_cost(queries: &Vec>) -> Cost { + fn estimate_cost(queries: &Vec>) -> Cost { let num_w = query_sets(queries).len(); - Cost { - num_commitment: num_w, - num_msm: num_w, - ..Default::default() - } + Cost { num_commitment: num_w, num_msm: num_w, ..Default::default() } } } diff --git a/snark-verifier/src/system/halo2.rs b/snark-verifier/src/system/halo2.rs index 98f4488c..573ab845 100644 --- a/snark-verifier/src/system/halo2.rs +++ b/snark-verifier/src/system/halo2.rs @@ -1,4 +1,4 @@ -//! [`halo2_proofs`] proof system +//! [`halo2_proofs`](crate::halo2_proofs) proof system use crate::halo2_proofs::{ plonk::{self, Any, ConstraintSystem, FirstPhase, SecondPhase, ThirdPhase, VerifyingKey}, @@ -7,7 +7,7 @@ use crate::halo2_proofs::{ }; use crate::{ util::{ - arithmetic::{root_of_unity, CurveAffine, Domain, FieldExt, Rotation}, + arithmetic::{root_of_unity, CurveAffine, Domain, PrimeField, Rotation}, Itertools, }, verifier::plonk::protocol::{ @@ -21,7 +21,7 @@ use std::{io, iter, mem::size_of}; pub mod strategy; pub mod transcript; -/// Configuration for converting a [`VerifyingKey`] of [`halo2_proofs`] into +/// Configuration for converting a [`VerifyingKey`] of [`halo2_proofs`](crate::halo2_proofs) into /// [`PlonkProtocol`]. #[derive(Clone, Debug, Default)] pub struct Config { @@ -78,7 +78,7 @@ impl Config { } } -/// Convert a [`VerifyingKey`] of [`halo2_proofs`] into [`PlonkProtocol`]. +/// Convert a [`VerifyingKey`] of [`halo2_proofs`](crate::halo2_proofs) into [`PlonkProtocol`]. pub fn compile<'a, C: CurveAffine, P: Params<'a, C>>( params: &P, vk: &VerifyingKey, @@ -141,6 +141,7 @@ pub fn compile<'a, C: CurveAffine, P: Params<'a, C>>( PlonkProtocol { domain, + domain_as_witness: None, preprocessed, num_instance: polynomials.num_instance(), num_witness: polynomials.num_witness(), @@ -161,7 +162,7 @@ impl From for Rotation { } } -struct Polynomials<'a, F: FieldExt> { +struct Polynomials<'a, F: PrimeField> { cs: &'a ConstraintSystem, zk: bool, query_instance: bool, @@ -179,7 +180,7 @@ struct Polynomials<'a, F: FieldExt> { num_lookup_z: usize, } -impl<'a, F: FieldExt> Polynomials<'a, F> { +impl<'a, F: PrimeField> Polynomials<'a, F> { fn new( cs: &'a ConstraintSystem, zk: bool, @@ -474,12 +475,11 @@ impl<'a, F: FieldExt> Polynomials<'a, F> { } fn l_active(&self) -> Expression { - Expression::Constant(F::one()) - self.l_last() - self.l_blind() + Expression::Constant(F::ONE) - self.l_last() - self.l_blind() } fn system_challenge_offset(&self) -> usize { - let num_challenge = self.num_challenge(); - num_challenge[..num_challenge.len() - 3].iter().sum() + self.num_challenge.iter().sum() } fn theta(&self) -> Expression { @@ -499,7 +499,7 @@ impl<'a, F: FieldExt> Polynomials<'a, F> { } fn permutation_constraints(&'a self, t: usize) -> impl IntoIterator> + 'a { - let one = &Expression::Constant(F::one()); + let one = &Expression::Constant(F::ONE); let l_0 = &Expression::::CommonPolynomial(CommonPolynomial::Lagrange(0)); let l_last = &self.l_last(); let l_active = &self.l_active(); @@ -591,7 +591,7 @@ impl<'a, F: FieldExt> Polynomials<'a, F> { } fn lookup_constraints(&'a self, t: usize) -> impl IntoIterator> + 'a { - let one = &Expression::Constant(F::one()); + let one = &Expression::Constant(F::ONE); let l_0 = &Expression::::CommonPolynomial(CommonPolynomial::Lagrange(0)); let l_last = &self.l_last(); let l_active = &self.l_active(); @@ -698,7 +698,7 @@ impl EncodedChallenge for MockChallenge { } #[derive(Default)] -struct MockTranscript(F); +struct MockTranscript(F); impl Transcript for MockTranscript { fn squeeze_challenge(&mut self) -> MockChallenge { diff --git a/snark-verifier/src/system/halo2/transcript.rs b/snark-verifier/src/system/halo2/transcript.rs index 9cfd6b89..10da3a22 100644 --- a/snark-verifier/src/system/halo2/transcript.rs +++ b/snark-verifier/src/system/halo2/transcript.rs @@ -1,7 +1,6 @@ //! Transcripts implemented with both `halo2_proofs::transcript` and //! `crate::util::transcript`. use crate::halo2_proofs; -use halo2_proofs::transcript::{Blake2bRead, Blake2bWrite, Challenge255}; use crate::{ loader::native::{self, NativeLoader}, util::{ @@ -10,6 +9,8 @@ use crate::{ }, Error, }; +use halo2_proofs::transcript::{Blake2bRead, Blake2bWrite, Challenge255}; +use pairing::group::ff::FromUniformBytes; use std::io::{Read, Write}; #[cfg(feature = "loader_evm")] @@ -18,7 +19,10 @@ pub mod evm; #[cfg(feature = "loader_halo2")] pub mod halo2; -impl Transcript for Blake2bRead> { +impl Transcript for Blake2bRead> +where + C::Scalar: FromUniformBytes<64>, +{ fn loader(&self) -> &NativeLoader { &native::LOADER } @@ -38,8 +42,9 @@ impl Transcript for Blake2bRead TranscriptRead - for Blake2bRead> +impl TranscriptRead for Blake2bRead> +where + C::Scalar: FromUniformBytes<64>, { fn read_scalar(&mut self) -> Result { halo2_proofs::transcript::TranscriptRead::read_scalar(self) @@ -52,7 +57,10 @@ impl TranscriptRead } } -impl Transcript for Blake2bWrite> { +impl Transcript for Blake2bWrite> +where + C::Scalar: FromUniformBytes<64>, +{ fn loader(&self) -> &NativeLoader { &native::LOADER } @@ -72,7 +80,10 @@ impl Transcript for Blake2bWrite TranscriptWrite for Blake2bWrite, C, Challenge255> { +impl TranscriptWrite for Blake2bWrite, C, Challenge255> +where + C::Scalar: FromUniformBytes<64>, +{ fn write_scalar(&mut self, scalar: C::Scalar) -> Result<(), Error> { halo2_proofs::transcript::TranscriptWrite::write_scalar(self, scalar) .map_err(|err| Error::Transcript(err.kind(), err.to_string())) diff --git a/snark-verifier/src/system/halo2/transcript/evm.rs b/snark-verifier/src/system/halo2/transcript/evm.rs index c71c9e79..5707fdfa 100644 --- a/snark-verifier/src/system/halo2/transcript/evm.rs +++ b/snark-verifier/src/system/halo2/transcript/evm.rs @@ -1,6 +1,7 @@ //! Transcript for verifier on EVM. use crate::halo2_proofs; +use crate::loader::evm::loader::MEM_PTR_START; use crate::{ loader::{ evm::{loader::Value, u256_to_fe, util::MemoryChunk, EcPoint, EvmLoader, Scalar, U256}, @@ -41,7 +42,7 @@ where /// u256 for `transcript_initial_state`. pub fn new(loader: &Rc) -> Self { let ptr = loader.allocate(0x20); - assert_eq!(ptr, 0); + assert_eq!(ptr, MEM_PTR_START); let mut buf = MemoryChunk::new(ptr); buf.extend(0x20); Self { loader: loader.clone(), stream: 0, buf, _marker: PhantomData } @@ -74,7 +75,7 @@ where } /// Does not allow the input to be a one-byte sequence, because the Transcript trait only supports writing scalars and elliptic curve points. - /// If the one-byte sequence [0x01] is a valid input to the transcript, the empty input [] will have the same transcript result as [0x01]. + /// If the one-byte sequence `[0x01]` is a valid input to the transcript, the empty input `[]` will have the same transcript result as `[0x01]`. fn squeeze_challenge(&mut self) -> Scalar { let len = if self.buf.len() == 0x20 { assert_eq!(self.loader.ptr(), self.buf.end()); @@ -116,7 +117,7 @@ where fn common_scalar(&mut self, scalar: &Scalar) -> Result<(), Error> { match scalar.value() { - Value::Constant(_) if self.buf.ptr() == 0 => { + Value::Constant(_) if self.buf.ptr() == MEM_PTR_START => { self.loader.copy_scalar(scalar, self.buf.ptr()); } Value::Memory(ptr) => { @@ -178,7 +179,7 @@ where .collect_vec(); let hash: [u8; 32] = Keccak256::digest(data).into(); self.buf = hash.to_vec(); - u256_to_fe(U256::from_big_endian(hash.as_slice())) + u256_to_fe(U256::from_be_bytes(hash)) } fn common_ec_point(&mut self, ec_point: &C) -> Result<(), Error> { @@ -274,7 +275,7 @@ where type Input = [u8; 32]; fn new(challenge_input: &[u8; 32]) -> Self { - ChallengeEvm(u256_to_fe(U256::from_big_endian(challenge_input))) + ChallengeEvm(u256_to_fe(U256::from_be_bytes(*challenge_input))) } fn get_scalar(&self) -> C::Scalar { diff --git a/snark-verifier/src/system/halo2/transcript/halo2.rs b/snark-verifier/src/system/halo2/transcript/halo2.rs index 86b1929c..8a0ce6d4 100644 --- a/snark-verifier/src/system/halo2/transcript/halo2.rs +++ b/snark-verifier/src/system/halo2/transcript/halo2.rs @@ -1,6 +1,7 @@ //! Transcript for verifier in [`halo2_proofs`] circuit. use crate::halo2_proofs; +use crate::util::arithmetic::FieldExt; use crate::{ loader::{ halo2::{EcPoint, EccInstructions, Halo2Loader, Scalar}, @@ -64,7 +65,10 @@ where { /// Initialize [`PoseidonTranscript`] given readable or writeable stream for /// verifying or proving with [`NativeLoader`]. - pub fn new(loader: &Rc>, stream: R) -> Self { + pub fn new(loader: &Rc>, stream: R) -> Self + where + C::Scalar: FieldExt, + { let buf = Poseidon::new::(loader); Self { loader: loader.clone(), stream, buf } } @@ -165,7 +169,10 @@ impl(stream: S) -> Self { + pub fn new(stream: S) -> Self + where + C::Scalar: FieldExt, + { Self { loader: NativeLoader, stream, @@ -375,6 +382,7 @@ impl where C: CurveAffine, + C::Scalar: FieldExt, R: Read, { fn init(reader: R) -> Self { @@ -409,6 +417,7 @@ impl where C: CurveAffine, + C::Scalar: FieldExt, W: Write, { fn init(writer: W) -> Self { @@ -423,12 +432,13 @@ where mod halo2_lib { use crate::halo2_curves::CurveAffineExt; use crate::system::halo2::transcript::halo2::NativeEncoding; - use halo2_ecc::{ecc::BaseFieldEccChip, fields::PrimeField}; + use halo2_base::utils::BigPrimeField; + use halo2_ecc::ecc::BaseFieldEccChip; impl<'chip, C: CurveAffineExt> NativeEncoding for BaseFieldEccChip<'chip, C> where - C::Scalar: PrimeField, - C::Base: PrimeField, + C::Scalar: BigPrimeField, + C::Base: BigPrimeField, { fn encode( &self, diff --git a/snark-verifier/src/util/arithmetic.rs b/snark-verifier/src/util/arithmetic.rs index 97962e32..3594be45 100644 --- a/snark-verifier/src/util/arithmetic.rs +++ b/snark-verifier/src/util/arithmetic.rs @@ -4,15 +4,15 @@ use crate::halo2_curves; use crate::util::Itertools; pub use halo2_curves::{ group::{ - ff::{BatchInvert, Field, PrimeField}, + ff::{BatchInvert, Field, FromUniformBytes, PrimeField}, prime::PrimeCurveAffine, Curve, Group, GroupEncoding, }, - pairing::MillerLoopResult, - Coordinates, CurveAffine, CurveExt, FieldExt, + Coordinates, CurveAffine, CurveExt, }; use num_bigint::BigUint; use num_traits::One; +pub use pairing::MillerLoopResult; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, @@ -21,10 +21,15 @@ use std::{ ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, }; -/// [`halo2_curves::pairing::MultiMillerLoop`] with [`std::fmt::Debug`]. -pub trait MultiMillerLoop: halo2_curves::pairing::MultiMillerLoop + Debug {} +/// [pairing::MultiMillerLoop] with [`std::fmt::Debug`]. +pub trait MultiMillerLoop: pairing::MultiMillerLoop + Debug {} -impl MultiMillerLoop for M {} +impl MultiMillerLoop for M {} + +/// Trait for fields that can implement Poseidon hash +pub trait FieldExt: PrimeField + FromUniformBytes<64> + Ord {} + +impl + Ord> FieldExt for F {} /// Operations that could be done with field elements. pub trait FieldOps: @@ -54,7 +59,7 @@ pub fn batch_invert_and_mul(values: &mut [F], coeff: &F) { } let products = values .iter() - .scan(F::one(), |acc, value| { + .scan(F::ONE, |acc, value| { *acc *= value; Some(*acc) }) @@ -65,7 +70,7 @@ pub fn batch_invert_and_mul(values: &mut [F], coeff: &F) { * coeff; for (value, product) in - values.iter_mut().rev().zip(products.into_iter().rev().skip(1).chain(Some(F::one()))) + values.iter_mut().rev().zip(products.into_iter().rev().skip(1).chain(Some(F::ONE))) { let mut inv = all_product_inv * product; mem::swap(value, &mut inv); @@ -75,7 +80,7 @@ pub fn batch_invert_and_mul(values: &mut [F], coeff: &F) { /// Batch invert [`PrimeField`] elements. pub fn batch_invert(values: &mut [F]) { - batch_invert_and_mul(values, &F::one()) + batch_invert_and_mul(values, &F::ONE) } /// Root of unity of 2^k-sized multiplicative subgroup of [`PrimeField`] by @@ -88,7 +93,7 @@ pub fn batch_invert(values: &mut [F]) { pub fn root_of_unity(k: usize) -> F { assert!(k <= F::S as usize); - iter::successors(Some(F::root_of_unity()), |acc| Some(acc.square())) + iter::successors(Some(F::ROOT_OF_UNITY), |acc| Some(acc.square())) .take(F::S as usize - k + 1) .last() .unwrap() @@ -151,7 +156,7 @@ impl Domain { match rotation.0.cmp(&0) { Ordering::Equal => scalar, Ordering::Greater => scalar * self.gen.pow_vartime([rotation.0 as u64]), - Ordering::Less => scalar * self.gen_inv.pow_vartime([(-(rotation.0 as i64)) as u64]), + Ordering::Less => scalar * self.gen_inv.pow_vartime([(-rotation.0) as u64]), } } } @@ -230,7 +235,7 @@ impl Fraction { /// Modulus of a [`PrimeField`] pub fn modulus() -> BigUint { - fe_to_big(-F::one()) + 1usize + fe_to_big(-F::ONE) + 1usize } /// Convert a [`BigUint`] into a [`PrimeField`] . @@ -286,7 +291,7 @@ pub fn fe_to_limbs(scalar: F) -> impl Iterator { - iter::successors(Some(F::one()), move |power| Some(scalar * power)) + iter::successors(Some(F::ONE), move |power| Some(scalar * power)) } /// Compute inner product of 2 slice of [`Field`]. diff --git a/snark-verifier/src/util/hash.rs b/snark-verifier/src/util/hash.rs index a8fe168c..a14eec23 100644 --- a/snark-verifier/src/util/hash.rs +++ b/snark-verifier/src/util/hash.rs @@ -1,10 +1,10 @@ //! Hash algorithms. -#[cfg(feature = "loader_halo2")] mod poseidon; +pub use crate::util::hash::poseidon::Poseidon; #[cfg(feature = "loader_halo2")] -pub use crate::util::hash::poseidon::{OptimizedPoseidonSpec, Poseidon}; +pub(crate) use halo2_base::poseidon::hasher::spec::OptimizedPoseidonSpec; #[cfg(feature = "loader_evm")] pub use sha3::{Digest, Keccak256}; diff --git a/snark-verifier/src/util/hash/poseidon.rs b/snark-verifier/src/util/hash/poseidon.rs index 1ff06ab9..740f4c72 100644 --- a/snark-verifier/src/util/hash/poseidon.rs +++ b/snark-verifier/src/util/hash/poseidon.rs @@ -1,339 +1,35 @@ -#![allow(clippy::needless_range_loop)] // for clarity of matrix operations +//! Trait based implementation of Poseidon permutation + +use halo2_base::poseidon::hasher::{mds::SparseMDSMatrix, spec::OptimizedPoseidonSpec}; + use crate::{ loader::{LoadedScalar, ScalarLoader}, - util::{arithmetic::FieldExt, Itertools}, + util::{ + arithmetic::{FieldExt, PrimeField}, + Itertools, + }, }; -use poseidon_circuit::poseidon::primitives::Spec as PoseidonSpec; // trait use std::{iter, marker::PhantomData, mem}; #[cfg(test)] mod tests; -// struct so we can use PoseidonSpec trait to generate round constants and MDS matrix -#[derive(Debug)] -pub struct Poseidon128Pow5Gen< - F: FieldExt, - const T: usize, - const RATE: usize, - const R_F: usize, - const R_P: usize, - const SECURE_MDS: usize, -> { - _marker: PhantomData, -} - -impl< - F: FieldExt, - const T: usize, - const RATE: usize, - const R_F: usize, - const R_P: usize, - const SECURE_MDS: usize, - > PoseidonSpec for Poseidon128Pow5Gen -{ - fn full_rounds() -> usize { - R_F - } - - fn partial_rounds() -> usize { - R_P - } - - fn sbox(val: F) -> F { - val.pow_vartime([5]) - } - - // see "Avoiding insecure matrices" in Section 2.3 of https://eprint.iacr.org/2019/458.pdf - // most Specs used in practice have SECURE_MDS = 0 - fn secure_mds() -> usize { - SECURE_MDS - } -} - -// We use the optimized Poseidon implementation described in Supplementary Material Section B of https://eprint.iacr.org/2019/458.pdf -// This involves some further computation of optimized constants and sparse MDS matrices beyond what the Scroll PoseidonSpec generates -// The implementation below is adapted from https://github.com/privacy-scaling-explorations/poseidon - -/// `OptimizedPoseidonSpec` holds construction parameters as well as constants that are used in -/// permutation step. -#[derive(Debug, Clone)] -pub struct OptimizedPoseidonSpec { - pub(crate) r_f: usize, - pub(crate) mds_matrices: MDSMatrices, - pub(crate) constants: OptimizedConstants, -} - -/// `OptimizedConstants` has round constants that are added each round. While -/// full rounds has T sized constants there is a single constant for each -/// partial round -#[derive(Debug, Clone)] -pub struct OptimizedConstants { - pub(crate) start: Vec<[F; T]>, - pub(crate) partial: Vec, - pub(crate) end: Vec<[F; T]>, -} - -/// The type used to hold the MDS matrix -pub(crate) type Mds = [[F; T]; T]; - -/// `MDSMatrices` holds the MDS matrix as well as transition matrix which is -/// also called `pre_sparse_mds` and sparse matrices that enables us to reduce -/// number of multiplications in apply MDS step -#[derive(Debug, Clone)] -pub struct MDSMatrices { - pub(crate) mds: MDSMatrix, - pub(crate) pre_sparse_mds: MDSMatrix, - pub(crate) sparse_matrices: Vec>, -} - -/// `SparseMDSMatrix` are in `[row], [hat | identity]` form and used in linear -/// layer of partial rounds instead of the original MDS -#[derive(Debug, Clone)] -pub struct SparseMDSMatrix { - pub(crate) row: [F; T], - pub(crate) col_hat: [F; RATE], -} - -/// `MDSMatrix` is applied to `State` to achive linear layer of Poseidon -#[derive(Clone, Debug)] -pub struct MDSMatrix(pub(crate) Mds); - -impl MDSMatrix { - pub(crate) fn mul_vector(&self, v: &[F; T]) -> [F; T] { - let mut res = [F::zero(); T]; - for i in 0..T { - for j in 0..T { - res[i] += self.0[i][j] * v[j]; - } - } - res - } - - fn identity() -> Mds { - let mut mds = [[F::zero(); T]; T]; - for i in 0..T { - mds[i][i] = F::one(); - } - mds - } - - /// Multiplies two MDS matrices. Used in sparse matrix calculations - fn mul(&self, other: &Self) -> Self { - let mut res = [[F::zero(); T]; T]; - for i in 0..T { - for j in 0..T { - for k in 0..T { - res[i][j] += self.0[i][k] * other.0[k][j]; - } - } - } - Self(res) - } - - fn transpose(&self) -> Self { - let mut res = [[F::zero(); T]; T]; - for i in 0..T { - for j in 0..T { - res[i][j] = self.0[j][i]; - } - } - Self(res) - } - - fn determinant(m: [[F; N]; N]) -> F { - let mut res = F::one(); - let mut m = m; - for i in 0..N { - let mut pivot = i; - while m[pivot][i] == F::zero() { - pivot += 1; - assert!(pivot < N, "matrix is not invertible"); - } - if pivot != i { - res = -res; - m.swap(pivot, i); - } - res *= m[i][i]; - let inv = m[i][i].invert().unwrap(); - for j in i + 1..N { - let factor = m[j][i] * inv; - for k in i + 1..N { - m[j][k] -= m[i][k] * factor; - } - } - } - res - } - - /// See Section B in Supplementary Material https://eprint.iacr.org/2019/458.pdf - /// Factorises an MDS matrix `M` into `M'` and `M''` where `M = M' * M''`. - /// Resulted `M''` matrices are the sparse ones while `M'` will contribute - /// to the accumulator of the process - fn factorise(&self) -> (Self, SparseMDSMatrix) { - assert_eq!(RATE + 1, T); - // Given `(t-1 * t-1)` MDS matrix called `hat` constructs the `t * t` matrix in - // form `[[1 | 0], [0 | m]]`, ie `hat` is the right bottom sub-matrix - let prime = |hat: Mds| -> Self { - let mut prime = Self::identity(); - for (prime_row, hat_row) in prime.iter_mut().skip(1).zip(hat.iter()) { - for (el_prime, el_hat) in prime_row.iter_mut().skip(1).zip(hat_row.iter()) { - *el_prime = *el_hat; - } - } - Self(prime) - }; - - // Given `(t-1)` sized `w_hat` vector constructs the matrix in form - // `[[m_0_0 | m_0_i], [w_hat | identity]]` - let prime_prime = |w_hat: [F; RATE]| -> Mds { - let mut prime_prime = Self::identity(); - prime_prime[0] = self.0[0]; - for (row, w) in prime_prime.iter_mut().skip(1).zip(w_hat.iter()) { - row[0] = *w - } - prime_prime - }; - - let w = self.0.iter().skip(1).map(|row| row[0]).collect::>(); - // m_hat is the `(t-1 * t-1)` right bottom sub-matrix of m := self.0 - let mut m_hat = [[F::zero(); RATE]; RATE]; - for i in 0..RATE { - for j in 0..RATE { - m_hat[i][j] = self.0[i + 1][j + 1]; - } - } - // w_hat = m_hat^{-1} * w, where m_hat^{-1} is matrix inverse and * is matrix mult - // we avoid computing m_hat^{-1} explicitly by using Cramer's rule: https://en.wikipedia.org/wiki/Cramer%27s_rule - let mut w_hat = [F::zero(); RATE]; - let det = Self::determinant(m_hat); - let det_inv = Option::::from(det.invert()).expect("matrix is not invertible"); - for j in 0..RATE { - let mut m_hat_j = m_hat; - for i in 0..RATE { - m_hat_j[i][j] = w[i]; - } - w_hat[j] = Self::determinant(m_hat_j) * det_inv; - } - let m_prime = prime(m_hat); - let m_prime_prime = prime_prime(w_hat); - // row = first row of m_prime_prime.transpose() = first column of m_prime_prime - let row: [F; T] = - m_prime_prime.iter().map(|row| row[0]).collect::>().try_into().unwrap(); - // col_hat = first column of m_prime_prime.transpose() without first element = first row of m_prime_prime without first element - let col_hat: [F; RATE] = m_prime_prime[0][1..].try_into().unwrap(); - (m_prime, SparseMDSMatrix { row, col_hat }) - } -} - -impl OptimizedPoseidonSpec { - /// Generate new spec with specific number of full and partial rounds. `SECURE_MDS` is usually 0, but may need to be specified because insecure matrices may sometimes be generated - pub fn new() -> Self { - let (round_constants, mds, mds_inv) = - Poseidon128Pow5Gen::::constants(); - let mds = MDSMatrix(mds); - let inverse_mds = MDSMatrix(mds_inv); - - let constants = - Self::calculate_optimized_constants(R_F, R_P, round_constants, &inverse_mds); - let (sparse_matrices, pre_sparse_mds) = Self::calculate_sparse_matrices(R_P, &mds); - - Self { - r_f: R_F, - constants, - mds_matrices: MDSMatrices { mds, sparse_matrices, pre_sparse_mds }, - } - } - - fn calculate_optimized_constants( - r_f: usize, - r_p: usize, - constants: Vec<[F; T]>, - inverse_mds: &MDSMatrix, - ) -> OptimizedConstants { - let (number_of_rounds, r_f_half) = (r_f + r_p, r_f / 2); - assert_eq!(constants.len(), number_of_rounds); - - // Calculate optimized constants for first half of the full rounds - let mut constants_start: Vec<[F; T]> = vec![[F::zero(); T]; r_f_half]; - constants_start[0] = constants[0]; - for (optimized, constants) in - constants_start.iter_mut().skip(1).zip(constants.iter().skip(1)) - { - *optimized = inverse_mds.mul_vector(constants); - } - - // Calculate constants for partial rounds - let mut acc = constants[r_f_half + r_p]; - let mut constants_partial = vec![F::zero(); r_p]; - for (optimized, constants) in constants_partial - .iter_mut() - .rev() - .zip(constants.iter().skip(r_f_half).rev().skip(r_f_half)) - { - let mut tmp = inverse_mds.mul_vector(&acc); - *optimized = tmp[0]; - - tmp[0] = F::zero(); - for ((acc, tmp), constant) in acc.iter_mut().zip(tmp.into_iter()).zip(constants.iter()) - { - *acc = tmp + constant - } - } - constants_start.push(inverse_mds.mul_vector(&acc)); - - // Calculate optimized constants for ending half of the full rounds - let mut constants_end: Vec<[F; T]> = vec![[F::zero(); T]; r_f_half - 1]; - for (optimized, constants) in - constants_end.iter_mut().zip(constants.iter().skip(r_f_half + r_p + 1)) - { - *optimized = inverse_mds.mul_vector(constants); - } - - OptimizedConstants { - start: constants_start, - partial: constants_partial, - end: constants_end, - } - } - - fn calculate_sparse_matrices( - r_p: usize, - mds: &MDSMatrix, - ) -> (Vec>, MDSMatrix) { - let mds = mds.transpose(); - let mut acc = mds.clone(); - let mut sparse_matrices = (0..r_p) - .map(|_| { - let (m_prime, m_prime_prime) = acc.factorise(); - acc = mds.mul(&m_prime); - m_prime_prime - }) - .collect::>>(); - - sparse_matrices.reverse(); - (sparse_matrices, acc.transpose()) - } -} - -// ================ END OF CONSTRUCTION OF POSEIDON SPEC ==================== - -// now we get to actual trait based implementation of Poseidon permutation // this works for any loader, where the two loaders used are NativeLoader (native rust) and Halo2Loader (ZK circuit) #[derive(Clone, Debug)] -struct State { +struct State { inner: [L; T], _marker: PhantomData, } // the transcript hash implementation is the one suggested in the original paper https://eprint.iacr.org/2019/458.pdf // another reference implementation is https://github.com/privacy-scaling-explorations/halo2wrong/tree/master/transcript/src -impl, const T: usize, const RATE: usize> State { +impl, const T: usize, const RATE: usize> State { fn new(inner: [L; T]) -> Self { Self { inner, _marker: PhantomData } } fn default(loader: &L::Loader) -> Self { - let mut default_state = [F::zero(); T]; + let mut default_state = [F::ZERO; T]; // from Section 4.2 of https://eprint.iacr.org/2019/458.pdf // • Variable-Input-Length Hashing. The capacity value is 2^64 + (o−1) where o the output length. // for our transcript use cases, o = 1 @@ -376,8 +72,8 @@ impl, const T: usize, const RATE: usize> State, const T: usize, const RATE: usize> State) { self.inner = iter::once( self.loader() - .sum_with_coeff(&mds.row.iter().cloned().zip(self.inner.iter()).collect_vec()), + .sum_with_coeff(&mds.row().iter().cloned().zip(self.inner.iter()).collect_vec()), ) - .chain(mds.col_hat.iter().zip(self.inner.iter().skip(1)).map(|(coeff, state)| { - self.loader().sum_with_coeff(&[(*coeff, &self.inner[0]), (F::one(), state)]) + .chain(mds.col_hat().iter().zip(self.inner.iter().skip(1)).map(|(coeff, state)| { + self.loader().sum_with_coeff(&[(*coeff, &self.inner[0]), (F::ONE, state)]) })) .collect_vec() .try_into() @@ -411,19 +107,22 @@ impl, const T: usize, const RATE: usize> State { +pub struct Poseidon { spec: OptimizedPoseidonSpec, default_state: State, state: State, buf: Vec, } -impl, const T: usize, const RATE: usize> Poseidon { +impl, const T: usize, const RATE: usize> Poseidon { /// Initialize a poseidon hasher. /// Generates a new spec with specific number of full and partial rounds. `SECURE_MDS` is usually 0, but may need to be specified because insecure matrices may sometimes be generated pub fn new( loader: &L::Loader, - ) -> Self { + ) -> Self + where + F: FieldExt, + { let default_state = State::default(loader); Self { spec: OptimizedPoseidonSpec::new::(), @@ -467,35 +166,35 @@ impl, const T: usize, const RATE: usize> Poseido } fn permutation(&mut self, inputs: &[L]) { - let r_f = self.spec.r_f / 2; - let mds = self.spec.mds_matrices.mds.0; - let pre_sparse_mds = self.spec.mds_matrices.pre_sparse_mds.0; - let sparse_matrices = &self.spec.mds_matrices.sparse_matrices; + let r_f = self.spec.r_f() / 2; + let mds = self.spec.mds_matrices().mds().as_ref(); + let pre_sparse_mds = self.spec.mds_matrices().pre_sparse_mds().as_ref(); + let sparse_matrices = &self.spec.mds_matrices().sparse_matrices(); // First half of the full rounds - let constants = &self.spec.constants.start; + let constants = self.spec.constants().start(); self.state.absorb_with_pre_constants(inputs, &constants[0]); for constants in constants.iter().skip(1).take(r_f - 1) { self.state.sbox_full(constants); - self.state.apply_mds(&mds); + self.state.apply_mds(mds); } self.state.sbox_full(constants.last().unwrap()); - self.state.apply_mds(&pre_sparse_mds); + self.state.apply_mds(pre_sparse_mds); // Partial rounds - let constants = &self.spec.constants.partial; + let constants = self.spec.constants().partial(); for (constant, sparse_mds) in constants.iter().zip(sparse_matrices.iter()) { self.state.sbox_part(constant); self.state.apply_sparse_mds(sparse_mds); } // Second half of the full rounds - let constants = &self.spec.constants.end; + let constants = self.spec.constants().end(); for constants in constants.iter() { self.state.sbox_full(constants); - self.state.apply_mds(&mds); + self.state.apply_mds(mds); } - self.state.sbox_full(&[F::zero(); T]); - self.state.apply_mds(&mds); + self.state.sbox_full(&[F::ZERO; T]); + self.state.apply_mds(mds); } } diff --git a/snark-verifier/src/util/hash/poseidon/tests.rs b/snark-verifier/src/util/hash/poseidon/tests.rs index cf4712bc..507b1d7c 100644 --- a/snark-verifier/src/util/hash/poseidon/tests.rs +++ b/snark-verifier/src/util/hash/poseidon/tests.rs @@ -24,7 +24,7 @@ fn test_mds() { "11597556804922396090267472882856054602429588299176362916247939723151043581408", ], ]; - for (row1, row2) in mds.iter().zip_eq(spec.mds_matrices.mds.0.iter()) { + for (row1, row2) in mds.iter().zip_eq(spec.mds_matrices().mds().as_ref().iter()) { for (e1, e2) in row1.iter().zip_eq(row2.iter()) { assert_eq!(Fr::from_str_vartime(e1).unwrap(), *e2); } @@ -47,7 +47,7 @@ fn test_poseidon_against_test_vectors() { hasher.state = State::new(state.try_into().unwrap()); hasher.permutation(&[(); RATE].map(|_| Fr::zero())); // avoid padding let state_0 = hasher.state.inner; - let expected = vec![ + let expected = [ "7853200120776062878684798364095072458815029376092732009249414926327459813530", "7142104613055408817911962100316808866448378443474503659992478482890339429929", "6549537674122432311777789598043107870002137484850126429160507761192163713804", @@ -71,7 +71,7 @@ fn test_poseidon_against_test_vectors() { hasher.state = State::new(state.try_into().unwrap()); hasher.permutation(&[(); RATE].map(|_| Fr::zero())); let state_0 = hasher.state.inner; - let expected = vec![ + let expected = [ "18821383157269793795438455681495246036402687001665670618754263018637548127333", "7817711165059374331357136443537800893307845083525445872661165200086166013245", "16733335996448830230979566039396561240864200624113062088822991822580465420551", diff --git a/snark-verifier/src/util/msm.rs b/snark-verifier/src/util/msm.rs index 8d18cdf8..fef53e59 100644 --- a/snark-verifier/src/util/msm.rs +++ b/snark-verifier/src/util/msm.rs @@ -71,7 +71,7 @@ where let gen = gen.map(|gen| self.bases.first().unwrap().loader().ec_point_load_const(&gen)); let pairs = iter::empty() .chain(self.constant.as_ref().map(|constant| (constant, gen.as_ref().unwrap()))) - .chain(self.scalars.iter().zip(self.bases.into_iter())) + .chain(self.scalars.iter().zip(self.bases)) .collect_vec(); L::multi_scalar_multiplication(&pairs) } diff --git a/snark-verifier/src/util/poly.rs b/snark-verifier/src/util/poly.rs index 17a065f9..86271af4 100644 --- a/snark-verifier/src/util/poly.rs +++ b/snark-verifier/src/util/poly.rs @@ -55,7 +55,7 @@ impl Polynomial { /// Returns evaluation at given `x`. pub fn evaluate(&self, x: F) -> F { let evaluate_serial = - |coeffs: &[F]| coeffs.iter().rev().fold(F::zero(), |acc, coeff| acc * x + coeff); + |coeffs: &[F]| coeffs.iter().rev().fold(F::ZERO, |acc, coeff| acc * x + coeff); #[cfg(feature = "parallel")] { @@ -68,17 +68,15 @@ impl Polynomial { } let chunk_size = Integer::div_ceil(&self.len(), &num_threads); - let mut results = vec![F::zero(); num_threads]; + let mut results = vec![F::ZERO; num_threads]; parallelize_iter( - results.iter_mut().zip(self.0.chunks(chunk_size)).zip(powers(x.pow_vartime(&[ - chunk_size as u64, - 0, - 0, - 0, - ]))), + results + .iter_mut() + .zip(self.0.chunks(chunk_size)) + .zip(powers(x.pow_vartime([chunk_size as u64]))), |((result, coeffs), scalar)| *result = evaluate_serial(coeffs) * scalar, ); - results.iter().fold(F::zero(), |acc, result| acc + result) + results.iter().fold(F::ZERO, |acc, result| acc + result) } #[cfg(not(feature = "parallel"))] evaluate_serial(&self.0) @@ -133,10 +131,10 @@ impl Mul for Polynomial { type Output = Polynomial; fn mul(mut self, rhs: F) -> Polynomial { - if rhs == F::zero() { - return Polynomial::new(vec![F::zero(); self.len()]); + if rhs == F::ZERO { + return Polynomial::new(vec![F::ZERO; self.len()]); } - if rhs == F::one() { + if rhs == F::ONE { return self; } parallelize(&mut self.0, |(lhs, _)| { diff --git a/snark-verifier/src/verifier/plonk.rs b/snark-verifier/src/verifier/plonk.rs index d5937ab8..9c910400 100644 --- a/snark-verifier/src/verifier/plonk.rs +++ b/snark-verifier/src/verifier/plonk.rs @@ -15,7 +15,10 @@ use crate::{ AccumulationDecider, AccumulationScheme, AccumulatorEncoding, PolynomialCommitmentScheme, Query, }, - util::{arithmetic::CurveAffine, transcript::TranscriptRead}, + util::{ + arithmetic::{CurveAffine, Rotation}, + transcript::TranscriptRead, + }, verifier::{plonk::protocol::CommonPolynomialEvaluation, SnarkVerifier}, Error, }; @@ -62,8 +65,12 @@ where proof: &Self::Proof, ) -> Result { let common_poly_eval = { - let mut common_poly_eval = - CommonPolynomialEvaluation::new(&protocol.domain, protocol.langranges(), &proof.z); + let mut common_poly_eval = CommonPolynomialEvaluation::new( + &protocol.domain, + protocol.langranges(), + &proof.z, + &protocol.domain_as_witness, + ); L::batch_invert(common_poly_eval.denoms()); common_poly_eval.evaluate(); @@ -140,7 +147,7 @@ where L: Loader, AS: AccumulationScheme + PolynomialCommitmentScheme - + CostEstimation>>, + + CostEstimation>>, { type Input = PlonkProtocol; @@ -168,7 +175,7 @@ where L: Loader, AS: AccumulationScheme + PolynomialCommitmentScheme - + CostEstimation>>, + + CostEstimation>>, { type Input = PlonkProtocol; diff --git a/snark-verifier/src/verifier/plonk/proof.rs b/snark-verifier/src/verifier/plonk/proof.rs index 7adba7ac..459027ba 100644 --- a/snark-verifier/src/verifier/plonk/proof.rs +++ b/snark-verifier/src/verifier/plonk/proof.rs @@ -13,7 +13,10 @@ use crate::{ }, Error, }; -use std::{collections::HashMap, iter}; +use std::{ + collections::{BTreeMap, HashMap}, + iter, +}; /// Proof of PLONK with [`PolynomialCommitmentScheme`] that has /// [`AccumulationScheme`]. @@ -153,26 +156,42 @@ where } /// Empty queries - pub fn empty_queries(protocol: &PlonkProtocol) -> Vec> { - protocol - .queries - .iter() - .map(|query| { - let shift = protocol.domain.rotate_scalar(C::Scalar::one(), query.rotation); - pcs::Query::new(query.poly, shift) - }) - .collect() + pub fn empty_queries(protocol: &PlonkProtocol) -> Vec> { + // `preprocessed` should always be non-empty, unless the circuit has no constraints or constants + protocol.queries.iter().map(|query| pcs::Query::new(query.poly, query.rotation)).collect() } pub(super) fn queries( &self, protocol: &PlonkProtocol, mut evaluations: HashMap, - ) -> Vec> { + ) -> Vec> { + if protocol.queries.is_empty() { + return vec![]; + } + let loader = evaluations[&protocol.queries[0]].loader(); + let rotations = + protocol.queries.iter().map(|query| query.rotation).sorted().dedup().collect_vec(); + let loaded_shifts = if let Some(domain) = protocol.domain_as_witness.as_ref() { + // the `rotation`s are still constants, it is only generator `omega` that might be witness + BTreeMap::from_iter( + rotations.into_iter().map(|rotation| (rotation, domain.rotate_one(rotation))), + ) + } else { + BTreeMap::from_iter(rotations.into_iter().map(|rotation| { + ( + rotation, + loader.load_const(&protocol.domain.rotate_scalar(C::Scalar::ONE, rotation)), + ) + })) + }; Self::empty_queries(protocol) .into_iter() .zip(protocol.queries.iter().map(|query| evaluations.remove(query).unwrap())) - .map(|(query, eval)| query.with_evaluation(eval)) + .map(|(query, eval)| { + let shift = loaded_shifts[&query.shift].clone(); + query.with_evaluation(shift, eval) + }) .collect() } diff --git a/snark-verifier/src/verifier/plonk/protocol.rs b/snark-verifier/src/verifier/plonk/protocol.rs index a3a84346..9260e572 100644 --- a/snark-verifier/src/verifier/plonk/protocol.rs +++ b/snark-verifier/src/verifier/plonk/protocol.rs @@ -1,7 +1,7 @@ use crate::{ loader::{native::NativeLoader, LoadedScalar, Loader}, util::{ - arithmetic::{CurveAffine, Domain, Field, Fraction, Rotation}, + arithmetic::{CurveAffine, Domain, Field, Fraction, PrimeField, Rotation}, Itertools, }, }; @@ -9,13 +9,46 @@ use num_integer::Integer; use num_traits::One; use serde::{Deserialize, Serialize}; use std::{ - cmp::max, + cmp::{max, Ordering}, collections::{BTreeMap, BTreeSet}, fmt::Debug, iter::{self, Sum}, ops::{Add, Mul, Neg, Sub}, }; +/// Domain parameters to be optionally loaded as witnesses +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DomainAsWitness +where + C: CurveAffine, + L: Loader, +{ + /// 2k is the number of rows in the domain + pub k: L::LoadedScalar, + /// n = 2k is the number of rows in the domain + pub n: L::LoadedScalar, + /// Generator of the domain + pub gen: L::LoadedScalar, + /// Inverse generator of the domain + pub gen_inv: L::LoadedScalar, +} + +impl DomainAsWitness +where + C: CurveAffine, + L: Loader, +{ + /// Rotate `F::one()` to given `rotation`. + pub fn rotate_one(&self, rotation: Rotation) -> L::LoadedScalar { + let loader = self.gen.loader(); + match rotation.0.cmp(&0) { + Ordering::Equal => loader.load_one(), + Ordering::Greater => self.gen.pow_const(rotation.0 as u64), + Ordering::Less => self.gen_inv.pow_const(-rotation.0 as u64), + } + } +} + /// Protocol specifying configuration of a PLONK. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PlonkProtocol @@ -29,6 +62,14 @@ where ))] /// Working domain. pub domain: Domain, + + #[serde(bound( + serialize = "L::LoadedScalar: Serialize", + deserialize = "L::LoadedScalar: Deserialize<'de>" + ))] + /// Optional: load `domain.n` and `domain.gen` as a witness + pub domain_as_witness: Option>, + #[serde(bound( serialize = "L::LoadedEcPoint: Serialize", deserialize = "L::LoadedEcPoint: Deserialize<'de>" @@ -115,6 +156,7 @@ where .map(|transcript_initial_state| loader.load_const(transcript_initial_state)); PlonkProtocol { domain: self.domain.clone(), + domain_as_witness: None, preprocessed, num_instance: self.num_instance.clone(), num_witness: self.num_witness.clone(), @@ -133,12 +175,18 @@ where #[cfg(feature = "loader_halo2")] mod halo2 { use crate::{ - loader::halo2::{EccInstructions, Halo2Loader}, + loader::{ + halo2::{EccInstructions, Halo2Loader}, + LoadedScalar, ScalarLoader, + }, util::arithmetic::CurveAffine, verifier::plonk::PlonkProtocol, }; + use halo2_base::utils::bit_length; use std::rc::Rc; + use super::{DomainAsWitness, PrimeField}; + impl PlonkProtocol where C: CurveAffine, @@ -149,7 +197,23 @@ mod halo2 { pub fn loaded_preprocessed_as_witness>( &self, loader: &Rc>, + load_k_as_witness: bool, ) -> PlonkProtocol>> { + let domain_as_witness = load_k_as_witness.then(|| { + let k = loader.assign_scalar(C::Scalar::from(self.domain.k as u64)); + // n = 2^k + let two = loader.load_const(&C::Scalar::from(2)); + let n = two.pow_var(&k, bit_length(C::Scalar::S as u64) + 1); + // gen = omega = ROOT_OF_UNITY ^ {2^{S - k}}, where ROOT_OF_UNITY is primitive 2^S root of unity + // this makes omega a 2^k root of unity + let root_of_unity = loader.load_const(&C::Scalar::ROOT_OF_UNITY); + let s = loader.load_const(&C::Scalar::from(C::Scalar::S as u64)); + let exp = two.pow_var(&(s - &k), bit_length(C::Scalar::S as u64)); // if S - k < 0, constraint on max bits will fail + let gen = root_of_unity.pow_var(&exp, C::Scalar::S as usize); // 2^{S - k} < 2^S for k > 0 + let gen_inv = gen.invert().expect("subgroup generation is invertible"); + DomainAsWitness { k, n, gen, gen_inv } + }); + let preprocessed = self .preprocessed .iter() @@ -161,6 +225,7 @@ mod halo2 { .map(|transcript_initial_state| loader.assign_scalar(*transcript_initial_state)); PlonkProtocol { domain: self.domain.clone(), + domain_as_witness, preprocessed, num_instance: self.num_instance.clone(), num_witness: self.num_witness.clone(), @@ -201,26 +266,39 @@ where C: CurveAffine, L: Loader, { + // if `n_as_witness` is Some, then we assume `n_as_witness` has value equal to `domain.n` (i.e., number of rows in the circuit) + // and is loaded as a witness instead of a constant. + // The generator of `domain` also depends on `n`. pub fn new( domain: &Domain, - langranges: impl IntoIterator, + lagranges: impl IntoIterator, z: &L::LoadedScalar, + domain_as_witness: &Option>, ) -> Self { let loader = z.loader(); - let zn = z.pow_const(domain.n as u64); - let langranges = langranges.into_iter().sorted().dedup().collect_vec(); - + let lagranges = lagranges.into_iter().sorted().dedup().collect_vec(); let one = loader.load_one(); + + let (zn, n_inv, omegas) = if let Some(domain) = domain_as_witness.as_ref() { + let zn = z.pow_var(&domain.n, C::Scalar::S as usize + 1); + let n_inv = domain.n.invert().expect("n is not zero"); + let omegas = lagranges.iter().map(|&i| domain.rotate_one(Rotation(i))).collect_vec(); + (zn, n_inv, omegas) + } else { + let zn = z.pow_const(domain.n as u64); + let n_inv = loader.load_const(&domain.n_inv); + let omegas = lagranges + .iter() + .map(|&i| loader.load_const(&domain.rotate_scalar(C::Scalar::ONE, Rotation(i)))) + .collect_vec(); + (zn, n_inv, omegas) + }; + let zn_minus_one = zn.clone() - &one; let zn_minus_one_inv = Fraction::one_over(zn_minus_one.clone()); - let n_inv = loader.load_const(&domain.n_inv); let numer = zn_minus_one.clone() * &n_inv; - let omegas = langranges - .iter() - .map(|&i| loader.load_const(&domain.rotate_scalar(C::Scalar::one(), Rotation(i)))) - .collect_vec(); let lagrange_evals = omegas .iter() .map(|omega| Fraction::new(numer.clone() * omega, z.clone() - omega)) @@ -231,7 +309,7 @@ where zn_minus_one, zn_minus_one_inv, identity: z.clone(), - lagrange: langranges.into_iter().zip(lagrange_evals).collect(), + lagrange: lagranges.into_iter().zip(lagrange_evals).collect(), } } @@ -478,7 +556,7 @@ impl Sum for Expression { impl One for Expression { fn one() -> Self { - Expression::Constant(F::one()) + Expression::Constant(F::ONE) } }