├── .github ├── CODEOWNERS ├── PULL_REQUEST_TEMPLATE.md ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benchmark_results ├── gkr_round_sumcheck_prove.jpg ├── gkr_round_sumcheck_verify.jpg ├── ml_sumcheck_prove.jpg └── ml_sumcheck_verify.jpg ├── src ├── error.rs ├── gkr_round_sumcheck │ ├── data_structures.rs │ ├── mod.rs │ └── test.rs ├── lib.rs ├── ml_sumcheck │ ├── data_structures.rs │ ├── mod.rs │ ├── protocol │ │ ├── mod.rs │ │ ├── prover.rs │ │ └── verifier.rs │ └── test.rs └── rng.rs └── sumcheck-benches ├── Cargo.toml └── benches ├── gkr_round_sumcheck_bench.rs └── ml_sumcheck_bench.rs /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @arkworks-rs/maintainers 2 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | ## Description 8 | 9 | 12 | 13 | closes: #XXXX 14 | 15 | --- 16 | 17 | Before we can merge this PR, please make sure that all the following items have been 18 | checked off. If any of the checklist items are not applicable, please leave them but 19 | write a little note why. 20 | 21 | - [ ] Targeted PR against correct branch (master) 22 | - [ ] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work. 23 | - [ ] Wrote unit tests 24 | - [ ] Updated relevant documentation in the code 25 | - [ ] Added a relevant changelog entry to the `Pending` section in `CHANGELOG.md` 26 | - [ ] Re-reviewed `Files changed` in the Github PR explorer -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | ignore: 9 | - dependency-name: hashbrown 10 | versions: 11 | - 0.11.0 12 | - 0.11.1 13 | - 0.11.2 14 | - dependency-name: rand 15 | versions: 16 | - 0.8.3 17 | - dependency-name: rand_core 18 | versions: 19 | - 0.6.1 20 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | env: 8 | RUST_BACKTRACE: 1 9 | 10 | jobs: 11 | style: 12 | name: Check Style 13 | runs-on: ubuntu-latest 14 | steps: 15 | 16 | - name: Checkout 17 | uses: actions/checkout@v1 18 | - name: Install Rust 19 | uses: actions-rs/toolchain@v1 20 | with: 21 | profile: minimal 22 | toolchain: stable 23 | override: true 24 | components: rustfmt 25 | 26 | - name: cargo fmt --check 27 | uses: actions-rs/cargo@v1 28 | with: 29 | command: fmt 30 | args: --all -- --check 31 | 32 | test: 33 | name: Test 34 | runs-on: ubuntu-latest 35 | env: 36 | RUSTFLAGS: -Dwarnings 37 | strategy: 38 | matrix: 39 | rust: 40 | - stable 41 | - nightly 42 | steps: 43 | - name: Checkout 44 | uses: actions/checkout@v2 45 | 46 | - name: Install Rust (${{ matrix.rust }}) 47 | uses: actions-rs/toolchain@v1 48 | with: 49 | profile: minimal 50 | toolchain: ${{ matrix.rust }} 51 | override: true 52 | 53 | - name: Check examples 54 | uses: actions-rs/cargo@v1 55 | with: 56 | command: check 57 | args: --examples --all 58 | 59 | - name: Check examples with all features on stable 60 | uses: actions-rs/cargo@v1 61 | with: 62 | command: check 63 | args: --examples --all-features --all 64 | if: matrix.rust == 'stable' 65 | 66 | - name: Check benchmarks on nightly 67 | uses: actions-rs/cargo@v1 68 | with: 69 | command: check 70 | args: --all-features --examples --all --benches 71 | if: matrix.rust == 'nightly' 72 | 73 | - name: Test 74 | uses: actions-rs/cargo@v1 75 | with: 76 | command: test 77 | args: --release 78 | 79 | check_no_std: 80 | name: Check no_std 81 | runs-on: ubuntu-latest 82 | steps: 83 | - name: Checkout 84 | uses: actions/checkout@v2 85 | 86 | - name: Install Rust (${{ matrix.rust }}) 87 | uses: actions-rs/toolchain@v1 88 | with: 89 | toolchain: stable 90 | target: thumbv6m-none-eabi 91 | override: true 92 | 93 | - name: Install Rust ARM64 (${{ matrix.rust }}) 94 | uses: actions-rs/toolchain@v1 95 | with: 96 | toolchain: stable 97 | target: aarch64-unknown-none 98 | override: true 99 | 100 | - uses: actions/cache@v2 101 | with: 102 | path: | 103 | ~/.cargo/registry 104 | ~/.cargo/git 105 | target 106 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 107 | 108 | - name: ark-linear-sumcheck 109 | run: | 110 | cargo build --no-default-features --target aarch64-unknown-none 111 | cargo check --examples --no-default-features --target aarch64-unknown-none 112 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /sumcheck-benches/target 2 | /target 3 | Cargo.lock 4 | /.idea 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | 3 | ## Pending 4 | 5 | ### Breaking changes 6 | 7 | - [\#55](https://github.com/arkworks-rs/sumcheck/pull/55) Change the function signatures of `IPForMLSumcheck::verify_round` and `IPForMLSumcheck::prove_round`. 8 | 9 | ### Features 10 | 11 | ### Improvements 12 | 13 | - [\#73](https://github.com/arkworks-rs/sumcheck/pull/73) Add support for using `MLSumcheck` as subprotocol. 14 | 15 | - [\#72](https://github.com/arkworks-rs/sumcheck/pull/72) Uses `rayon` in the prover when the `parallel` feature is enabled. 16 | 17 | - [\#71](https://github.com/arkworks-rs/sumcheck/pull/71) Improve prover performance by using an arithmetic sequence rather than interpolation inside of the `prove_round` loop. 18 | 19 | - [\#55](https://github.com/arkworks-rs/sumcheck/pull/55) Improve the interpolation performance and avoid unnecessary state clones. 20 | 21 | ### Bug fixes 22 | 23 | - [\#75](https://github.com/arkworks-rs/sumcheck/pull/75) Correct interpolation function in the verifier 24 | 25 | ## v0.4.0 26 | - Change dependency to version `0.4.0` of other arkworks-rs crates. 27 | 28 | ## v0.3.0 29 | 30 | - Change dependency to version `0.3.0` of other arkworks-rs crates. 31 | 32 | ## v0.2.0 33 | 34 | The main feature of this release are: 35 | 36 | - Speedup and improved memory usage when same `MLExtension` is used for multiple places 37 | 38 | ### Breaking Changes 39 | 40 | - [\#41](https://github.com/arkworks-rs/sumcheck/pull/41) `ListOfProductsOfPolynomial::add_product` takes iterators of `Rc>` instead of `DenseMultilinearExtension`. 41 | - [\#41](https://github.com/arkworks-rs/sumcheck/pull/41) `ListOfProductsOfPolynomial` has been moved to `ml_sumcheck::data_structures`, but no actions required. 42 | - [\#46](https://github.com/arkworks-rs/sumcheck/pull/46) Update to hashbrown version 0.11.2. 43 | 44 | ### Features 45 | 46 | ### Improvements 47 | 48 | - [\#41](https://github.com/arkworks-rs/sumcheck/pull/41) `MLSumcheck` Prover uses memory linear to number of unique multilinear extensions instead of total number of multiplicands. 49 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ark-sumcheck" 3 | version = "0.4.0" 4 | authors = [ 5 | "Tom Shen ", 6 | "arkworks contributors" 7 | ] 8 | description = "A library for efficient sumcheck protocols" 9 | homepage = "https://arkworks.rs" 10 | repository = "https://github.com/arkworks-rs/sumcheck/" 11 | keywords = ["cryptography", "finite-fields", "polynomials", "sumcheck", "gkr"] 12 | categories = ["cryptography"] 13 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 14 | license = "MIT/Apache-2.0" 15 | edition = "2018" 16 | resolver = "2" 17 | 18 | [dependencies] 19 | ark-ff = { version = "0.4.0", default-features = false } 20 | ark-serialize = { version = "0.4.0", default-features = false, features = ["derive"] } 21 | ark-std = { version = "0.4.0", default-features = false } 22 | ark-poly = { version = "0.4.0", default-features = false } 23 | hashbrown = { version = "0.15.0" } 24 | blake2 = { version = "0.10", default-features = false } 25 | rayon = { version = "1", optional = true } 26 | 27 | [dev-dependencies] 28 | ark-test-curves = { version = "0.4.0", default-features = false, features = ["bls12_381_scalar_field", "bls12_381_curve"] } 29 | 30 | [profile.release] 31 | opt-level = 3 32 | lto = "thin" 33 | incremental = true 34 | panic = 'abort' 35 | 36 | [profile.bench] 37 | opt-level = 3 38 | debug = false 39 | rpath = false 40 | lto = "thin" 41 | incremental = true 42 | debug-assertions = false 43 | 44 | [profile.dev] 45 | opt-level = 0 46 | panic = 'abort' 47 | 48 | [profile.test] 49 | opt-level = 3 50 | lto = "thin" 51 | incremental = true 52 | debug-assertions = true 53 | debug = true 54 | 55 | [features] 56 | default = ["std"] 57 | std = ["ark-ff/std", "ark-serialize/std", "blake2/std", "ark-std/std", "ark-poly/std"] 58 | parallel = ["std", "ark-ff/parallel", "ark-poly/parallel", "ark-std/parallel", "rayon"] 59 | 60 | # To be removed in the new release. 61 | [patch.crates-io] 62 | ark-ec = { git = "https://github.com/arkworks-rs/algebra" } 63 | ark-ff = { git = "https://github.com/arkworks-rs/algebra" } 64 | ark-poly = { git = "https://github.com/arkworks-rs/algebra" } 65 | ark-serialize = { git = "https://github.com/arkworks-rs/algebra" } 66 | ark-test-curves = { git = "https://github.com/arkworks-rs/algebra" } 67 | ark-std = { git = "https://github.com/arkworks-rs/std" } -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Linear-Time Sumcheck

2 | 3 |

4 | 5 | 6 | 7 | 8 |

9 | 10 | 11 | `linear-sumcheck` is a Rust library that implements the sumcheck protocol. 12 | 13 | This crate implements the following protocols: 14 | - [`MLSumcheck`](src/ml_sumcheck/mod.rs#L18): The sumcheck protocol for 15 | products of multilinear polynomials in evaluation form over boolean hypercube. 16 | - [`GKRRoundSumcheck`](src/gkr_round_sumcheck/mod.rs#L83): The sumcheck protocol for GKR Round Function. 17 | This protocol takes `MLSumcheck` as a subroutine. 18 | 19 | **WARNING**: This is an academic proof-of-concept prototype, and in particular has not received careful code review. This implementation is NOT ready for production use. 20 | 21 | ## Build guide 22 | 23 | The library compiles on the `stable` toolchain of the Rust compiler. To install the latest version of Rust, first install `rustup` by following the instructions [here](https://rustup.rs/), or via your platform's package manager. Once `rustup` is installed, install the Rust toolchain by invoking: 24 | ```bash 25 | rustup install stable 26 | ``` 27 | 28 | After that, use `cargo` (the standard Rust build tool) to build the library: 29 | ```bash 30 | git clone https://github.com/arkworks-rs/sumcheck.git 31 | cd sumcheck 32 | cargo build --release 33 | ``` 34 | 35 | This library comes with some unit and integration tests. Run these tests with: 36 | ```bash 37 | cargo test 38 | ``` 39 | 40 | Lastly, this library is instrumented with profiling infrastructure that prints detailed traces of execution time. To enable this, compile with `cargo build --features print-trace`. 41 | 42 | ## Benchmarks 43 | 44 | To run the benchmarks, install the nightly Rust toolchain, via `rustup install nightly`, and then run the following command: 45 | 46 | ```shell 47 | cargo +nightly bench --all-features 48 | ``` 49 | 50 | All benchmarks below are performed over BLS12-381 scalar field implemented in the `ark-test-curves` library. Benchmarks were run on a machine with an Intel Xeon 6136 CPU running at 3.0 GHz. 51 | 52 | #### Benchmarks for `MLSumcheck` 53 | 54 | ml_sumcheck_prove 55 | 56 | ml_sumcheck_verify 57 | 58 | #### Benchmarks for `GKRRoundSumcheck` 59 | 60 | gkr_round_sumcheck_prove 61 | 62 | gkr_round_sumcheck_verify 63 | 64 | ## License 65 | 66 | This library is licensed under either of the following licenses, at your discretion. 67 | 68 | * [Apache License Version 2.0](LICENSE-APACHE) 69 | * [MIT License](LICENSE-MIT) 70 | 71 | Unless you explicitly state otherwise, any contribution that you submit to this library shall be dual licensed as above (as defined in the Apache v2 License), without any additional terms or conditions. 72 | 73 | ## Reference Paper 74 | [Libra: Succinct Zero-Knowledge Proofs with Optimal Prover Computation](https://eprint.iacr.org/2019/317)
75 | Tiancheng Xie, Jiaheng Zhang, Yupeng Zhang, Charalampos Papamanthou, Dawn Song 76 | 77 | [Time-Optimal Interactive Proofs for Circuit Evaluation](https://arxiv.org/abs/1304.3812)
78 | Justin Thaler 79 | -------------------------------------------------------------------------------- /benchmark_results/gkr_round_sumcheck_prove.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arkworks-rs/sumcheck/d241e9b17f48989831534975eb8e43adc8ec71d3/benchmark_results/gkr_round_sumcheck_prove.jpg -------------------------------------------------------------------------------- /benchmark_results/gkr_round_sumcheck_verify.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arkworks-rs/sumcheck/d241e9b17f48989831534975eb8e43adc8ec71d3/benchmark_results/gkr_round_sumcheck_verify.jpg -------------------------------------------------------------------------------- /benchmark_results/ml_sumcheck_prove.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arkworks-rs/sumcheck/d241e9b17f48989831534975eb8e43adc8ec71d3/benchmark_results/ml_sumcheck_prove.jpg -------------------------------------------------------------------------------- /benchmark_results/ml_sumcheck_verify.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arkworks-rs/sumcheck/d241e9b17f48989831534975eb8e43adc8ec71d3/benchmark_results/ml_sumcheck_verify.jpg -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use ark_std::fmt; 2 | 3 | use ark_std::string::String; 4 | use core::fmt::Formatter; 5 | /// Error type for this crate 6 | #[derive(fmt::Debug)] 7 | pub enum Error { 8 | /// protocol rejects this proof 9 | Reject(Option), 10 | /// IO Error 11 | IOError, 12 | /// Serialization Error 13 | SerializationError, 14 | /// Random Generator Error 15 | RNGError, 16 | /// Other caused by other operations 17 | OtherError(String), 18 | } 19 | 20 | impl fmt::Display for Error { 21 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 22 | if let Self::OtherError(s) = self { 23 | f.write_str(s) 24 | } else { 25 | f.write_fmt(format_args!("{self:?}")) 26 | } 27 | } 28 | } 29 | 30 | impl ark_std::error::Error for Error {} 31 | 32 | impl From for Error { 33 | fn from(_: ark_std::io::Error) -> Self { 34 | Self::IOError 35 | } 36 | } 37 | 38 | impl From for Error { 39 | fn from(_: ark_serialize::SerializationError) -> Self { 40 | Self::SerializationError 41 | } 42 | } 43 | impl From for Error { 44 | fn from(_: ark_std::rand::Error) -> Self { 45 | Self::RNGError 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/gkr_round_sumcheck/data_structures.rs: -------------------------------------------------------------------------------- 1 | //! Data structures used by GKR Round Sumcheck 2 | 3 | use crate::ml_sumcheck::protocol::prover::ProverMsg; 4 | use ark_ff::Field; 5 | use ark_poly::{DenseMultilinearExtension, Polynomial, SparseMultilinearExtension}; 6 | use ark_std::vec::Vec; 7 | 8 | /// Proof for GKR Round Function 9 | pub struct GKRProof { 10 | pub(crate) phase1_sumcheck_msgs: Vec>, 11 | pub(crate) phase2_sumcheck_msgs: Vec>, 12 | } 13 | 14 | impl GKRProof { 15 | /// Extract the witness (i.e. the sum of GKR) 16 | pub fn extract_sum(&self) -> F { 17 | self.phase1_sumcheck_msgs[0].evaluations[0] + self.phase1_sumcheck_msgs[0].evaluations[1] 18 | } 19 | } 20 | 21 | /// Subclaim for GKR Round Function 22 | pub struct GKRRoundSumcheckSubClaim { 23 | /// u 24 | pub u: Vec, 25 | /// v 26 | pub v: Vec, 27 | /// expected evaluation at f(g,u,v) 28 | pub expected_evaluation: F, 29 | } 30 | 31 | impl GKRRoundSumcheckSubClaim { 32 | /// Verify that the subclaim is true by evaluating the GKR Round function. 33 | pub fn verify_subclaim( 34 | &self, 35 | f1: &SparseMultilinearExtension, 36 | f2: &DenseMultilinearExtension, 37 | f3: &DenseMultilinearExtension, 38 | g: &[F], 39 | ) -> bool { 40 | let dim = self.u.len(); 41 | assert_eq!(self.v.len(), dim); 42 | assert_eq!(f1.num_vars, 3 * dim); 43 | assert_eq!(f2.num_vars, dim); 44 | assert_eq!(f3.num_vars, dim); 45 | assert_eq!(g.len(), dim); 46 | 47 | let guv: Vec<_> = g 48 | .iter() 49 | .chain(self.u.iter()) 50 | .chain(self.v.iter()) 51 | .copied() 52 | .collect(); 53 | let actual_evaluation = f1.evaluate(&guv) * f2.evaluate(&self.u) * f3.evaluate(&self.v); 54 | 55 | actual_evaluation == self.expected_evaluation 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/gkr_round_sumcheck/mod.rs: -------------------------------------------------------------------------------- 1 | //! Implementation of GKR Round Sumcheck algorithm as described in [XZZPS19](https://eprint.iacr.org/2019/317.pdf#subsection.3.3) (Section 3.3) 2 | //! 3 | //! GKR Round Sumcheck will use `ml_sumcheck` as a subroutine. 4 | 5 | pub mod data_structures; 6 | #[cfg(test)] 7 | mod test; 8 | 9 | use crate::gkr_round_sumcheck::data_structures::{GKRProof, GKRRoundSumcheckSubClaim}; 10 | use crate::ml_sumcheck::protocol::prover::ProverState; 11 | use crate::ml_sumcheck::protocol::{IPForMLSumcheck, ListOfProductsOfPolynomials, PolynomialInfo}; 12 | use crate::rng::FeedableRNG; 13 | use ark_ff::{Field, Zero}; 14 | use ark_poly::{ 15 | DenseMultilinearExtension, MultilinearExtension, Polynomial, SparseMultilinearExtension, 16 | }; 17 | use ark_std::marker::PhantomData; 18 | use ark_std::rc::Rc; 19 | use ark_std::vec::Vec; 20 | 21 | /// Takes multilinear f1, f3, and input g = g1,...,gl. Returns h_g, and f1 fixed at g. 22 | pub fn initialize_phase_one( 23 | f1: &SparseMultilinearExtension, 24 | f3: &DenseMultilinearExtension, 25 | g: &[F], 26 | ) -> (DenseMultilinearExtension, SparseMultilinearExtension) { 27 | let dim = f3.num_vars; // 'l` in paper 28 | assert_eq!(f1.num_vars, dim * 3); 29 | assert_eq!(g.len(), dim); 30 | let mut a_hg: Vec<_> = (0..(1 << dim)).map(|_| F::zero()).collect(); 31 | let f1_at_g = f1.fix_variables(g); 32 | for (xy, v) in f1_at_g.evaluations.iter() { 33 | if v != &F::zero() { 34 | let x = xy & ((1 << dim) - 1); 35 | let y = xy >> dim; 36 | a_hg[x] += *v * f3[y]; 37 | } 38 | } 39 | 40 | let hg = DenseMultilinearExtension::from_evaluations_vec(dim, a_hg); 41 | (hg, f1_at_g) 42 | } 43 | 44 | /// Takes h_g and returns a sumcheck state 45 | pub fn start_phase1_sumcheck( 46 | h_g: &DenseMultilinearExtension, 47 | f2: &DenseMultilinearExtension, 48 | ) -> ProverState { 49 | let dim = h_g.num_vars; 50 | assert_eq!(f2.num_vars, dim); 51 | let mut poly = ListOfProductsOfPolynomials::new(dim); 52 | poly.add_product(vec![Rc::new(h_g.clone()), Rc::new(f2.clone())], F::one()); 53 | IPForMLSumcheck::prover_init(&poly) 54 | } 55 | 56 | /// Takes multilinear f1 fixed at g, phase one randomness u. Returns f1 fixed at g||u 57 | pub fn initialize_phase_two( 58 | f1_g: &SparseMultilinearExtension, 59 | u: &[F], 60 | ) -> DenseMultilinearExtension { 61 | assert_eq!(u.len() * 2, f1_g.num_vars); 62 | f1_g.fix_variables(u).to_dense_multilinear_extension() 63 | } 64 | 65 | /// Takes f1 fixed at g||u, f3, and f2 evaluated at u. 66 | pub fn start_phase2_sumcheck( 67 | f1_gu: &DenseMultilinearExtension, 68 | f3: &DenseMultilinearExtension, 69 | f2_u: F, 70 | ) -> ProverState { 71 | let f3_f2u = { 72 | let mut zero = DenseMultilinearExtension::zero(); 73 | zero += (f2_u, f3); 74 | zero 75 | }; 76 | 77 | let dim = f1_gu.num_vars; 78 | assert_eq!(f3.num_vars, dim); 79 | let mut poly = ListOfProductsOfPolynomials::new(dim); 80 | poly.add_product(vec![Rc::new(f1_gu.clone()), Rc::new(f3_f2u)], F::one()); 81 | IPForMLSumcheck::prover_init(&poly) 82 | } 83 | 84 | /// Sumcheck Argument for GKR Round Function 85 | pub struct GKRRoundSumcheck { 86 | _marker: PhantomData, 87 | } 88 | 89 | impl GKRRoundSumcheck { 90 | /// Takes a GKR Round Function and input, prove the sum. 91 | /// * `f1`,`f2`,`f3`: represents the GKR round function 92 | /// * `g`: represents the fixed input. 93 | pub fn prove( 94 | rng: &mut R, 95 | f1: &SparseMultilinearExtension, 96 | f2: &DenseMultilinearExtension, 97 | f3: &DenseMultilinearExtension, 98 | g: &[F], 99 | ) -> GKRProof { 100 | assert_eq!(f1.num_vars, 3 * f2.num_vars); 101 | assert_eq!(f1.num_vars, 3 * f3.num_vars); 102 | 103 | let dim = f2.num_vars; 104 | let g = g.to_vec(); 105 | 106 | let (h_g, f1_g) = initialize_phase_one(f1, f3, &g); 107 | let mut phase1_ps = start_phase1_sumcheck(&h_g, f2); 108 | let mut phase1_vm = None; 109 | let mut phase1_prover_msgs = Vec::with_capacity(dim); 110 | let mut u = Vec::with_capacity(dim); 111 | for _ in 0..dim { 112 | let pm = IPForMLSumcheck::prove_round(&mut phase1_ps, &phase1_vm); 113 | 114 | rng.feed(&pm).unwrap(); 115 | phase1_prover_msgs.push(pm); 116 | let vm = IPForMLSumcheck::sample_round(rng); 117 | phase1_vm = Some(vm.clone()); 118 | u.push(vm.randomness); 119 | } 120 | 121 | let f1_gu = initialize_phase_two(&f1_g, &u); 122 | let mut phase2_ps = start_phase2_sumcheck(&f1_gu, f3, f2.evaluate(&u)); 123 | let mut phase2_vm = None; 124 | let mut phase2_prover_msgs = Vec::with_capacity(dim); 125 | let mut v = Vec::with_capacity(dim); 126 | for _ in 0..dim { 127 | let pm = IPForMLSumcheck::prove_round(&mut phase2_ps, &phase2_vm); 128 | rng.feed(&pm).unwrap(); 129 | phase2_prover_msgs.push(pm); 130 | let vm = IPForMLSumcheck::sample_round(rng); 131 | phase2_vm = Some(vm.clone()); 132 | v.push(vm.randomness); 133 | } 134 | 135 | GKRProof { 136 | phase1_sumcheck_msgs: phase1_prover_msgs, 137 | phase2_sumcheck_msgs: phase2_prover_msgs, 138 | } 139 | } 140 | 141 | /// Takes a GKR Round Function, input, and proof, and returns a subclaim. 142 | /// 143 | /// If the `claimed_sum` is correct, then it is `subclaim.verify_subclaim` will return true. 144 | /// Otherwise, it is very likely that `subclaim.verify_subclaim` will return false. 145 | /// Larger field size guarantees smaller soundness error. 146 | /// * `f2_num_vars`: represents number of variables of f2 147 | pub fn verify( 148 | rng: &mut R, 149 | f2_num_vars: usize, 150 | proof: &GKRProof, 151 | claimed_sum: F, 152 | ) -> Result, crate::Error> { 153 | // verify first sumcheck 154 | let dim = f2_num_vars; 155 | 156 | let mut phase1_vs = IPForMLSumcheck::verifier_init(&PolynomialInfo { 157 | max_multiplicands: 2, 158 | num_variables: dim, 159 | }); 160 | 161 | for i in 0..dim { 162 | let pm = &proof.phase1_sumcheck_msgs[i]; 163 | rng.feed(pm).unwrap(); 164 | let _result = IPForMLSumcheck::verify_round((*pm).clone(), &mut phase1_vs, rng); 165 | } 166 | let phase1_subclaim = IPForMLSumcheck::check_and_generate_subclaim(phase1_vs, claimed_sum)?; 167 | let u = phase1_subclaim.point; 168 | 169 | let mut phase2_vs = IPForMLSumcheck::verifier_init(&PolynomialInfo { 170 | max_multiplicands: 2, 171 | num_variables: dim, 172 | }); 173 | for i in 0..dim { 174 | let pm = &proof.phase2_sumcheck_msgs[i]; 175 | rng.feed(pm).unwrap(); 176 | let _result = IPForMLSumcheck::verify_round((*pm).clone(), &mut phase2_vs, rng); 177 | } 178 | let phase2_subclaim = IPForMLSumcheck::check_and_generate_subclaim( 179 | phase2_vs, 180 | phase1_subclaim.expected_evaluation, 181 | )?; 182 | 183 | let v = phase2_subclaim.point; 184 | 185 | let expected_evaluation = phase2_subclaim.expected_evaluation; 186 | 187 | Ok(GKRRoundSumcheckSubClaim { 188 | u, 189 | v, 190 | expected_evaluation, 191 | }) 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/gkr_round_sumcheck/test.rs: -------------------------------------------------------------------------------- 1 | use crate::gkr_round_sumcheck::GKRRoundSumcheck; 2 | use crate::rng::{Blake2b512Rng, FeedableRNG}; 3 | use ark_ff::Field; 4 | use ark_poly::{DenseMultilinearExtension, MultilinearExtension, SparseMultilinearExtension}; 5 | use ark_std::rand::RngCore; 6 | use ark_std::{test_rng, UniformRand}; 7 | use ark_test_curves::bls12_381::Fr; 8 | 9 | fn random_gkr_instance( 10 | dim: usize, 11 | rng: &mut R, 12 | ) -> ( 13 | SparseMultilinearExtension, 14 | DenseMultilinearExtension, 15 | DenseMultilinearExtension, 16 | ) { 17 | ( 18 | SparseMultilinearExtension::rand_with_config(dim * 3, 1 << dim, rng), 19 | DenseMultilinearExtension::rand(dim, rng), 20 | DenseMultilinearExtension::rand(dim, rng), 21 | ) 22 | } 23 | 24 | fn calculate_sum_naive( 25 | f1: &SparseMultilinearExtension, 26 | f2: &DenseMultilinearExtension, 27 | f3: &DenseMultilinearExtension, 28 | g: &[F], 29 | ) -> F { 30 | let dim = f2.num_vars; 31 | assert_eq!(f1.num_vars, 3 * dim); 32 | assert_eq!(f3.num_vars, dim); 33 | let f1_g = f1.fix_variables(g); 34 | let mut sum_xy = F::zero(); 35 | for x in 0..(1 << dim) { 36 | let f2_x = f2[x]; 37 | let f1_gx = f1_g 38 | .fix_variables(&index_to_field_element(x, dim)) 39 | .to_dense_multilinear_extension(); 40 | for y in 0..(1 << dim) { 41 | sum_xy += f1_gx[y] * f2_x * f3[y]; 42 | } 43 | } 44 | sum_xy 45 | } 46 | 47 | fn index_to_field_element(mut index: usize, mut nv: usize) -> Vec { 48 | let mut ans = Vec::with_capacity(nv); 49 | while nv != 0 { 50 | ans.push(((index & 1) as u64).into()); 51 | index >>= 1; 52 | nv -= 1; 53 | } 54 | ans 55 | } 56 | 57 | fn test_circuit(nv: usize) { 58 | let mut rng = test_rng(); 59 | let (f1, f2, f3) = random_gkr_instance(nv, &mut rng); 60 | let g: Vec<_> = (0..nv).map(|_| F::rand(&mut rng)).collect(); 61 | let claimed_sum = calculate_sum_naive(&f1, &f2, &f3, &g); 62 | let mut rng = Blake2b512Rng::setup(); 63 | let proof = GKRRoundSumcheck::prove(&mut rng, &f1, &f2, &f3, &g); 64 | rng = Blake2b512Rng::setup(); 65 | let subclaim = GKRRoundSumcheck::verify(&mut rng, f2.num_vars, &proof, claimed_sum) 66 | .expect("verification failed"); 67 | let result = subclaim.verify_subclaim(&f1, &f2, &f3, &g); 68 | assert!(result) 69 | } 70 | 71 | #[test] 72 | fn test_small() { 73 | test_circuit::(9); 74 | } 75 | 76 | #[test] 77 | fn test_extract() { 78 | let nv = 6; 79 | let mut rng = test_rng(); 80 | let (f1, f2, f3) = random_gkr_instance(nv, &mut rng); 81 | let g: Vec<_> = (0..nv).map(|_| Fr::rand(&mut rng)).collect(); 82 | let expected_sum = calculate_sum_naive(&f1, &f2, &f3, &g); 83 | let mut rng = Blake2b512Rng::setup(); 84 | let proof = GKRRoundSumcheck::prove(&mut rng, &f1, &f2, &f3, &g); 85 | let actual_sum = proof.extract_sum(); 86 | 87 | assert_eq!(actual_sum, expected_sum); 88 | } 89 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![forbid(unsafe_code)] 2 | #![cfg_attr(not(feature = "std"), no_std)] 3 | //! A crate for sumcheck protocol of GKR functions 4 | #![deny(unused_import_braces, unused_qualifications, trivial_casts)] 5 | #![deny(trivial_numeric_casts, variant_size_differences)] 6 | #![deny(stable_features, unreachable_pub, non_shorthand_field_patterns)] 7 | #![deny(unused_attributes, unused_mut)] 8 | #![deny(missing_docs)] 9 | #![deny(unused_imports)] 10 | #![deny(renamed_and_removed_lints, stable_features, unused_allocation)] 11 | #![deny(unused_comparisons, bare_trait_objects, unused_must_use)] 12 | 13 | pub use error::Error; 14 | 15 | /// use ark_std for std 16 | #[macro_use] 17 | extern crate ark_std; 18 | 19 | /// error for this crate 20 | mod error; 21 | 22 | pub mod gkr_round_sumcheck; 23 | pub mod ml_sumcheck; 24 | 25 | pub mod rng; 26 | 27 | #[cfg(test)] 28 | mod tests {} 29 | -------------------------------------------------------------------------------- /src/ml_sumcheck/data_structures.rs: -------------------------------------------------------------------------------- 1 | //! Defines the data structures used by the `MLSumcheck` protocol. 2 | 3 | use ark_ff::Field; 4 | use ark_poly::{DenseMultilinearExtension, Polynomial}; 5 | use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; 6 | use ark_std::cmp::max; 7 | use ark_std::rc::Rc; 8 | use ark_std::vec::Vec; 9 | use hashbrown::HashMap; 10 | /// Stores a list of products of `DenseMultilinearExtension` that is meant to be added together. 11 | /// 12 | /// The polynomial is represented by a list of products of polynomials along with its coefficient that is meant to be added together. 13 | /// 14 | /// This data structure of the polynomial is a list of list of `(coefficient, DenseMultilinearExtension)`. 15 | /// * Number of products n = `self.products.len()`, 16 | /// * Number of multiplicands of ith product m_i = `self.products[i].1.len()`, 17 | /// * Coefficient of ith product c_i = `self.products[i].0` 18 | /// 19 | /// The resulting polynomial is 20 | /// 21 | /// $$\sum_{i=0}^{n}C_i\cdot\prod_{j=0}^{m_i}P_{ij}$$ 22 | /// 23 | /// The result polynomial is used as the prover key. 24 | #[derive(Clone)] 25 | pub struct ListOfProductsOfPolynomials { 26 | /// max number of multiplicands in each product 27 | pub max_multiplicands: usize, 28 | /// number of variables of the polynomial 29 | pub num_variables: usize, 30 | /// list of reference to products (as usize) of multilinear extension 31 | pub products: Vec<(F, Vec)>, 32 | /// Stores multilinear extensions in which product multiplicand can refer to. 33 | pub flattened_ml_extensions: Vec>>, 34 | raw_pointers_lookup_table: HashMap<*const DenseMultilinearExtension, usize>, 35 | } 36 | 37 | impl ListOfProductsOfPolynomials { 38 | /// Extract the max number of multiplicands and number of variables of the list of products. 39 | pub fn info(&self) -> PolynomialInfo { 40 | PolynomialInfo { 41 | max_multiplicands: self.max_multiplicands, 42 | num_variables: self.num_variables, 43 | } 44 | } 45 | } 46 | 47 | #[derive(CanonicalSerialize, CanonicalDeserialize, Clone)] 48 | /// Stores the number of variables and max number of multiplicands of the added polynomial used by the prover. 49 | /// This data structures will is used as the verifier key. 50 | pub struct PolynomialInfo { 51 | /// max number of multiplicands in each product 52 | pub max_multiplicands: usize, 53 | /// number of variables of the polynomial 54 | pub num_variables: usize, 55 | } 56 | 57 | impl ListOfProductsOfPolynomials { 58 | /// Returns an empty polynomial 59 | pub fn new(num_variables: usize) -> Self { 60 | ListOfProductsOfPolynomials { 61 | max_multiplicands: 0, 62 | num_variables, 63 | products: Vec::new(), 64 | flattened_ml_extensions: Vec::new(), 65 | raw_pointers_lookup_table: HashMap::new(), 66 | } 67 | } 68 | 69 | /// Add a list of multilinear extensions that is meant to be multiplied together. 70 | /// The resulting polynomial will be multiplied by the scalar `coefficient`. 71 | pub fn add_product( 72 | &mut self, 73 | product: impl IntoIterator>>, 74 | coefficient: F, 75 | ) { 76 | let product: Vec>> = product.into_iter().collect(); 77 | let mut indexed_product = Vec::with_capacity(product.len()); 78 | assert!(!product.is_empty()); 79 | self.max_multiplicands = max(self.max_multiplicands, product.len()); 80 | for m in product { 81 | assert_eq!( 82 | m.num_vars, self.num_variables, 83 | "product has a multiplicand with wrong number of variables" 84 | ); 85 | let m_ptr: *const DenseMultilinearExtension = Rc::as_ptr(&m); 86 | if let Some(index) = self.raw_pointers_lookup_table.get(&m_ptr) { 87 | indexed_product.push(*index) 88 | } else { 89 | let curr_index = self.flattened_ml_extensions.len(); 90 | self.flattened_ml_extensions.push(m.clone()); 91 | self.raw_pointers_lookup_table.insert(m_ptr, curr_index); 92 | indexed_product.push(curr_index); 93 | } 94 | } 95 | self.products.push((coefficient, indexed_product)); 96 | } 97 | 98 | /// Evaluate the polynomial at point `point` 99 | pub fn evaluate(&self, point: &[F]) -> F { 100 | self.products 101 | .iter() 102 | .map(|(c, p)| { 103 | *c * p 104 | .iter() 105 | .map(|&i| self.flattened_ml_extensions[i].evaluate(&point.to_vec())) 106 | .product::() 107 | }) 108 | .sum() 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/ml_sumcheck/mod.rs: -------------------------------------------------------------------------------- 1 | //! Sumcheck Protocol for multilinear extension 2 | 3 | use crate::ml_sumcheck::data_structures::{ListOfProductsOfPolynomials, PolynomialInfo}; 4 | use crate::ml_sumcheck::protocol::prover::{ProverMsg, ProverState}; 5 | use crate::ml_sumcheck::protocol::verifier::SubClaim; 6 | use crate::ml_sumcheck::protocol::IPForMLSumcheck; 7 | use crate::rng::{Blake2b512Rng, FeedableRNG}; 8 | use ark_ff::Field; 9 | use ark_std::marker::PhantomData; 10 | use ark_std::vec::Vec; 11 | 12 | pub mod protocol; 13 | 14 | pub mod data_structures; 15 | #[cfg(test)] 16 | mod test; 17 | 18 | /// Sumcheck for products of multilinear polynomial 19 | pub struct MLSumcheck(#[doc(hidden)] PhantomData); 20 | 21 | /// proof generated by prover 22 | pub type Proof = Vec>; 23 | 24 | impl MLSumcheck { 25 | /// extract sum from the proof 26 | pub fn extract_sum(proof: &Proof) -> F { 27 | proof[0].evaluations[0] + proof[0].evaluations[1] 28 | } 29 | 30 | /// generate proof of the sum of polynomial over {0,1}^`num_vars` 31 | /// 32 | /// The polynomial is represented by a list of products of polynomials along with its coefficient that is meant to be added together. 33 | /// 34 | /// This data structure of the polynomial is a list of list of `(coefficient, DenseMultilinearExtension)`. 35 | /// * Number of products n = `polynomial.products.len()`, 36 | /// * Number of multiplicands of ith product m_i = `polynomial.products[i].1.len()`, 37 | /// * Coefficient of ith product c_i = `polynomial.products[i].0` 38 | /// 39 | /// The resulting polynomial is 40 | /// 41 | /// $$\sum_{i=0}^{n}C_i\cdot\prod_{j=0}^{m_i}P_{ij}$$ 42 | pub fn prove(polynomial: &ListOfProductsOfPolynomials) -> Result, crate::Error> { 43 | let mut fs_rng = Blake2b512Rng::setup(); 44 | Self::prove_as_subprotocol(&mut fs_rng, polynomial).map(|r| r.0) 45 | } 46 | 47 | /// This function does the same thing as `prove`, but it uses a `FeedableRNG` as the transcript/to generate the 48 | /// verifier challenges. Additionally, it returns the prover's state in addition to the proof. 49 | /// Both of these allow this sumcheck to be better used as a part of a larger protocol. 50 | pub fn prove_as_subprotocol( 51 | fs_rng: &mut impl FeedableRNG, 52 | polynomial: &ListOfProductsOfPolynomials, 53 | ) -> Result<(Proof, ProverState), crate::Error> { 54 | fs_rng.feed(&polynomial.info())?; 55 | 56 | let mut prover_state = IPForMLSumcheck::prover_init(polynomial); 57 | let mut verifier_msg = None; 58 | let mut prover_msgs = Vec::with_capacity(polynomial.num_variables); 59 | for _ in 0..polynomial.num_variables { 60 | let prover_msg = IPForMLSumcheck::prove_round(&mut prover_state, &verifier_msg); 61 | fs_rng.feed(&prover_msg)?; 62 | prover_msgs.push(prover_msg); 63 | verifier_msg = Some(IPForMLSumcheck::sample_round(fs_rng)); 64 | } 65 | prover_state 66 | .randomness 67 | .push(verifier_msg.unwrap().randomness); 68 | 69 | Ok((prover_msgs, prover_state)) 70 | } 71 | 72 | /// verify the claimed sum using the proof 73 | pub fn verify( 74 | polynomial_info: &PolynomialInfo, 75 | claimed_sum: F, 76 | proof: &Proof, 77 | ) -> Result, crate::Error> { 78 | let mut fs_rng = Blake2b512Rng::setup(); 79 | Self::verify_as_subprotocol(&mut fs_rng, polynomial_info, claimed_sum, proof) 80 | } 81 | 82 | /// This function does the same thing as `prove`, but it uses a `FeedableRNG` as the transcript/to generate the 83 | /// verifier challenges. This allows this sumcheck to be used as a part of a larger protocol. 84 | pub fn verify_as_subprotocol( 85 | fs_rng: &mut impl FeedableRNG, 86 | polynomial_info: &PolynomialInfo, 87 | claimed_sum: F, 88 | proof: &Proof, 89 | ) -> Result, crate::Error> { 90 | fs_rng.feed(polynomial_info)?; 91 | let mut verifier_state = IPForMLSumcheck::verifier_init(polynomial_info); 92 | for i in 0..polynomial_info.num_variables { 93 | let prover_msg = proof.get(i).expect("proof is incomplete"); 94 | fs_rng.feed(prover_msg)?; 95 | let _verifier_msg = 96 | IPForMLSumcheck::verify_round((*prover_msg).clone(), &mut verifier_state, fs_rng); 97 | } 98 | 99 | IPForMLSumcheck::check_and_generate_subclaim(verifier_state, claimed_sum) 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/ml_sumcheck/protocol/mod.rs: -------------------------------------------------------------------------------- 1 | //! Interactive Proof Protocol used for Multilinear Sumcheck 2 | 3 | use ark_ff::Field; 4 | use ark_std::marker::PhantomData; 5 | 6 | pub mod prover; 7 | pub mod verifier; 8 | pub use crate::ml_sumcheck::data_structures::{ListOfProductsOfPolynomials, PolynomialInfo}; 9 | /// Interactive Proof for Multilinear Sumcheck 10 | pub struct IPForMLSumcheck { 11 | #[doc(hidden)] 12 | _marker: PhantomData, 13 | } 14 | -------------------------------------------------------------------------------- /src/ml_sumcheck/protocol/prover.rs: -------------------------------------------------------------------------------- 1 | //! Prover 2 | use crate::ml_sumcheck::data_structures::ListOfProductsOfPolynomials; 3 | use crate::ml_sumcheck::protocol::verifier::VerifierMsg; 4 | use crate::ml_sumcheck::protocol::IPForMLSumcheck; 5 | use ark_ff::Field; 6 | use ark_poly::{DenseMultilinearExtension, MultilinearExtension}; 7 | use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; 8 | use ark_std::{cfg_iter_mut, vec::Vec}; 9 | #[cfg(feature = "parallel")] 10 | use rayon::prelude::*; 11 | 12 | /// Prover Message 13 | #[derive(Clone, CanonicalSerialize, CanonicalDeserialize)] 14 | pub struct ProverMsg { 15 | /// evaluations on P(0), P(1), P(2), ... 16 | pub(crate) evaluations: Vec, 17 | } 18 | /// Prover State 19 | pub struct ProverState { 20 | /// sampled randomness given by the verifier 21 | pub randomness: Vec, 22 | /// Stores the list of products that is meant to be added together. Each multiplicand is represented by 23 | /// the index in flattened_ml_extensions 24 | pub list_of_products: Vec<(F, Vec)>, 25 | /// Stores a list of multilinear extensions in which `self.list_of_products` points to 26 | pub flattened_ml_extensions: Vec>, 27 | /// Number of variables 28 | pub num_vars: usize, 29 | /// Max number of multiplicands in a product 30 | pub max_multiplicands: usize, 31 | /// The current round number 32 | pub round: usize, 33 | } 34 | 35 | impl IPForMLSumcheck { 36 | /// initialize the prover to argue for the sum of polynomial over {0,1}^`num_vars` 37 | /// 38 | /// The polynomial is represented by a list of products of polynomials along with its coefficient that is meant to be added together. 39 | /// 40 | /// This data structure of the polynomial is a list of list of `(coefficient, DenseMultilinearExtension)`. 41 | /// * Number of products n = `polynomial.products.len()`, 42 | /// * Number of multiplicands of ith product m_i = `polynomial.products[i].1.len()`, 43 | /// * Coefficient of ith product c_i = `polynomial.products[i].0` 44 | /// 45 | /// The resulting polynomial is 46 | /// 47 | /// $$\sum_{i=0}^{n}C_i\cdot\prod_{j=0}^{m_i}P_{ij}$$ 48 | /// 49 | pub fn prover_init(polynomial: &ListOfProductsOfPolynomials) -> ProverState { 50 | if polynomial.num_variables == 0 { 51 | panic!("Attempt to prove a constant.") 52 | } 53 | 54 | // create a deep copy of all unique MLExtensions 55 | let flattened_ml_extensions = polynomial 56 | .flattened_ml_extensions 57 | .iter() 58 | .map(|x| x.as_ref().clone()) 59 | .collect(); 60 | 61 | ProverState { 62 | randomness: Vec::with_capacity(polynomial.num_variables), 63 | list_of_products: polynomial.products.clone(), 64 | flattened_ml_extensions, 65 | num_vars: polynomial.num_variables, 66 | max_multiplicands: polynomial.max_multiplicands, 67 | round: 0, 68 | } 69 | } 70 | 71 | /// receive message from verifier, generate prover message, and proceed to next round 72 | /// 73 | /// Main algorithm used is from section 3.2 of [XZZPS19](https://eprint.iacr.org/2019/317.pdf#subsection.3.2). 74 | pub fn prove_round( 75 | prover_state: &mut ProverState, 76 | v_msg: &Option>, 77 | ) -> ProverMsg { 78 | if let Some(msg) = v_msg { 79 | if prover_state.round == 0 { 80 | panic!("first round should be prover first."); 81 | } 82 | prover_state.randomness.push(msg.randomness); 83 | 84 | // fix argument 85 | let i = prover_state.round; 86 | let r = prover_state.randomness[i - 1]; 87 | cfg_iter_mut!(prover_state.flattened_ml_extensions).for_each(|multiplicand| { 88 | *multiplicand = multiplicand.fix_variables(&[r]); 89 | }); 90 | } else if prover_state.round > 0 { 91 | panic!("verifier message is empty"); 92 | } 93 | 94 | prover_state.round += 1; 95 | 96 | if prover_state.round > prover_state.num_vars { 97 | panic!("Prover is not active"); 98 | } 99 | 100 | let i = prover_state.round; 101 | let nv = prover_state.num_vars; 102 | let degree = prover_state.max_multiplicands; // the degree of univariate polynomial sent by prover at this round 103 | 104 | #[cfg(not(feature = "parallel"))] 105 | let zeros = (vec![F::zero(); degree + 1], vec![F::zero(); degree + 1]); 106 | #[cfg(feature = "parallel")] 107 | let zeros = || (vec![F::zero(); degree + 1], vec![F::zero(); degree + 1]); 108 | 109 | // generate sum 110 | let fold_result = ark_std::cfg_into_iter!(0..1 << (nv - i), 1 << 10).fold( 111 | zeros, 112 | |(mut products_sum, mut product), b| { 113 | // In effect, this fold is essentially doing simply: 114 | // for b in 0..1 << (nv - i) { 115 | for (coefficient, products) in &prover_state.list_of_products { 116 | product.fill(*coefficient); 117 | for &jth_product in products { 118 | let table = &prover_state.flattened_ml_extensions[jth_product]; 119 | let mut start = table[b << 1]; 120 | let step = table[(b << 1) + 1] - start; 121 | for p in product.iter_mut() { 122 | *p *= start; 123 | start += step; 124 | } 125 | } 126 | for t in 0..degree + 1 { 127 | products_sum[t] += product[t]; 128 | } 129 | } 130 | (products_sum, product) 131 | }, 132 | ); 133 | 134 | #[cfg(not(feature = "parallel"))] 135 | let products_sum = fold_result.0; 136 | 137 | // When rayon is used, the `fold` operation results in a iterator of `Vec` rather than a single `Vec`. In this case, we simply need to sum them. 138 | #[cfg(feature = "parallel")] 139 | let products_sum = fold_result.map(|scratch| scratch.0).reduce( 140 | || vec![F::zero(); degree + 1], 141 | |mut overall_products_sum, sublist_sum| { 142 | overall_products_sum 143 | .iter_mut() 144 | .zip(sublist_sum.iter()) 145 | .for_each(|(f, s)| *f += s); 146 | overall_products_sum 147 | }, 148 | ); 149 | 150 | ProverMsg { 151 | evaluations: products_sum, 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /src/ml_sumcheck/protocol/verifier.rs: -------------------------------------------------------------------------------- 1 | //! Verifier 2 | use crate::ml_sumcheck::data_structures::PolynomialInfo; 3 | use crate::ml_sumcheck::protocol::prover::ProverMsg; 4 | use crate::ml_sumcheck::protocol::IPForMLSumcheck; 5 | use ark_ff::Field; 6 | use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; 7 | use ark_std::rand::RngCore; 8 | use ark_std::vec::Vec; 9 | 10 | #[derive(Clone, CanonicalSerialize, CanonicalDeserialize)] 11 | /// Verifier Message 12 | pub struct VerifierMsg { 13 | /// randomness sampled by verifier 14 | pub randomness: F, 15 | } 16 | 17 | /// Verifier State 18 | pub struct VerifierState { 19 | round: usize, 20 | nv: usize, 21 | max_multiplicands: usize, 22 | finished: bool, 23 | /// a list storing the univariate polynomial in evaluation form sent by the prover at each round 24 | polynomials_received: Vec>, 25 | /// a list storing the randomness sampled by the verifier at each round 26 | randomness: Vec, 27 | } 28 | /// Subclaim when verifier is convinced 29 | pub struct SubClaim { 30 | /// the multi-dimensional point that this multilinear extension is evaluated to 31 | pub point: Vec, 32 | /// the expected evaluation 33 | pub expected_evaluation: F, 34 | } 35 | 36 | impl IPForMLSumcheck { 37 | /// initialize the verifier 38 | pub fn verifier_init(index_info: &PolynomialInfo) -> VerifierState { 39 | VerifierState { 40 | round: 1, 41 | nv: index_info.num_variables, 42 | max_multiplicands: index_info.max_multiplicands, 43 | finished: false, 44 | polynomials_received: Vec::with_capacity(index_info.num_variables), 45 | randomness: Vec::with_capacity(index_info.num_variables), 46 | } 47 | } 48 | 49 | /// Run verifier at current round, given prover message 50 | /// 51 | /// Normally, this function should perform actual verification. Instead, `verify_round` only samples 52 | /// and stores randomness and perform verifications altogether in `check_and_generate_subclaim` at 53 | /// the last step. 54 | pub fn verify_round( 55 | prover_msg: ProverMsg, 56 | verifier_state: &mut VerifierState, 57 | rng: &mut R, 58 | ) -> Option> { 59 | if verifier_state.finished { 60 | panic!("Incorrect verifier state: Verifier is already finished."); 61 | } 62 | 63 | // Now, verifier should check if the received P(0) + P(1) = expected. The check is moved to 64 | // `check_and_generate_subclaim`, and will be done after the last round. 65 | 66 | let msg = Self::sample_round(rng); 67 | verifier_state.randomness.push(msg.randomness); 68 | verifier_state 69 | .polynomials_received 70 | .push(prover_msg.evaluations); 71 | 72 | // Now, verifier should set `expected` to P(r). 73 | // This operation is also moved to `check_and_generate_subclaim`, 74 | // and will be done after the last round. 75 | 76 | if verifier_state.round == verifier_state.nv { 77 | // accept and close 78 | verifier_state.finished = true; 79 | } else { 80 | verifier_state.round += 1; 81 | } 82 | Some(msg) 83 | } 84 | 85 | /// verify the sumcheck phase, and generate the subclaim 86 | /// 87 | /// If the asserted sum is correct, then the multilinear polynomial evaluated at `subclaim.point` 88 | /// is `subclaim.expected_evaluation`. Otherwise, it is highly unlikely that those two will be equal. 89 | /// Larger field size guarantees smaller soundness error. 90 | pub fn check_and_generate_subclaim( 91 | verifier_state: VerifierState, 92 | asserted_sum: F, 93 | ) -> Result, crate::Error> { 94 | if !verifier_state.finished { 95 | panic!("Verifier has not finished."); 96 | } 97 | 98 | let mut expected = asserted_sum; 99 | if verifier_state.polynomials_received.len() != verifier_state.nv { 100 | panic!("insufficient rounds"); 101 | } 102 | for i in 0..verifier_state.nv { 103 | let evaluations = &verifier_state.polynomials_received[i]; 104 | if evaluations.len() != verifier_state.max_multiplicands + 1 { 105 | panic!("incorrect number of evaluations"); 106 | } 107 | let p0 = evaluations[0]; 108 | let p1 = evaluations[1]; 109 | if p0 + p1 != expected { 110 | return Err(crate::Error::Reject(Some( 111 | "Prover message is not consistent with the claim.".into(), 112 | ))); 113 | } 114 | expected = interpolate_uni_poly(evaluations, verifier_state.randomness[i]); 115 | } 116 | 117 | Ok(SubClaim { 118 | point: verifier_state.randomness, 119 | expected_evaluation: expected, 120 | }) 121 | } 122 | 123 | /// simulate a verifier message without doing verification 124 | /// 125 | /// Given the same calling context, `random_oracle_round` output exactly the same message as 126 | /// `verify_round` 127 | #[inline] 128 | pub fn sample_round(rng: &mut R) -> VerifierMsg { 129 | VerifierMsg { 130 | randomness: F::rand(rng), 131 | } 132 | } 133 | } 134 | 135 | /// interpolate the *unique* univariate polynomial of degree *at most* 136 | /// p_i.len()-1 passing through the y-values in p_i at x = 0,..., p_i.len()-1 137 | /// and evaluate this polynomial at `eval_at`. In other words, efficiently compute 138 | /// \sum_{i=0}^{len p_i - 1} p_i[i] * (\prod_{j!=i} (eval_at - j)/(i-j)) 139 | pub(crate) fn interpolate_uni_poly(p_i: &[F], eval_at: F) -> F { 140 | let len = p_i.len(); 141 | 142 | let mut evals = vec![]; 143 | 144 | let mut prod = eval_at; 145 | evals.push(eval_at); 146 | 147 | //`prod = \prod_{j} (eval_at - j)` 148 | // we return early if 0 <= eval_at < len, i.e. if the desired value has been passed 149 | let mut check = F::zero(); 150 | for i in 1..len { 151 | if eval_at == check { 152 | return p_i[i - 1]; 153 | } 154 | check += F::one(); 155 | 156 | let tmp = eval_at - check; 157 | evals.push(tmp); 158 | prod *= tmp; 159 | } 160 | 161 | if eval_at == check { 162 | return p_i[len - 1]; 163 | } 164 | 165 | let mut res = F::zero(); 166 | // we want to compute \prod (j!=i) (i-j) for a given i 167 | // 168 | // we start from the last step, which is 169 | // denom[len-1] = (len-1) * (len-2) *... * 2 * 1 170 | // the step before that is 171 | // denom[len-2] = (len-2) * (len-3) * ... * 2 * 1 * -1 172 | // and the step before that is 173 | // denom[len-3] = (len-3) * (len-4) * ... * 2 * 1 * -1 * -2 174 | // 175 | // i.e., for any i, the one before this will be derived from 176 | // denom[i-1] = - denom[i] * (len-i) / i 177 | // 178 | // that is, we only need to store 179 | // - the last denom for i = len-1, and 180 | // - the ratio between the current step and the last step, which is the 181 | // product of -(len-i) / i from all previous steps and we store 182 | // this product as a fraction number to reduce field divisions. 183 | 184 | // We know 185 | // - 2^61 < factorial(20) < 2^62 186 | // - 2^122 < factorial(33) < 2^123 187 | // so we will be able to compute the ratio 188 | // - for len <= 20 with i64 189 | // - for len <= 33 with i128 190 | // - for len > 33 with BigInt 191 | if p_i.len() <= 20 { 192 | let last_denom = F::from(u64_factorial(len - 1)); 193 | let mut ratio_numerator = 1i64; 194 | let mut ratio_enumerator = 1u64; 195 | 196 | for i in (0..len).rev() { 197 | let ratio_numerator_f = if ratio_numerator < 0 { 198 | -F::from((-ratio_numerator) as u64) 199 | } else { 200 | F::from(ratio_numerator as u64) 201 | }; 202 | 203 | res += p_i[i] * prod * F::from(ratio_enumerator) 204 | / (last_denom * ratio_numerator_f * evals[i]); 205 | 206 | // compute ratio for the next step which is current_ratio * -(len-i)/i 207 | if i != 0 { 208 | ratio_numerator *= -(len as i64 - i as i64); 209 | ratio_enumerator *= i as u64; 210 | } 211 | } 212 | } else if p_i.len() <= 33 { 213 | let last_denom = F::from(u128_factorial(len - 1)); 214 | let mut ratio_numerator = 1i128; 215 | let mut ratio_enumerator = 1u128; 216 | 217 | for i in (0..len).rev() { 218 | let ratio_numerator_f = if ratio_numerator < 0 { 219 | -F::from((-ratio_numerator) as u128) 220 | } else { 221 | F::from(ratio_numerator as u128) 222 | }; 223 | 224 | res += p_i[i] * prod * F::from(ratio_enumerator) 225 | / (last_denom * ratio_numerator_f * evals[i]); 226 | 227 | // compute ratio for the next step which is current_ratio * -(len-i)/i 228 | if i != 0 { 229 | ratio_numerator *= -(len as i128 - i as i128); 230 | ratio_enumerator *= i as u128; 231 | } 232 | } 233 | } else { 234 | // since we are using field operations, we can merge 235 | // `last_denom` and `ratio_numerator` into a single field element. 236 | let mut denom_up = field_factorial::(len - 1); 237 | let mut denom_down = F::one(); 238 | 239 | for i in (0..len).rev() { 240 | res += p_i[i] * prod * denom_down / (denom_up * evals[i]); 241 | 242 | // compute denom for the next step is -current_denom * (len-i)/i 243 | if i != 0 { 244 | denom_up *= -F::from((len - i) as u64); 245 | denom_down *= F::from(i as u64); 246 | } 247 | } 248 | } 249 | 250 | res 251 | } 252 | 253 | /// compute the factorial(a) = 1 * 2 * ... * a 254 | #[inline] 255 | fn field_factorial(a: usize) -> F { 256 | let mut res = F::one(); 257 | for i in 1..=a { 258 | res *= F::from(i as u64); 259 | } 260 | res 261 | } 262 | 263 | /// compute the factorial(a) = 1 * 2 * ... * a 264 | #[inline] 265 | fn u128_factorial(a: usize) -> u128 { 266 | let mut res = 1u128; 267 | for i in 1..=a { 268 | res *= i as u128; 269 | } 270 | res 271 | } 272 | 273 | /// compute the factorial(a) = 1 * 2 * ... * a 274 | #[inline] 275 | fn u64_factorial(a: usize) -> u64 { 276 | let mut res = 1u64; 277 | for i in 1..=a { 278 | res *= i as u64; 279 | } 280 | res 281 | } 282 | 283 | #[cfg(test)] 284 | mod test { 285 | use crate::ml_sumcheck::protocol::verifier::interpolate_uni_poly; 286 | use ark_poly::univariate::DensePolynomial; 287 | use ark_poly::DenseUVPolynomial; 288 | use ark_poly::Polynomial; 289 | use ark_std::vec::Vec; 290 | use ark_std::UniformRand; 291 | 292 | type F = ark_test_curves::bls12_381::Fr; 293 | 294 | #[test] 295 | fn test_interpolation() { 296 | let mut prng = ark_std::test_rng(); 297 | 298 | // test a polynomial with 20 known points, i.e., with degree 19 299 | let poly = DensePolynomial::::rand(20 - 1, &mut prng); 300 | let evals = (0..20) 301 | .map(|i| poly.evaluate(&F::from(i))) 302 | .collect::>(); 303 | let query = F::rand(&mut prng); 304 | 305 | assert_eq!(poly.evaluate(&query), interpolate_uni_poly(&evals, query)); 306 | 307 | // test a polynomial with 33 known points, i.e., with degree 32 308 | let poly = DensePolynomial::::rand(33 - 1, &mut prng); 309 | let evals = (0..33) 310 | .map(|i| poly.evaluate(&F::from(i))) 311 | .collect::>(); 312 | let query = F::rand(&mut prng); 313 | 314 | assert_eq!(poly.evaluate(&query), interpolate_uni_poly(&evals, query)); 315 | 316 | // test a polynomial with 64 known points, i.e., with degree 63 317 | let poly = DensePolynomial::::rand(64 - 1, &mut prng); 318 | let evals = (0..64) 319 | .map(|i| poly.evaluate(&F::from(i))) 320 | .collect::>(); 321 | let query = F::rand(&mut prng); 322 | 323 | assert_eq!(poly.evaluate(&query), interpolate_uni_poly(&evals, query)); 324 | 325 | // test interpolation when we ask for the value at an x-cordinate 326 | // we are already passing, i.e. in the range 0 <= x < len(values) - 1 327 | let evals = vec![0, 1, 4, 9] 328 | .into_iter() 329 | .map(|i| F::from(i)) 330 | .collect::>(); 331 | assert_eq!(interpolate_uni_poly(&evals, F::from(3)), F::from(9)); 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /src/ml_sumcheck/test.rs: -------------------------------------------------------------------------------- 1 | use crate::ml_sumcheck::data_structures::ListOfProductsOfPolynomials; 2 | use crate::ml_sumcheck::protocol::IPForMLSumcheck; 3 | use crate::ml_sumcheck::MLSumcheck; 4 | use crate::rng::Blake2b512Rng; 5 | use crate::rng::FeedableRNG; 6 | use ark_ff::Field; 7 | use ark_poly::{DenseMultilinearExtension, MultilinearExtension}; 8 | use ark_std::rand::Rng; 9 | use ark_std::rand::RngCore; 10 | use ark_std::rc::Rc; 11 | use ark_std::vec::Vec; 12 | use ark_std::{test_rng, UniformRand}; 13 | use ark_test_curves::bls12_381::Fr; 14 | 15 | fn random_product( 16 | nv: usize, 17 | num_multiplicands: usize, 18 | rng: &mut R, 19 | ) -> (Vec>>, F) { 20 | let mut multiplicands = Vec::with_capacity(num_multiplicands); 21 | for _ in 0..num_multiplicands { 22 | multiplicands.push(Vec::with_capacity(1 << nv)) 23 | } 24 | let mut sum = F::zero(); 25 | 26 | for _ in 0..(1 << nv) { 27 | let mut product = F::one(); 28 | for multiplicand in &mut multiplicands { 29 | let val = F::rand(rng); 30 | multiplicand.push(val); 31 | product *= val; 32 | } 33 | sum += product; 34 | } 35 | 36 | ( 37 | multiplicands 38 | .into_iter() 39 | .map(|x| Rc::new(DenseMultilinearExtension::from_evaluations_vec(nv, x))) 40 | .collect(), 41 | sum, 42 | ) 43 | } 44 | 45 | fn random_list_of_products( 46 | nv: usize, 47 | num_multiplicands_range: (usize, usize), 48 | num_products: usize, 49 | rng: &mut R, 50 | ) -> (ListOfProductsOfPolynomials, F) { 51 | let mut sum = F::zero(); 52 | let mut poly = ListOfProductsOfPolynomials::new(nv); 53 | for _ in 0..num_products { 54 | let num_multiplicands = rng.gen_range(num_multiplicands_range.0..num_multiplicands_range.1); 55 | let (product, product_sum) = random_product(nv, num_multiplicands, rng); 56 | let coefficient = F::rand(rng); 57 | poly.add_product(product.into_iter(), coefficient); 58 | sum += product_sum * coefficient; 59 | } 60 | 61 | (poly, sum) 62 | } 63 | 64 | fn test_polynomial(nv: usize, num_multiplicands_range: (usize, usize), num_products: usize) { 65 | let mut rng = test_rng(); 66 | let (poly, asserted_sum) = 67 | random_list_of_products::(nv, num_multiplicands_range, num_products, &mut rng); 68 | let poly_info = poly.info(); 69 | let proof = MLSumcheck::prove(&poly).expect("fail to prove"); 70 | let subclaim = MLSumcheck::verify(&poly_info, asserted_sum, &proof).expect("fail to verify"); 71 | assert!( 72 | poly.evaluate(&subclaim.point) == subclaim.expected_evaluation, 73 | "wrong subclaim" 74 | ); 75 | } 76 | 77 | fn test_protocol(nv: usize, num_multiplicands_range: (usize, usize), num_products: usize) { 78 | let mut rng = test_rng(); 79 | let (poly, asserted_sum) = 80 | random_list_of_products::(nv, num_multiplicands_range, num_products, &mut rng); 81 | let poly_info = poly.info(); 82 | let mut prover_state = IPForMLSumcheck::prover_init(&poly); 83 | let mut verifier_state = IPForMLSumcheck::verifier_init(&poly_info); 84 | let mut verifier_msg = None; 85 | for _ in 0..poly.num_variables { 86 | let prover_message = IPForMLSumcheck::prove_round(&mut prover_state, &verifier_msg); 87 | let verifier_msg2 = 88 | IPForMLSumcheck::verify_round(prover_message, &mut verifier_state, &mut rng); 89 | verifier_msg = verifier_msg2; 90 | } 91 | let subclaim = IPForMLSumcheck::check_and_generate_subclaim(verifier_state, asserted_sum) 92 | .expect("fail to generate subclaim"); 93 | assert!( 94 | poly.evaluate(&subclaim.point) == subclaim.expected_evaluation, 95 | "wrong subclaim" 96 | ); 97 | } 98 | 99 | fn test_polynomial_as_subprotocol( 100 | nv: usize, 101 | num_multiplicands_range: (usize, usize), 102 | num_products: usize, 103 | prover_rng: &mut impl FeedableRNG, 104 | verifier_rng: &mut impl FeedableRNG, 105 | ) { 106 | let mut rng = test_rng(); 107 | let (poly, asserted_sum) = 108 | random_list_of_products::(nv, num_multiplicands_range, num_products, &mut rng); 109 | let poly_info = poly.info(); 110 | let (proof, prover_state) = 111 | MLSumcheck::prove_as_subprotocol(prover_rng, &poly).expect("fail to prove"); 112 | let subclaim = 113 | MLSumcheck::verify_as_subprotocol(verifier_rng, &poly_info, asserted_sum, &proof) 114 | .expect("fail to verify"); 115 | assert!( 116 | poly.evaluate(&subclaim.point) == subclaim.expected_evaluation, 117 | "wrong subclaim" 118 | ); 119 | assert_eq!(prover_state.randomness, subclaim.point); 120 | } 121 | 122 | #[test] 123 | fn test_trivial_polynomial() { 124 | let nv = 1; 125 | let num_multiplicands_range = (4, 13); 126 | let num_products = 5; 127 | 128 | for _ in 0..10 { 129 | test_polynomial(nv, num_multiplicands_range, num_products); 130 | test_protocol(nv, num_multiplicands_range, num_products); 131 | 132 | let mut prover_rng = Blake2b512Rng::setup(); 133 | prover_rng.feed(b"Test Trivial Works").unwrap(); 134 | let mut verifier_rng = Blake2b512Rng::setup(); 135 | verifier_rng.feed(b"Test Trivial Works").unwrap(); 136 | test_polynomial_as_subprotocol( 137 | nv, 138 | num_multiplicands_range, 139 | num_products, 140 | &mut prover_rng, 141 | &mut verifier_rng, 142 | ) 143 | } 144 | } 145 | #[test] 146 | fn test_normal_polynomial() { 147 | let nv = 12; 148 | let num_multiplicands_range = (4, 9); 149 | let num_products = 5; 150 | 151 | for _ in 0..10 { 152 | test_polynomial(nv, num_multiplicands_range, num_products); 153 | test_protocol(nv, num_multiplicands_range, num_products); 154 | 155 | let mut prover_rng = Blake2b512Rng::setup(); 156 | prover_rng.feed(b"Test Trivial Works").unwrap(); 157 | let mut verifier_rng = Blake2b512Rng::setup(); 158 | verifier_rng.feed(b"Test Trivial Works").unwrap(); 159 | test_polynomial_as_subprotocol( 160 | nv, 161 | num_multiplicands_range, 162 | num_products, 163 | &mut prover_rng, 164 | &mut verifier_rng, 165 | ) 166 | } 167 | } 168 | #[test] 169 | #[should_panic] 170 | fn test_normal_polynomial_different_transcripts_fails() { 171 | let nv = 12; 172 | let num_multiplicands_range = (4, 9); 173 | let num_products = 5; 174 | 175 | let mut prover_rng = Blake2b512Rng::setup(); 176 | prover_rng.feed(b"Test Trivial Works").unwrap(); 177 | let mut verifier_rng = Blake2b512Rng::setup(); 178 | verifier_rng.feed(b"Test Trivial Fails").unwrap(); 179 | test_polynomial_as_subprotocol( 180 | nv, 181 | num_multiplicands_range, 182 | num_products, 183 | &mut prover_rng, 184 | &mut verifier_rng, 185 | ) 186 | } 187 | #[test] 188 | #[should_panic] 189 | fn zero_polynomial_should_error() { 190 | let nv = 0; 191 | let num_multiplicands_range = (4, 13); 192 | let num_products = 5; 193 | 194 | test_polynomial(nv, num_multiplicands_range, num_products); 195 | } 196 | #[test] 197 | #[should_panic] 198 | fn zero_polynomial_protocol_should_error() { 199 | let nv = 0; 200 | let num_multiplicands_range = (4, 13); 201 | let num_products = 5; 202 | 203 | test_protocol(nv, num_multiplicands_range, num_products); 204 | } 205 | 206 | #[test] 207 | fn test_extract_sum() { 208 | let mut rng = test_rng(); 209 | let (poly, asserted_sum) = random_list_of_products::(8, (3, 4), 3, &mut rng); 210 | 211 | let proof = MLSumcheck::prove(&poly).expect("fail to prove"); 212 | assert_eq!(MLSumcheck::extract_sum(&proof), asserted_sum); 213 | } 214 | 215 | #[test] 216 | /// Test that the memory usage of shared-reference is linear to number of unique MLExtensions 217 | /// instead of total number of multiplicands. 218 | fn test_shared_reference() { 219 | let mut rng = test_rng(); 220 | let ml_extensions: Vec<_> = (0..5) 221 | .map(|_| Rc::new(DenseMultilinearExtension::::rand(8, &mut rng))) 222 | .collect(); 223 | let mut poly = ListOfProductsOfPolynomials::new(8); 224 | poly.add_product( 225 | vec![ 226 | ml_extensions[2].clone(), 227 | ml_extensions[3].clone(), 228 | ml_extensions[0].clone(), 229 | ], 230 | Fr::rand(&mut rng), 231 | ); 232 | poly.add_product( 233 | vec![ 234 | ml_extensions[1].clone(), 235 | ml_extensions[4].clone(), 236 | ml_extensions[4].clone(), 237 | ], 238 | Fr::rand(&mut rng), 239 | ); 240 | poly.add_product( 241 | vec![ 242 | ml_extensions[3].clone(), 243 | ml_extensions[2].clone(), 244 | ml_extensions[1].clone(), 245 | ], 246 | Fr::rand(&mut rng), 247 | ); 248 | poly.add_product( 249 | vec![ml_extensions[0].clone(), ml_extensions[0].clone()], 250 | Fr::rand(&mut rng), 251 | ); 252 | poly.add_product(vec![ml_extensions[4].clone()], Fr::rand(&mut rng)); 253 | 254 | assert_eq!(poly.flattened_ml_extensions.len(), 5); 255 | 256 | // test memory usage for prover 257 | let prover = IPForMLSumcheck::prover_init(&poly); 258 | assert_eq!(prover.flattened_ml_extensions.len(), 5); 259 | drop(prover); 260 | 261 | let poly_info = poly.info(); 262 | let proof = MLSumcheck::prove(&poly).expect("fail to prove"); 263 | let asserted_sum = MLSumcheck::extract_sum(&proof); 264 | let subclaim = MLSumcheck::verify(&poly_info, asserted_sum, &proof).expect("fail to verify"); 265 | assert!( 266 | poly.evaluate(&subclaim.point) == subclaim.expected_evaluation, 267 | "wrong subclaim" 268 | ); 269 | } 270 | -------------------------------------------------------------------------------- /src/rng.rs: -------------------------------------------------------------------------------- 1 | //! Fiat-Shamir Random Generator 2 | use ark_serialize::CanonicalSerialize; 3 | use ark_std::rand::RngCore; 4 | use ark_std::vec::Vec; 5 | use blake2::{Blake2b512, Digest}; 6 | /// Random Field Element Generator where randomness `feed` adds entropy for the output. 7 | /// 8 | /// Implementation should support all types of input that has `ToBytes` trait. 9 | /// 10 | /// Same sequence of `feed` and `get` call should yield same result! 11 | pub trait FeedableRNG: RngCore { 12 | /// Error type 13 | type Error: ark_std::error::Error + From; 14 | /// Setup should not have any parameter. 15 | fn setup() -> Self; 16 | 17 | /// Provide randomness for the generator, given the message. 18 | fn feed(&mut self, msg: &M) -> Result<(), Self::Error>; 19 | } 20 | 21 | /// 512-bits digest hash pseudorandom generator 22 | pub struct Blake2b512Rng { 23 | /// current digest instance 24 | current_digest: Blake2b512, 25 | } 26 | 27 | impl FeedableRNG for Blake2b512Rng { 28 | type Error = crate::Error; 29 | 30 | fn setup() -> Self { 31 | Self { 32 | current_digest: Blake2b512::new(), 33 | } 34 | } 35 | 36 | fn feed(&mut self, msg: &M) -> Result<(), Self::Error> { 37 | let mut buf = Vec::new(); 38 | msg.serialize_uncompressed(&mut buf)?; 39 | self.current_digest.update(&buf); 40 | Ok(()) 41 | } 42 | } 43 | 44 | impl RngCore for Blake2b512Rng { 45 | fn next_u32(&mut self) -> u32 { 46 | let mut temp = [0u8; 4]; 47 | self.fill_bytes(&mut temp); 48 | u32::from_le_bytes(temp) 49 | } 50 | 51 | fn next_u64(&mut self) -> u64 { 52 | let mut temp = [0u8; 8]; 53 | self.fill_bytes(&mut temp); 54 | u64::from_le_bytes(temp) 55 | } 56 | 57 | fn fill_bytes(&mut self, dest: &mut [u8]) { 58 | self.try_fill_bytes(dest).unwrap() 59 | } 60 | 61 | fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), ark_std::rand::Error> { 62 | let mut digest = self.current_digest.clone(); 63 | let mut output = digest.finalize(); 64 | let output_size = Blake2b512::output_size(); 65 | let mut ptr = 0; 66 | let mut digest_ptr = 0; 67 | while ptr < dest.len() { 68 | dest[ptr] = output[digest_ptr]; 69 | ptr += 1usize; 70 | digest_ptr += 1; 71 | if digest_ptr == output_size { 72 | self.current_digest.update(output); 73 | digest = self.current_digest.clone(); 74 | output = digest.finalize(); 75 | digest_ptr = 0; 76 | } 77 | } 78 | self.current_digest.update(output); 79 | Ok(()) 80 | } 81 | } 82 | 83 | #[cfg(test)] 84 | mod tests { 85 | use ark_ff::Field; 86 | use ark_std::rand::Rng; 87 | use ark_std::rand::RngCore; 88 | 89 | use crate::rng::{Blake2b512Rng, FeedableRNG}; 90 | use ark_serialize::CanonicalSerialize; 91 | use ark_std::test_rng; 92 | use ark_std::vec::Vec; 93 | use ark_test_curves::bls12_381::Fr; 94 | 95 | /// Special type of input used for test. 96 | #[derive(CanonicalSerialize)] 97 | struct TestMessage { 98 | data: Vec, 99 | } 100 | 101 | impl TestMessage { 102 | fn rand(rng: &mut R, size: usize) -> TestMessage { 103 | let mut data = Vec::with_capacity(size); 104 | data.resize_with(size, || rng.gen()); 105 | TestMessage { data } 106 | } 107 | } 108 | 109 | /// Test that same sequence of `feed` and `get` call should yield same result. 110 | /// 111 | /// * `rng_test`: the pseudorandom RNG to be tested 112 | /// * `num_iterations`: number of independent tests 113 | fn test_deterministic_pseudorandom_generator(num_iterations: u32) 114 | where 115 | F: Field, 116 | G: FeedableRNG, 117 | { 118 | let mut rng = test_rng(); 119 | for _ in 0..num_iterations { 120 | // generate write messages 121 | let mut msgs = Vec::with_capacity(7); 122 | msgs.resize_with(7, || TestMessage::rand(&mut rng, 128)); 123 | 124 | let rw_sequence = |r: &mut G, o: &mut Vec| { 125 | r.feed(&msgs[0]).unwrap(); 126 | o.push(F::rand(r)); 127 | o.push(F::rand(r)); 128 | r.feed(&msgs[1]).unwrap(); 129 | r.feed(&msgs[2]).unwrap(); 130 | o.push(F::rand(r)); 131 | r.feed(&msgs[3]).unwrap(); 132 | o.push(F::rand(r)); 133 | o.push(F::rand(r)); 134 | r.feed(&msgs[4]).unwrap(); 135 | r.feed(&msgs[5]).unwrap(); 136 | r.feed(&msgs[6]).unwrap(); 137 | let f1 = F::rand(r); 138 | o.push(f1); 139 | let f2 = F::rand(r); 140 | o.push(f2); 141 | assert_ne!(f1, f2, "Producing same element"); 142 | o.push(F::rand(r)); 143 | o.push(F::rand(r)); 144 | // edge case: not aligned bytes 145 | let mut buf1 = [0u8; 127]; 146 | let mut buf2 = [0u8; 128]; 147 | let mut buf3 = [0u8; 777]; 148 | r.fill_bytes(&mut buf1); 149 | r.feed(&buf1.to_vec()).unwrap(); 150 | r.fill_bytes(&mut buf2); 151 | r.fill_bytes(&mut buf3); 152 | assert_ne!(&buf2[..64], &buf3[..64]); 153 | o.push(F::rand(r)); 154 | r.feed(&buf3.to_vec()).unwrap(); 155 | o.push(F::rand(r)); 156 | }; 157 | let mut rng_test = G::setup(); 158 | let mut random_output = Vec::with_capacity(8); 159 | 160 | rw_sequence(&mut rng_test, &mut random_output); 161 | 162 | // test that it is deterministic 163 | for _ in 0..10 { 164 | let mut another_rng_test = G::setup(); 165 | let mut another_random_output = Vec::with_capacity(8); 166 | rw_sequence(&mut another_rng_test, &mut another_random_output); 167 | assert_eq!(random_output, another_random_output); 168 | } 169 | } 170 | } 171 | 172 | #[test] 173 | fn test_blake2s_hashing() { 174 | test_deterministic_pseudorandom_generator::(5) 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /sumcheck-benches/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sumcheck-benches" 3 | version = "0.3.0" 4 | authors = [ 5 | "Tom Shen ", 6 | "arkworks contributors" 7 | ] 8 | description = "Benchmarks for ark-linear-sumcheck" 9 | homepage = "https://arkworks.rs" 10 | repository = "https://github.com/arkworks-rs/sumcheck/" 11 | keywords = ["cryptography", "finite-fields", "polynomials", "sumcheck"] 12 | categories = ["cryptography"] 13 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 14 | license = "MIT/Apache-2.0" 15 | publish = false 16 | edition = "2018" 17 | 18 | [dependencies] 19 | ark-ff = { version = "^0.3.0", default-features = false } 20 | ark-std = { version = "^0.3.0", default-features = false } 21 | ark-poly = { version = "^0.3.0", default-features = false } 22 | blake2 = { version = "0.9", default-features = false } 23 | ark-test-curves = { version = "^0.3.0", default-features = false, features = ["bls12_381_scalar_field", "bls12_381_curve"] } 24 | 25 | criterion = { version = "0.3.1" } 26 | ark-linear-sumcheck = { path = "../" } 27 | rayon = { version = "1", optional = true } 28 | 29 | [features] 30 | default = [ "std" ] 31 | std = ["ark-ff/std", "ark-std/std", "ark-poly/std"] 32 | parallel = ["std", "ark-ff/parallel", "ark-poly/parallel", "ark-std/parallel", "rayon"] 33 | 34 | [[bench]] 35 | name = "ml_sumcheck" 36 | path = "benches/ml_sumcheck_bench.rs" 37 | harness = false 38 | 39 | [[bench]] 40 | name = "gkr_round_sumcheck" 41 | path = "benches/gkr_round_sumcheck_bench.rs" 42 | harness = false 43 | 44 | # To be removed in the new release. 45 | [patch.crates-io] 46 | ark-ec = { git = "https://github.com/arkworks-rs/algebra" } 47 | ark-ff = { git = "https://github.com/arkworks-rs/algebra" } 48 | ark-poly = { git = "https://github.com/arkworks-rs/algebra" } 49 | ark-serialize = { git = "https://github.com/arkworks-rs/algebra" } 50 | ark-test-curves = { git = "https://github.com/arkworks-rs/algebra" } 51 | ark-std = { git = "https://github.com/arkworks-rs/std" } -------------------------------------------------------------------------------- /sumcheck-benches/benches/gkr_round_sumcheck_bench.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate criterion; 3 | 4 | use ark_ff::Field; 5 | use ark_linear_sumcheck::{ 6 | gkr_round_sumcheck::GKRRoundSumcheck, 7 | rng::{Blake2s512Rng, FeedableRNG}, 8 | }; 9 | use ark_poly::{DenseMultilinearExtension, MultilinearExtension, SparseMultilinearExtension}; 10 | use ark_std::ops::Range; 11 | use criterion::{black_box, BenchmarkId, Criterion}; 12 | 13 | const NUM_VARIABLES_RANGE: Range = 10..21; 14 | 15 | fn prove_bench(c: &mut Criterion) { 16 | let mut rng = Blake2s512Rng::setup(); 17 | 18 | let mut group = c.benchmark_group("Prove"); 19 | for nv in NUM_VARIABLES_RANGE { 20 | group.bench_with_input(BenchmarkId::new("GKR", nv), &nv, |b, &nv| { 21 | let f1 = SparseMultilinearExtension::rand_with_config(3 * nv, 1 << nv, &mut rng); 22 | let f2 = DenseMultilinearExtension::rand(nv, &mut rng); 23 | let f3 = DenseMultilinearExtension::rand(nv, &mut rng); 24 | let g: Vec<_> = (0..nv).map(|_| F::rand(&mut rng)).collect(); 25 | b.iter(|| { 26 | GKRRoundSumcheck::prove( 27 | &mut rng, 28 | black_box(&f1), 29 | black_box(&f2), 30 | black_box(&f3), 31 | black_box(&g), 32 | ) 33 | }); 34 | }); 35 | } 36 | } 37 | 38 | fn verify_bench(c: &mut Criterion) { 39 | let mut rng = Blake2s512Rng::setup(); 40 | 41 | let mut group = c.benchmark_group("Verify"); 42 | for nv in NUM_VARIABLES_RANGE { 43 | group.bench_with_input(BenchmarkId::new("GKR", nv), &nv, |b, &nv| { 44 | let f1 = SparseMultilinearExtension::rand_with_config(3 * nv, 1 << nv, &mut rng); 45 | let f2 = DenseMultilinearExtension::rand(nv, &mut rng); 46 | let f3 = DenseMultilinearExtension::rand(nv, &mut rng); 47 | let g: Vec<_> = (0..nv).map(|_| F::rand(&mut rng)).collect(); 48 | let proof = GKRRoundSumcheck::prove(&mut rng, &f1, &f2, &f3, &g); 49 | let expected_sum = proof.extract_sum(); 50 | b.iter(|| GKRRoundSumcheck::verify(&mut rng, f2.num_vars, &proof, expected_sum)); 51 | }); 52 | } 53 | } 54 | 55 | fn bench_bls_381(c: &mut Criterion) { 56 | prove_bench::(c); 57 | verify_bench::(c); 58 | } 59 | 60 | criterion_group!(benches, bench_bls_381); 61 | criterion_main!(benches); 62 | -------------------------------------------------------------------------------- /sumcheck-benches/benches/ml_sumcheck_bench.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate criterion; 3 | 4 | use ark_ff::Field; 5 | use ark_linear_sumcheck::ml_sumcheck::protocol::ListOfProductsOfPolynomials; 6 | use ark_linear_sumcheck::ml_sumcheck::MLSumcheck; 7 | use ark_poly::{DenseMultilinearExtension, MultilinearExtension}; 8 | use ark_std::ops::Range; 9 | use ark_std::rc::Rc; 10 | use ark_std::test_rng; 11 | use criterion::{black_box, BenchmarkId, Criterion}; 12 | 13 | const NUM_VARIABLES_RANGE: Range = 10..21; 14 | 15 | fn prove_bench(c: &mut Criterion) { 16 | let mut rng = test_rng(); 17 | 18 | let mut group = c.benchmark_group("Prove"); 19 | for nv in NUM_VARIABLES_RANGE { 20 | group.bench_with_input(BenchmarkId::new("ML", nv), &nv, |b, &nv| { 21 | let product_1: Vec<_> = (0..3) 22 | .map(|_| Rc::new(DenseMultilinearExtension::::rand(nv, &mut rng))) 23 | .collect(); 24 | let product_2: Vec<_> = (0..3) 25 | .map(|_| Rc::new(DenseMultilinearExtension::::rand(nv, &mut rng))) 26 | .collect(); 27 | let coefficient_1 = F::rand(&mut rng); 28 | let coefficient_2 = F::rand(&mut rng); 29 | let mut products = ListOfProductsOfPolynomials::new(nv); 30 | products.add_product(product_1, coefficient_1); 31 | products.add_product(product_2, coefficient_2); 32 | b.iter(|| MLSumcheck::prove(black_box(&products))); 33 | }); 34 | } 35 | } 36 | 37 | fn verify_bench(c: &mut Criterion) { 38 | let mut rng = test_rng(); 39 | 40 | let mut group = c.benchmark_group("Verify"); 41 | for nv in NUM_VARIABLES_RANGE { 42 | group.bench_with_input(BenchmarkId::new("ML", nv), &nv, |b, &nv| { 43 | let product_1: Vec<_> = (0..3) 44 | .map(|_| Rc::new(DenseMultilinearExtension::::rand(nv, &mut rng))) 45 | .collect(); 46 | let product_2: Vec<_> = (0..3) 47 | .map(|_| Rc::new(DenseMultilinearExtension::::rand(nv, &mut rng))) 48 | .collect(); 49 | let coefficient_1 = F::rand(&mut rng); 50 | let coefficient_2 = F::rand(&mut rng); 51 | // calculate expected sum 52 | let mut products = ListOfProductsOfPolynomials::new(nv); 53 | products.add_product(product_1, coefficient_1); 54 | products.add_product(product_2, coefficient_2); 55 | let proof = MLSumcheck::prove(&products).unwrap(); 56 | let expected_sum = MLSumcheck::extract_sum(&proof); 57 | b.iter(|| { 58 | MLSumcheck::verify(&products.info(), black_box(expected_sum), &proof).unwrap() 59 | }); 60 | }); 61 | } 62 | } 63 | 64 | fn bench_bls_381(c: &mut Criterion) { 65 | prove_bench::(c); 66 | verify_bench::(c); 67 | } 68 | 69 | criterion_group!(benches, bench_bls_381); 70 | criterion_main!(benches); 71 | --------------------------------------------------------------------------------