├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── ci.yml ├── .gitignore ├── .hooks └── pre-commit ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── rustfmt.toml ├── scripts └── install-hook.sh ├── src ├── constraints.rs ├── data_structures.rs ├── generator.rs ├── lib.rs ├── link │ ├── matrix.rs │ ├── mod.rs │ └── snark.rs ├── prover.rs ├── r1cs_to_qap.rs ├── test.rs └── verifier.rs └── tests └── mimc.rs /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us squash bugs! 4 | 5 | --- 6 | 7 | ∂ 12 | 13 | ## Summary of Bug 14 | 15 | 16 | 17 | ## Version 18 | 19 | 20 | 21 | ## Steps to Reproduce 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Create a proposal to request a feature 4 | 5 | --- 6 | 7 | 13 | 14 | ## Summary 15 | 16 | 17 | 18 | ## Problem Definition 19 | 20 | 23 | 24 | ## Proposal 25 | 26 | 27 | 28 | ____ 29 | 30 | #### For Admin Use 31 | 32 | - [ ] Not duplicate issue 33 | - [ ] Appropriate labels applied 34 | - [ ] Appropriate contributors tagged 35 | - [ ] Contributor assigned/self-assigned 36 | -------------------------------------------------------------------------------- /.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 27 | -------------------------------------------------------------------------------- /.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: -- --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 | - uses: actions/cache@v2 54 | with: 55 | path: | 56 | ~/.cargo/registry 57 | ~/.cargo/git 58 | target 59 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 60 | 61 | - name: Check examples 62 | uses: actions-rs/cargo@v1 63 | with: 64 | command: check 65 | args: --examples 66 | 67 | - name: Check examples with all features on stable 68 | uses: actions-rs/cargo@v1 69 | with: 70 | command: check 71 | args: --examples --all-features 72 | if: matrix.rust == 'stable' 73 | 74 | - name: Test 75 | uses: actions-rs/cargo@v1 76 | with: 77 | command: test 78 | args: --all-features 79 | 80 | check_no_std: 81 | name: Check no_std 82 | runs-on: ubuntu-latest 83 | steps: 84 | - name: Checkout 85 | uses: actions/checkout@v2 86 | 87 | - name: Install Rust (${{ matrix.rust }}) 88 | uses: actions-rs/toolchain@v1 89 | with: 90 | toolchain: stable 91 | target: thumbv6m-none-eabi 92 | override: true 93 | 94 | - name: Install Rust ARM64 (${{ matrix.rust }}) 95 | uses: actions-rs/toolchain@v1 96 | with: 97 | toolchain: stable 98 | target: aarch64-unknown-none 99 | override: true 100 | 101 | - uses: actions/cache@v2 102 | with: 103 | path: | 104 | ~/.cargo/registry 105 | ~/.cargo/git 106 | target 107 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 108 | 109 | - name: groth16 110 | run: | 111 | cargo build --no-default-features --target aarch64-unknown-none 112 | cargo check --examples --no-default-features --target aarch64-unknown-none 113 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .DS_Store 4 | .idea 5 | *.iml 6 | *.ipynb_checkpoints 7 | *.pyc 8 | *.sage.py 9 | params 10 | *.swp 11 | *.swo 12 | -------------------------------------------------------------------------------- /.hooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rustfmt --version &>/dev/null 4 | if [ $? != 0 ]; then 5 | printf "[pre_commit] \033[0;31merror\033[0m: \"rustfmt\" not available. \n" 6 | printf "[pre_commit] \033[0;31merror\033[0m: rustfmt can be installed via - \n" 7 | printf "[pre_commit] $ rustup component add rustfmt \n" 8 | exit 1 9 | fi 10 | 11 | problem_files=() 12 | 13 | # collect ill-formatted files 14 | for file in $(git diff --name-only --cached); do 15 | if [ ${file: -3} == ".rs" ]; then 16 | rustfmt +stable --check $file &>/dev/null 17 | if [ $? != 0 ]; then 18 | problem_files+=($file) 19 | fi 20 | fi 21 | done 22 | 23 | if [ ${#problem_files[@]} == 0 ]; then 24 | # done 25 | printf "[pre_commit] rustfmt \033[0;32mok\033[0m \n" 26 | else 27 | # reformat the files that need it and re-stage them. 28 | printf "[pre_commit] the following files were rustfmt'd before commit: \n" 29 | for file in ${problem_files[@]}; do 30 | rustfmt +stable $file 31 | git add $file 32 | printf "\033[0;32m $file\033[0m \n" 33 | done 34 | fi 35 | 36 | exit 0 37 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Sample changelog for maintainers 2 | 3 | ## Pending 4 | 5 | ### Breaking changes 6 | - #4 Change groth16's logic to implement the `SNARK` trait. 7 | - Minimum version on crates from `arkworks-rs/algebra` and `arkworks-rs/curves` is now `v0.2.0` 8 | 9 | ### Features 10 | - #5 Add R1CS constraints for the groth16 verifier. 11 | - #8 Add benchmarks for the prover 12 | - #16 Add proof re-randomization 13 | 14 | ### Improvements 15 | - #9 Improve memory consumption by manually dropping large vectors once they're no longer needed 16 | 17 | ### Bug fixes 18 | - [c9bc5519](https://github.com/arkworks-rs/groth16/commit/885b9b569522f59a7eb428d1095f442ec9bc5519) Fix parallel feature flag 19 | - #22 Compile with `panic='abort'` in release mode, for safety of the library across FFI boundaries. 20 | 21 | ## v0.1.0 22 | 23 | _Initial release_ -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | # NOTE TO MAINTAINERS 3 | # REPLACE `groth16` AND master 4 | 5 | Thank you for considering making contributions to `arkworks-rs/groth16`! 6 | 7 | Contributing to this repo can be done in several forms, such as participating in discussion or proposing code changes. 8 | To ensure a smooth workflow for all contributors, the following general procedure for contributing has been established: 9 | 10 | 1) Either open or find an issue you'd like to help with 11 | 2) Participate in thoughtful discussion on that issue 12 | 3) If you would like to contribute: 13 | * If the issue is a feature proposal, ensure that the proposal has been accepted 14 | * Ensure that nobody else has already begun working on this issue. 15 | If they have, please try to contact them to collaborate 16 | * If nobody has been assigned for the issue and you would like to work on it, make a comment on the issue to inform the community of your intentions to begin work. (So we can avoid duplication of efforts) 17 | * We suggest using standard Github best practices for contributing: fork the repo, branch from the HEAD of master, make some commits on your branch, and submit a PR from the branch to master. 18 | More detail on this is below 19 | * Be sure to include a relevant change log entry in the Pending section of CHANGELOG.md (see file for log format) 20 | * If the change is breaking, we may add migration instructions. 21 | 22 | Note that for very small or clear problems (such as typos), or well isolated improvements, it is not required to an open issue to submit a PR. 23 | But be aware that for more complex problems/features touching multiple parts of the codebase, if a PR is opened before an adequate design discussion has taken place in a github issue, that PR runs a larger likelihood of being rejected. 24 | 25 | Looking for a good place to start contributing? How about checking out some good first issues 26 | 27 | ## Branch Structure 28 | 29 | `groth16` has its default branch as `master`, which is where PRs are merged into. Releases will be periodically made, on no set schedule. 30 | All other branches should be assumed to be miscellaneous feature development branches. 31 | 32 | All downstream users of the library should be using tagged versions of the library pulled from cargo. 33 | 34 | ## How to work on a fork 35 | Please skip this section if you're familiar with contributing to opensource github projects. 36 | 37 | First fork the repo from the github UI, and clone it locally. 38 | Then in the repo, you want to add the repo you forked from as a new remote. You do this as: 39 | ```bash 40 | git remote add upstream git@github.com:arkworks-rs/groth16.git 41 | ``` 42 | 43 | Then the way you make code contributions is to first think of a branch name that describes your change. 44 | Then do the following: 45 | ```bash 46 | git checkout master 47 | git pull upstream master 48 | git checkout -b $BRANCH_NAME 49 | ``` 50 | and then work as normal on that branch, and pull request to upstream master when you're done =) 51 | 52 | ## Updating documentation 53 | 54 | All PRs should aim to leave the code more documented than it started with. 55 | Please don't assume that its easy to infer what the code is doing, 56 | as that is usually not the case for these complex protocols. 57 | (Even when you understand the paper!) 58 | 59 | Its often very useful to describe what is the high level view of what a code block is doing, 60 | and either refer to the relevant section of a paper or include a short proof/argument for why it makes sense before the actual logic. 61 | 62 | ## Performance improvements 63 | 64 | All performance improvements should be accompanied with benchmarks improving, or otherwise have it be clear that things have improved. 65 | For some areas of the codebase, performance roughly follows the number of field multiplications, but there are also many areas where 66 | hard to predict low level system effects such as cache locality and superscalar operations become important for performance. 67 | Thus performance can often become very non-intuitive / diverge from minimizing the number of arithmetic operations. -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "legogro16" 3 | version = "0.1.0" 4 | authors = [ "arkworks contributors" ] 5 | description = "An implementation of the Groth 2016 zkSNARK proof system" 6 | homepage = "https://arkworks.rs" 7 | repository = "https://github.com/arkworks-rs/groth16" 8 | documentation = "https://docs.rs/ark-groth16/" 9 | keywords = [ "zero knowledge", "cryptography", "zkSNARK", "SNARK", "Groth-Maller" ] 10 | categories = [ "cryptography" ] 11 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 12 | license = "MIT/Apache-2.0" 13 | edition = "2018" 14 | 15 | ################################# Dependencies ################################ 16 | 17 | [dependencies] 18 | ark-ff = { version = "^0.3.0", default-features = false } 19 | ark-ec = { version = "^0.3.0", default-features = false } 20 | ark-serialize = { version = "^0.3.0", default-features = false, features = [ "derive" ] } 21 | ark-poly = { version = "^0.3.0", default-features = false } 22 | ark-std = { version = "^0.3.0", default-features = false } 23 | ark-relations = { version = "^0.3.0", default-features = false } 24 | ark-crypto-primitives = { version = "^0.3.0", default-features = false } 25 | ark-r1cs-std = { version = "^0.3.1", default-features = false, optional = true } 26 | 27 | tracing = { version = "0.1", default-features = false, features = [ "attributes" ], optional = true } 28 | derivative = { version = "2.0", features = ["use_core"], optional = true} 29 | 30 | rayon = { version = "1", optional = true } 31 | cfg-if = "1.0" 32 | 33 | [dev-dependencies] 34 | csv = { version = "1" } 35 | ark-bls12-381 = { version = "^0.3.0", default-features = false, features = ["curve"] } 36 | ark-bls12-377 = { version = "^0.3.0", default-features = false, features = ["curve"] } 37 | ark-cp6-782 = { version = "^0.3.0", default-features = false } 38 | ark-mnt4-298 = { version = "^0.3.0", default-features = false, features = ["r1cs", "curve"] } 39 | ark-mnt6-298 = { version = "^0.3.0", default-features = false, features = ["r1cs"] } 40 | ark-mnt4-753 = { version = "^0.3.0", default-features = false, features = ["r1cs", "curve"] } 41 | ark-mnt6-753 = { version = "^0.3.0", default-features = false, features = ["r1cs"] } 42 | ark-groth16 = { version = "^0.3.0", default-features = false } 43 | 44 | [profile.release] 45 | opt-level = 3 46 | panic = 'abort' 47 | 48 | [profile.dev] 49 | opt-level = 0 50 | panic = 'abort' 51 | 52 | [features] 53 | default = ["parallel"] 54 | std = ["ark-ff/std", "ark-ec/std", "ark-poly/std", "ark-relations/std", "ark-crypto-primitives/std", "ark-std/std" ] 55 | parallel = ["std", "ark-ff/parallel", "ark-poly/parallel", "ark-ec/parallel", "ark-crypto-primitives/parallel", "ark-std/parallel", "rayon"] 56 | r1cs = [ "ark-crypto-primitives/r1cs", "ark-r1cs-std", "tracing", "derivative" ] 57 | print-trace = [ "ark-std/print-trace" ] 58 | -------------------------------------------------------------------------------- /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 |

legogroth16

2 | 3 |

4 | 5 | 6 | 7 | 8 |

9 | 10 | The arkworks ecosystem consist of Rust libraries for designing and working with __zero knowledge succinct non-interactive arguments (zkSNARKs)__. This repository contains an efficient implementation of the zkSNARK of [[Groth16]](https://eprint.iacr.org/2016/260). 11 | 12 | This library is released under the MIT License and the Apache v2 License (see [License](#license)). 13 | 14 | **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. 15 | 16 | ## Build guide 17 | 18 | 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: 19 | ```bash 20 | rustup install stable 21 | ``` 22 | 23 | After that, use `cargo`, the standard Rust build tool, to build the library: 24 | ```bash 25 | git clone https://github.com/arkworks-rs/groth16.git 26 | cargo build --release 27 | ``` 28 | 29 | This library comes with unit tests for each of the provided crates. Run the tests with: 30 | ```bash 31 | cargo test 32 | ``` 33 | 34 | ## License 35 | 36 | This library is licensed under either of the following licenses, at your discretion. 37 | 38 | * Apache License Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 39 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 40 | 41 | Unless you explicitly state otherwise, any contribution submitted for inclusion in this library by you shall be dual licensed as above (as defined in the Apache v2 License), without any additional terms or conditions. 42 | 43 | ## Acknowledgements 44 | 45 | This work was supported by: 46 | a Google Faculty Award; 47 | the National Science Foundation; 48 | the UC Berkeley Center for Long-Term Cybersecurity; 49 | and donations from the Ethereum Foundation, the Interchain Foundation, and Qtum. 50 | 51 | An earlier version of this library was developed as part of the paper *"[ZEXE: Enabling Decentralized Private Computation][zexe]"*. 52 | 53 | [zexe]: https://ia.cr/2018/962 54 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | reorder_imports = true 2 | wrap_comments = true 3 | normalize_comments = true 4 | use_try_shorthand = true 5 | match_block_trailing_comma = true 6 | use_field_init_shorthand = true 7 | edition = "2018" 8 | condense_wildcard_suffixes = true 9 | merge_imports = true 10 | -------------------------------------------------------------------------------- /scripts/install-hook.sh: -------------------------------------------------------------------------------- 1 | #!/bin/env bash 2 | # This script will install the provided directory ../.hooks as the hook 3 | # directory for the present repo. See there for hooks, including a pre-commit 4 | # hook that runs rustfmt on files before a commit. 5 | 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | HOOKS_DIR="${DIR}/../.hooks" 8 | 9 | git config core.hooksPath "$HOOKS_DIR" 10 | -------------------------------------------------------------------------------- /src/constraints.rs: -------------------------------------------------------------------------------- 1 | use crate::{Groth16, PreparedVerifyingKey, Proof, VerifyingKey}; 2 | use ark_crypto_primitives::snark::constraints::{CircuitSpecificSetupSNARKGadget, SNARKGadget}; 3 | use ark_crypto_primitives::snark::{BooleanInputVar, SNARK}; 4 | use ark_ec::{AffineCurve, PairingEngine}; 5 | use ark_r1cs_std::groups::CurveVar; 6 | use ark_r1cs_std::{ 7 | alloc::{AllocVar, AllocationMode}, 8 | bits::boolean::Boolean, 9 | bits::uint8::UInt8, 10 | eq::EqGadget, 11 | pairing::PairingVar, 12 | ToBitsGadget, ToBytesGadget, 13 | }; 14 | use ark_relations::r1cs::{Namespace, SynthesisError}; 15 | use ark_std::{borrow::Borrow, marker::PhantomData, vec::Vec}; 16 | 17 | /// The proof variable for the Groth16 construction 18 | #[derive(Derivative)] 19 | #[derivative(Clone(bound = "P::G1Var: Clone, P::G2Var: Clone"))] 20 | pub struct ProofVar> { 21 | /// The `A` element in `G1`. 22 | pub a: P::G1Var, 23 | /// The `B` element in `G2`. 24 | pub b: P::G2Var, 25 | /// The `C` element in `G1`. 26 | pub c: P::G1Var, 27 | } 28 | 29 | /// A variable representing the Groth16 verifying key in the constraint system. 30 | #[derive(Derivative)] 31 | #[derivative( 32 | Clone(bound = "P::G1Var: Clone, P::GTVar: Clone, P::G1PreparedVar: Clone, \ 33 | P::G2PreparedVar: Clone, ") 34 | )] 35 | pub struct VerifyingKeyVar> { 36 | #[doc(hidden)] 37 | pub alpha_g1: P::G1Var, 38 | #[doc(hidden)] 39 | pub beta_g2: P::G2Var, 40 | #[doc(hidden)] 41 | pub gamma_g2: P::G2Var, 42 | #[doc(hidden)] 43 | pub delta_g2: P::G2Var, 44 | #[doc(hidden)] 45 | pub gamma_abc_g1: Vec, 46 | } 47 | 48 | impl> VerifyingKeyVar { 49 | /// Prepare `self` for use in proof verification. 50 | pub fn prepare(&self) -> Result, SynthesisError> { 51 | let alpha_g1_pc = P::prepare_g1(&self.alpha_g1)?; 52 | let beta_g2_pc = P::prepare_g2(&self.beta_g2)?; 53 | 54 | let alpha_g1_beta_g2 = P::pairing(alpha_g1_pc, beta_g2_pc)?; 55 | let gamma_g2_neg_pc = P::prepare_g2(&self.gamma_g2.negate()?)?; 56 | let delta_g2_neg_pc = P::prepare_g2(&self.delta_g2.negate()?)?; 57 | 58 | Ok(PreparedVerifyingKeyVar { 59 | alpha_g1_beta_g2, 60 | gamma_g2_neg_pc, 61 | delta_g2_neg_pc, 62 | gamma_abc_g1: self.gamma_abc_g1.clone(), 63 | }) 64 | } 65 | } 66 | 67 | /// Preprocessed verification key parameters variable for the Groth16 construction 68 | #[derive(Derivative)] 69 | #[derivative( 70 | Clone(bound = "P::G1Var: Clone, P::GTVar: Clone, P::G1PreparedVar: Clone, \ 71 | P::G2PreparedVar: Clone, ") 72 | )] 73 | pub struct PreparedVerifyingKeyVar> { 74 | #[doc(hidden)] 75 | pub alpha_g1_beta_g2: P::GTVar, 76 | #[doc(hidden)] 77 | pub gamma_g2_neg_pc: P::G2PreparedVar, 78 | #[doc(hidden)] 79 | pub delta_g2_neg_pc: P::G2PreparedVar, 80 | #[doc(hidden)] 81 | pub gamma_abc_g1: Vec, 82 | } 83 | 84 | /// Constraints for the verifier of the SNARK of [[Groth16]](https://eprint.iacr.org/2016/260.pdf). 85 | pub struct Groth16VerifierGadget 86 | where 87 | E: PairingEngine, 88 | P: PairingVar, 89 | { 90 | _pairing_engine: PhantomData, 91 | _pairing_gadget: PhantomData

, 92 | } 93 | 94 | impl> SNARKGadget> 95 | for Groth16VerifierGadget 96 | { 97 | type ProcessedVerifyingKeyVar = PreparedVerifyingKeyVar; 98 | type VerifyingKeyVar = VerifyingKeyVar; 99 | type InputVar = BooleanInputVar; 100 | type ProofVar = ProofVar; 101 | 102 | type VerifierSize = usize; 103 | 104 | fn verifier_size( 105 | circuit_vk: & as SNARK>::VerifyingKey, 106 | ) -> Self::VerifierSize { 107 | circuit_vk.gamma_abc_g1.len() 108 | } 109 | 110 | /// Allocates `N::Proof` in `cs` without performing 111 | /// subgroup checks. 112 | #[tracing::instrument(target = "r1cs", skip(cs, f))] 113 | fn new_proof_unchecked>>( 114 | cs: impl Into>, 115 | f: impl FnOnce() -> Result, 116 | mode: AllocationMode, 117 | ) -> Result { 118 | let ns = cs.into(); 119 | let cs = ns.cs(); 120 | f().and_then(|proof| { 121 | let proof = proof.borrow(); 122 | let a = CurveVar::new_variable_omit_prime_order_check( 123 | ark_relations::ns!(cs, "Proof.a"), 124 | || Ok(proof.a.into_projective()), 125 | mode, 126 | )?; 127 | let b = CurveVar::new_variable_omit_prime_order_check( 128 | ark_relations::ns!(cs, "Proof.b"), 129 | || Ok(proof.b.into_projective()), 130 | mode, 131 | )?; 132 | let c = CurveVar::new_variable_omit_prime_order_check( 133 | ark_relations::ns!(cs, "Proof.c"), 134 | || Ok(proof.c.into_projective()), 135 | mode, 136 | )?; 137 | Ok(ProofVar { a, b, c }) 138 | }) 139 | } 140 | 141 | /// Allocates `N::Proof` in `cs` without performing 142 | /// subgroup checks. 143 | #[tracing::instrument(target = "r1cs", skip(cs, f))] 144 | fn new_verification_key_unchecked>>( 145 | cs: impl Into>, 146 | f: impl FnOnce() -> Result, 147 | mode: AllocationMode, 148 | ) -> Result { 149 | let ns = cs.into(); 150 | let cs = ns.cs(); 151 | f().and_then(|vk| { 152 | let vk = vk.borrow(); 153 | let alpha_g1 = P::G1Var::new_variable_omit_prime_order_check( 154 | ark_relations::ns!(cs, "alpha_g1"), 155 | || Ok(vk.alpha_g1.into_projective()), 156 | mode, 157 | )?; 158 | let beta_g2 = P::G2Var::new_variable_omit_prime_order_check( 159 | ark_relations::ns!(cs, "beta_g2"), 160 | || Ok(vk.beta_g2.into_projective()), 161 | mode, 162 | )?; 163 | let gamma_g2 = P::G2Var::new_variable_omit_prime_order_check( 164 | ark_relations::ns!(cs, "gamma_g2"), 165 | || Ok(vk.gamma_g2.into_projective()), 166 | mode, 167 | )?; 168 | let delta_g2 = P::G2Var::new_variable_omit_prime_order_check( 169 | ark_relations::ns!(cs, "delta_g2"), 170 | || Ok(vk.delta_g2.into_projective()), 171 | mode, 172 | )?; 173 | let gamma_abc_g1 = vk 174 | .gamma_abc_g1 175 | .iter() 176 | .map(|g| { 177 | P::G1Var::new_variable_omit_prime_order_check( 178 | ark_relations::ns!(cs, "gamma_abc_g1"), 179 | || Ok(g.into_projective()), 180 | mode, 181 | ) 182 | }) 183 | .collect::, _>>()?; 184 | 185 | Ok(VerifyingKeyVar { 186 | alpha_g1, 187 | beta_g2, 188 | gamma_g2, 189 | delta_g2, 190 | gamma_abc_g1, 191 | }) 192 | }) 193 | } 194 | 195 | #[tracing::instrument(target = "r1cs", skip(circuit_pvk, x, proof))] 196 | fn verify_with_processed_vk( 197 | circuit_pvk: &Self::ProcessedVerifyingKeyVar, 198 | x: &Self::InputVar, 199 | proof: &Self::ProofVar, 200 | ) -> Result, SynthesisError> { 201 | let circuit_pvk = circuit_pvk.clone(); 202 | 203 | let g_ic = { 204 | let mut g_ic: P::G1Var = circuit_pvk.gamma_abc_g1[0].clone(); 205 | let mut input_len = 1; 206 | let mut public_inputs = x.clone().into_iter(); 207 | for (input, b) in public_inputs 208 | .by_ref() 209 | .zip(circuit_pvk.gamma_abc_g1.iter().skip(1)) 210 | { 211 | let encoded_input_i: P::G1Var = b.scalar_mul_le(input.to_bits_le()?.iter())?; 212 | g_ic += encoded_input_i; 213 | input_len += 1; 214 | } 215 | // Check that the input and the query in the verification are of the 216 | // same length. 217 | assert!(input_len == circuit_pvk.gamma_abc_g1.len() && public_inputs.next().is_none()); 218 | g_ic 219 | }; 220 | 221 | let test_exp = { 222 | let proof_a_prep = P::prepare_g1(&proof.a)?; 223 | let proof_b_prep = P::prepare_g2(&proof.b)?; 224 | let proof_c_prep = P::prepare_g1(&proof.c)?; 225 | 226 | let g_ic_prep = P::prepare_g1(&g_ic)?; 227 | 228 | P::miller_loop( 229 | &[proof_a_prep, g_ic_prep, proof_c_prep], 230 | &[ 231 | proof_b_prep, 232 | circuit_pvk.gamma_g2_neg_pc.clone(), 233 | circuit_pvk.delta_g2_neg_pc.clone(), 234 | ], 235 | )? 236 | }; 237 | 238 | let test = P::final_exponentiation(&test_exp)?; 239 | test.is_eq(&circuit_pvk.alpha_g1_beta_g2) 240 | } 241 | 242 | #[tracing::instrument(target = "r1cs", skip(circuit_vk, x, proof))] 243 | fn verify( 244 | circuit_vk: &Self::VerifyingKeyVar, 245 | x: &Self::InputVar, 246 | proof: &Self::ProofVar, 247 | ) -> Result, SynthesisError> { 248 | let pvk = circuit_vk.prepare()?; 249 | Self::verify_with_processed_vk(&pvk, x, proof) 250 | } 251 | } 252 | 253 | impl CircuitSpecificSetupSNARKGadget> for Groth16VerifierGadget 254 | where 255 | E: PairingEngine, 256 | P: PairingVar, 257 | { 258 | } 259 | 260 | impl AllocVar, E::Fq> for PreparedVerifyingKeyVar 261 | where 262 | E: PairingEngine, 263 | P: PairingVar, 264 | { 265 | #[tracing::instrument(target = "r1cs", skip(cs, f))] 266 | fn new_variable>>( 267 | cs: impl Into>, 268 | f: impl FnOnce() -> Result, 269 | mode: AllocationMode, 270 | ) -> Result { 271 | let ns = cs.into(); 272 | let cs = ns.cs(); 273 | 274 | f().and_then(|pvk| { 275 | let pvk = pvk.borrow(); 276 | let alpha_g1_beta_g2 = P::GTVar::new_variable( 277 | ark_relations::ns!(cs, "alpha_g1_beta_g2"), 278 | || Ok(pvk.alpha_g1_beta_g2.clone()), 279 | mode, 280 | )?; 281 | 282 | let gamma_g2_neg_pc = P::G2PreparedVar::new_variable( 283 | ark_relations::ns!(cs, "gamma_g2_neg_pc"), 284 | || Ok(pvk.gamma_g2_neg_pc.clone()), 285 | mode, 286 | )?; 287 | 288 | let delta_g2_neg_pc = P::G2PreparedVar::new_variable( 289 | ark_relations::ns!(cs, "delta_g2_neg_pc"), 290 | || Ok(pvk.delta_g2_neg_pc.clone()), 291 | mode, 292 | )?; 293 | 294 | let gamma_abc_g1 = Vec::new_variable( 295 | ark_relations::ns!(cs, "gamma_abc_g1"), 296 | || Ok(pvk.vk.gamma_abc_g1.clone()), 297 | mode, 298 | )?; 299 | 300 | Ok(Self { 301 | alpha_g1_beta_g2, 302 | gamma_g2_neg_pc, 303 | delta_g2_neg_pc, 304 | gamma_abc_g1, 305 | }) 306 | }) 307 | } 308 | } 309 | 310 | impl AllocVar, E::Fq> for VerifyingKeyVar 311 | where 312 | E: PairingEngine, 313 | P: PairingVar, 314 | { 315 | #[tracing::instrument(target = "r1cs", skip(cs, f))] 316 | fn new_variable>>( 317 | cs: impl Into>, 318 | f: impl FnOnce() -> Result, 319 | mode: AllocationMode, 320 | ) -> Result { 321 | let ns = cs.into(); 322 | let cs = ns.cs(); 323 | 324 | f().and_then(|vk| { 325 | let VerifyingKey { 326 | alpha_g1, 327 | beta_g2, 328 | gamma_g2, 329 | delta_g2, 330 | gamma_abc_g1, 331 | } = vk.borrow().clone(); 332 | let alpha_g1 = 333 | P::G1Var::new_variable(ark_relations::ns!(cs, "alpha_g1"), || Ok(alpha_g1), mode)?; 334 | let beta_g2 = 335 | P::G2Var::new_variable(ark_relations::ns!(cs, "beta_g2"), || Ok(beta_g2), mode)?; 336 | let gamma_g2 = 337 | P::G2Var::new_variable(ark_relations::ns!(cs, "gamma_g2"), || Ok(gamma_g2), mode)?; 338 | let delta_g2 = 339 | P::G2Var::new_variable(ark_relations::ns!(cs, "delta_g2"), || Ok(delta_g2), mode)?; 340 | 341 | let gamma_abc_g1 = Vec::new_variable(cs.clone(), || Ok(gamma_abc_g1), mode)?; 342 | Ok(Self { 343 | alpha_g1, 344 | beta_g2, 345 | gamma_g2, 346 | delta_g2, 347 | gamma_abc_g1, 348 | }) 349 | }) 350 | } 351 | } 352 | 353 | impl AllocVar, E::Fq> for ProofVar 354 | where 355 | E: PairingEngine, 356 | P: PairingVar, 357 | { 358 | #[tracing::instrument(target = "r1cs", skip(cs, f))] 359 | fn new_variable>>( 360 | cs: impl Into>, 361 | f: impl FnOnce() -> Result, 362 | mode: AllocationMode, 363 | ) -> Result { 364 | let ns = cs.into(); 365 | let cs = ns.cs(); 366 | 367 | f().and_then(|proof| { 368 | let Proof { a, b, c } = proof.borrow().clone(); 369 | let a = P::G1Var::new_variable(ark_relations::ns!(cs, "a"), || Ok(a), mode)?; 370 | let b = P::G2Var::new_variable(ark_relations::ns!(cs, "b"), || Ok(b), mode)?; 371 | let c = P::G1Var::new_variable(ark_relations::ns!(cs, "c"), || Ok(c), mode)?; 372 | Ok(Self { a, b, c }) 373 | }) 374 | } 375 | } 376 | 377 | impl ToBytesGadget for VerifyingKeyVar 378 | where 379 | E: PairingEngine, 380 | P: PairingVar, 381 | { 382 | #[inline] 383 | #[tracing::instrument(target = "r1cs", skip(self))] 384 | fn to_bytes(&self) -> Result>, SynthesisError> { 385 | let mut bytes = Vec::new(); 386 | bytes.extend_from_slice(&self.alpha_g1.to_bytes()?); 387 | bytes.extend_from_slice(&self.beta_g2.to_bytes()?); 388 | bytes.extend_from_slice(&self.gamma_g2.to_bytes()?); 389 | bytes.extend_from_slice(&self.delta_g2.to_bytes()?); 390 | for g in &self.gamma_abc_g1 { 391 | bytes.extend_from_slice(&g.to_bytes()?); 392 | } 393 | Ok(bytes) 394 | } 395 | } 396 | 397 | #[cfg(test)] 398 | mod test { 399 | use crate::{constraints::Groth16VerifierGadget, Groth16}; 400 | use ark_crypto_primitives::snark::constraints::SNARKGadget; 401 | use ark_crypto_primitives::snark::{CircuitSpecificSetupSNARK, SNARK}; 402 | use ark_ec::PairingEngine; 403 | use ark_ff::{Field, UniformRand}; 404 | use ark_mnt4_298::{ 405 | constraints::PairingVar as MNT4PairingVar, Fr as MNT4Fr, MNT4_298 as MNT4PairingEngine, 406 | }; 407 | use ark_mnt6_298::Fr as MNT6Fr; 408 | use ark_r1cs_std::bits::boolean::Boolean; 409 | use ark_r1cs_std::{alloc::AllocVar, eq::EqGadget}; 410 | use ark_relations::{ 411 | lc, ns, 412 | r1cs::{ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, SynthesisError}, 413 | }; 414 | use ark_std::ops::MulAssign; 415 | use ark_std::rand::{rngs::StdRng, SeedableRng}; 416 | 417 | #[derive(Copy, Clone)] 418 | struct Circuit { 419 | a: Option, 420 | b: Option, 421 | num_constraints: usize, 422 | num_variables: usize, 423 | } 424 | 425 | impl ConstraintSynthesizer for Circuit { 426 | fn generate_constraints( 427 | self, 428 | cs: ConstraintSystemRef, 429 | ) -> Result<(), SynthesisError> { 430 | let a = cs.new_witness_variable(|| self.a.ok_or(SynthesisError::AssignmentMissing))?; 431 | let b = cs.new_witness_variable(|| self.b.ok_or(SynthesisError::AssignmentMissing))?; 432 | let c = cs.new_input_variable(|| { 433 | let mut a = self.a.ok_or(SynthesisError::AssignmentMissing)?; 434 | let b = self.b.ok_or(SynthesisError::AssignmentMissing)?; 435 | 436 | a.mul_assign(&b); 437 | Ok(a) 438 | })?; 439 | 440 | for _ in 0..(self.num_variables - 3) { 441 | cs.new_witness_variable(|| self.a.ok_or(SynthesisError::AssignmentMissing))?; 442 | } 443 | 444 | for _ in 0..self.num_constraints { 445 | cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c) 446 | .unwrap(); 447 | } 448 | Ok(()) 449 | } 450 | } 451 | 452 | type TestSNARK = Groth16; 453 | type TestSNARKGadget = Groth16VerifierGadget; 454 | 455 | #[test] 456 | fn groth16_snark_test() { 457 | let mut rng = StdRng::seed_from_u64(0u64); 458 | let a = MNT4Fr::rand(&mut rng); 459 | let b = MNT4Fr::rand(&mut rng); 460 | let mut c = a; 461 | c.mul_assign(&b); 462 | 463 | let circ = Circuit { 464 | a: Some(a.clone()), 465 | b: Some(b.clone()), 466 | num_constraints: 100, 467 | num_variables: 25, 468 | }; 469 | 470 | let (pk, vk) = TestSNARK::setup(circ, &mut rng).unwrap(); 471 | 472 | let proof = TestSNARK::prove(&pk, circ.clone(), &mut rng).unwrap(); 473 | 474 | assert!( 475 | TestSNARK::verify(&vk, &vec![c], &proof).unwrap(), 476 | "The native verification check fails." 477 | ); 478 | 479 | let cs_sys = ConstraintSystem::::new(); 480 | let cs = ConstraintSystemRef::new(cs_sys); 481 | 482 | let input_gadget = ::Fr, 484 | ::Fq, 485 | TestSNARK, 486 | >>::InputVar::new_input(ns!(cs, "new_input"), || Ok(vec![c])) 487 | .unwrap(); 488 | let proof_gadget = ::Fr, 490 | ::Fq, 491 | TestSNARK, 492 | >>::ProofVar::new_witness(ns!(cs, "alloc_proof"), || Ok(proof)) 493 | .unwrap(); 494 | let vk_gadget = ::Fr, 496 | ::Fq, 497 | TestSNARK, 498 | >>::VerifyingKeyVar::new_constant(ns!(cs, "alloc_vk"), vk.clone()) 499 | .unwrap(); 500 | ::Fr, 502 | ::Fq, 503 | TestSNARK, 504 | >>::verify(&vk_gadget, &input_gadget, &proof_gadget) 505 | .unwrap() 506 | .enforce_equal(&Boolean::constant(true)) 507 | .unwrap(); 508 | 509 | assert!( 510 | cs.is_satisfied().unwrap(), 511 | "Constraints not satisfied: {}", 512 | cs.which_is_unsatisfied().unwrap().unwrap_or_default() 513 | ); 514 | 515 | let pvk = TestSNARK::process_vk(&vk).unwrap(); 516 | let pvk_gadget = ::Fr, 518 | ::Fq, 519 | TestSNARK, 520 | >>::ProcessedVerifyingKeyVar::new_constant( 521 | ns!(cs, "alloc_pvk"), pvk.clone() 522 | ) 523 | .unwrap(); 524 | TestSNARKGadget::verify_with_processed_vk(&pvk_gadget, &input_gadget, &proof_gadget) 525 | .unwrap() 526 | .enforce_equal(&Boolean::constant(true)) 527 | .unwrap(); 528 | 529 | assert!( 530 | cs.is_satisfied().unwrap(), 531 | "Constraints not satisfied: {}", 532 | cs.which_is_unsatisfied().unwrap().unwrap_or_default() 533 | ); 534 | } 535 | } 536 | -------------------------------------------------------------------------------- /src/data_structures.rs: -------------------------------------------------------------------------------- 1 | use crate::link::{EK, PP, VK}; 2 | use ark_ec::PairingEngine; 3 | use ark_ff::bytes::ToBytes; 4 | use ark_serialize::*; 5 | use ark_std::{ 6 | io::{self, Result as IoResult}, 7 | vec::Vec, 8 | }; 9 | 10 | /// A proof in the Groth16 SNARK. 11 | #[derive(Clone, Debug, PartialEq, CanonicalSerialize, CanonicalDeserialize)] 12 | pub struct Proof { 13 | /// The `A` element in `G1`. 14 | pub a: E::G1Affine, 15 | /// The `B` element in `G2`. 16 | pub b: E::G2Affine, 17 | /// The `C` element in `G1`. 18 | pub c: E::G1Affine, 19 | /// The `D` element in `G1`. 20 | pub d: E::G1Affine, 21 | 22 | /// cp_{link} proof of commitment equality 23 | pub link_d: E::G1Affine, 24 | pub link_pi: E::G1Affine, 25 | } 26 | 27 | impl ToBytes for Proof { 28 | #[inline] 29 | fn write(&self, mut writer: W) -> io::Result<()> { 30 | self.a.write(&mut writer)?; 31 | self.b.write(&mut writer)?; 32 | self.c.write(&mut writer)?; 33 | self.d.write(&mut writer)?; 34 | self.link_d.write(&mut writer)?; 35 | self.link_pi.write(&mut writer) 36 | } 37 | } 38 | 39 | impl Default for Proof { 40 | fn default() -> Self { 41 | Self { 42 | a: E::G1Affine::default(), 43 | b: E::G2Affine::default(), 44 | c: E::G1Affine::default(), 45 | d: E::G1Affine::default(), 46 | link_pi: E::G1Affine::default(), 47 | link_d: E::G1Affine::default(), 48 | } 49 | } 50 | } 51 | 52 | //////////////////////////////////////////////////////////////////////////////// 53 | //////////////////////////////////////////////////////////////////////////////// 54 | 55 | /// A verification key in the Groth16 SNARK. 56 | #[derive(Clone, Debug, PartialEq, CanonicalSerialize, CanonicalDeserialize)] 57 | pub struct VerifyingKey { 58 | /// The `alpha * G`, where `G` is the generator of `E::G1`. 59 | pub alpha_g1: E::G1Affine, 60 | /// The `alpha * H`, where `H` is the generator of `E::G2`. 61 | pub beta_g2: E::G2Affine, 62 | /// The `gamma * H`, where `H` is the generator of `E::G2`. 63 | pub gamma_g2: E::G2Affine, 64 | /// The `delta * H`, where `H` is the generator of `E::G2`. 65 | pub delta_g2: E::G2Affine, 66 | /// The `gamma^{-1} * (beta * a_i + alpha * b_i + c_i) * H`, where `H` is the generator of `E::G1`. 67 | pub gamma_abc_g1: Vec, 68 | /// The element `eta*gamma^-1 * G` in `E::G1`. 69 | pub eta_gamma_inv_g1: E::G1Affine, 70 | 71 | /// cp_{link} 72 | pub link_pp: PP, 73 | pub link_bases: Vec, 74 | pub link_vk: VK, 75 | } 76 | 77 | impl ToBytes for VerifyingKey { 78 | fn write(&self, mut writer: W) -> IoResult<()> { 79 | self.alpha_g1.write(&mut writer)?; 80 | self.beta_g2.write(&mut writer)?; 81 | self.gamma_g2.write(&mut writer)?; 82 | self.delta_g2.write(&mut writer)?; 83 | for q in &self.gamma_abc_g1 { 84 | q.write(&mut writer)?; 85 | } 86 | self.eta_gamma_inv_g1.write(&mut writer)?; 87 | self.link_pp.write(&mut writer)?; 88 | for q in &self.link_bases { 89 | q.write(&mut writer)?; 90 | } 91 | self.link_vk.write(&mut writer)?; 92 | 93 | Ok(()) 94 | } 95 | } 96 | 97 | impl Default for VerifyingKey { 98 | fn default() -> Self { 99 | Self { 100 | alpha_g1: E::G1Affine::default(), 101 | beta_g2: E::G2Affine::default(), 102 | gamma_g2: E::G2Affine::default(), 103 | delta_g2: E::G2Affine::default(), 104 | gamma_abc_g1: Vec::new(), 105 | eta_gamma_inv_g1: E::G1Affine::default(), 106 | link_pp: PP::::default(), 107 | link_bases: Vec::new(), 108 | link_vk: VK::::default(), 109 | } 110 | } 111 | } 112 | 113 | /// Preprocessed verification key parameters that enable faster verification 114 | /// at the expense of larger size in memory. 115 | #[derive(Clone, Debug, PartialEq)] 116 | pub struct PreparedVerifyingKey { 117 | /// The unprepared verification key. 118 | pub vk: VerifyingKey, 119 | /// The element `e(alpha * G, beta * H)` in `E::GT`. 120 | pub alpha_g1_beta_g2: E::Fqk, 121 | /// The element `- gamma * H` in `E::G2`, prepared for use in pairings. 122 | pub gamma_g2_neg_pc: E::G2Prepared, 123 | /// The element `- delta * H` in `E::G2`, prepared for use in pairings. 124 | pub delta_g2_neg_pc: E::G2Prepared, 125 | } 126 | 127 | impl From> for VerifyingKey { 128 | fn from(other: PreparedVerifyingKey) -> Self { 129 | other.vk 130 | } 131 | } 132 | 133 | impl From> for PreparedVerifyingKey { 134 | fn from(other: VerifyingKey) -> Self { 135 | crate::prepare_verifying_key(&other) 136 | } 137 | } 138 | 139 | impl Default for PreparedVerifyingKey { 140 | fn default() -> Self { 141 | Self { 142 | vk: VerifyingKey::default(), 143 | alpha_g1_beta_g2: E::Fqk::default(), 144 | gamma_g2_neg_pc: E::G2Prepared::default(), 145 | delta_g2_neg_pc: E::G2Prepared::default(), 146 | } 147 | } 148 | } 149 | 150 | impl ToBytes for PreparedVerifyingKey { 151 | fn write(&self, mut writer: W) -> IoResult<()> { 152 | self.vk.write(&mut writer)?; 153 | self.alpha_g1_beta_g2.write(&mut writer)?; 154 | self.gamma_g2_neg_pc.write(&mut writer)?; 155 | self.delta_g2_neg_pc.write(&mut writer)?; 156 | Ok(()) 157 | } 158 | } 159 | 160 | //////////////////////////////////////////////////////////////////////////////// 161 | //////////////////////////////////////////////////////////////////////////////// 162 | 163 | /// The prover key for for the Groth16 zkSNARK. 164 | #[derive(Clone, Debug, PartialEq, CanonicalSerialize, CanonicalDeserialize)] 165 | pub struct ProvingKey { 166 | /// The underlying verification key. 167 | pub vk: VerifyingKey, 168 | /// The element `beta * G` in `E::G1`. 169 | pub beta_g1: E::G1Affine, 170 | /// The element `delta * G` in `E::G1`. 171 | pub delta_g1: E::G1Affine, 172 | /// The element `eta*delta^-1 * G` in `E::G1`. 173 | pub eta_delta_inv_g1: E::G1Affine, 174 | /// The elements `a_i * G` in `E::G1`. 175 | pub a_query: Vec, 176 | /// The elements `b_i * G` in `E::G1`. 177 | pub b_g1_query: Vec, 178 | /// The elements `b_i * H` in `E::G2`. 179 | pub b_g2_query: Vec, 180 | /// The elements `h_i * G` in `E::G1`. 181 | pub h_query: Vec, 182 | /// The elements `l_i * G` in `E::G1`. 183 | pub l_query: Vec, 184 | 185 | /// Evaluation key of cp_{link} 186 | pub link_ek: EK, 187 | } 188 | -------------------------------------------------------------------------------- /src/generator.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | link::{PESubspaceSnark, SparseMatrix, SubspaceSnark, PP}, 3 | r1cs_to_qap::R1CStoQAP, 4 | ProvingKey, Vec, VerifyingKey, 5 | }; 6 | use ark_ec::{msm::FixedBaseMSM, AffineCurve, PairingEngine, ProjectiveCurve}; 7 | use ark_ff::{Field, PrimeField, UniformRand, Zero}; 8 | use ark_poly::{EvaluationDomain, GeneralEvaluationDomain}; 9 | use ark_relations::r1cs::{ 10 | ConstraintSynthesizer, ConstraintSystem, OptimizationGoal, Result as R1CSResult, 11 | SynthesisError, SynthesisMode, 12 | }; 13 | use ark_std::rand::Rng; 14 | use ark_std::{cfg_into_iter, cfg_iter, end_timer, start_timer}; 15 | 16 | #[cfg(feature = "parallel")] 17 | use rayon::prelude::*; 18 | 19 | /// Generates a random common reference string for 20 | /// a circuit. 21 | #[inline] 22 | pub fn generate_random_parameters( 23 | circuit: C, 24 | pedersen_bases: &[E::G1Affine], 25 | rng: &mut R, 26 | ) -> R1CSResult> 27 | where 28 | E: PairingEngine, 29 | C: ConstraintSynthesizer, 30 | R: Rng, 31 | { 32 | let alpha = E::Fr::rand(rng); 33 | let beta = E::Fr::rand(rng); 34 | let gamma = E::Fr::rand(rng); 35 | let delta = E::Fr::rand(rng); 36 | let eta = E::Fr::rand(rng); 37 | 38 | generate_parameters::(circuit, alpha, beta, gamma, delta, eta, pedersen_bases, rng) 39 | } 40 | 41 | /// Create parameters for a circuit, given some toxic waste. 42 | pub fn generate_parameters( 43 | circuit: C, 44 | alpha: E::Fr, 45 | beta: E::Fr, 46 | gamma: E::Fr, 47 | delta: E::Fr, 48 | eta: E::Fr, 49 | pedersen_bases: &[E::G1Affine], 50 | rng: &mut R, 51 | ) -> R1CSResult> 52 | where 53 | E: PairingEngine, 54 | C: ConstraintSynthesizer, 55 | R: Rng, 56 | { 57 | type D = GeneralEvaluationDomain; 58 | 59 | let setup_time = start_timer!(|| "Groth16::Generator"); 60 | let cs = ConstraintSystem::new_ref(); 61 | cs.set_optimization_goal(OptimizationGoal::Constraints); 62 | cs.set_mode(SynthesisMode::Setup); 63 | 64 | // Synthesize the circuit. 65 | let synthesis_time = start_timer!(|| "Constraint synthesis"); 66 | circuit.generate_constraints(cs.clone())?; 67 | end_timer!(synthesis_time); 68 | 69 | let lc_time = start_timer!(|| "Inlining LCs"); 70 | cs.finalize(); 71 | end_timer!(lc_time); 72 | 73 | /////////////////////////////////////////////////////////////////////////// 74 | let domain_time = start_timer!(|| "Constructing evaluation domain"); 75 | 76 | let domain_size = cs.num_constraints() + cs.num_instance_variables(); 77 | let domain = D::new(domain_size).ok_or(SynthesisError::PolynomialDegreeTooLarge)?; 78 | let t = domain.sample_element_outside_domain(rng); 79 | 80 | end_timer!(domain_time); 81 | /////////////////////////////////////////////////////////////////////////// 82 | 83 | let reduction_time = start_timer!(|| "R1CS to QAP Instance Map with Evaluation"); 84 | let num_instance_variables = cs.num_instance_variables(); 85 | let (a, b, c, zt, qap_num_variables, m_raw) = 86 | R1CStoQAP::instance_map_with_evaluation::>(cs, &t)?; 87 | end_timer!(reduction_time); 88 | 89 | // Compute query densities 90 | let non_zero_a: usize = cfg_into_iter!(0..qap_num_variables) 91 | .map(|i| usize::from(!a[i].is_zero())) 92 | .sum(); 93 | 94 | let non_zero_b: usize = cfg_into_iter!(0..qap_num_variables) 95 | .map(|i| usize::from(!b[i].is_zero())) 96 | .sum(); 97 | 98 | let scalar_bits = E::Fr::size_in_bits(); 99 | 100 | let gamma_inverse = gamma.inverse().ok_or(SynthesisError::UnexpectedIdentity)?; 101 | let delta_inverse = delta.inverse().ok_or(SynthesisError::UnexpectedIdentity)?; 102 | 103 | let gamma_abc = cfg_iter!(a[..num_instance_variables]) 104 | .zip(&b[..num_instance_variables]) 105 | .zip(&c[..num_instance_variables]) 106 | .map(|((a, b), c)| (beta * a + &(alpha * b) + c) * &gamma_inverse) 107 | .collect::>(); 108 | 109 | let l = cfg_iter!(a) 110 | .zip(&b) 111 | .zip(&c) 112 | .map(|((a, b), c)| (beta * a + &(alpha * b) + c) * &delta_inverse) 113 | .collect::>(); 114 | 115 | drop(c); 116 | 117 | let g1_generator = E::G1Projective::rand(rng); 118 | let g2_generator = E::G2Projective::rand(rng); 119 | 120 | // Compute B window table 121 | let g2_time = start_timer!(|| "Compute G2 table"); 122 | let g2_window = FixedBaseMSM::get_mul_window_size(non_zero_b); 123 | let g2_table = 124 | FixedBaseMSM::get_window_table::(scalar_bits, g2_window, g2_generator); 125 | end_timer!(g2_time); 126 | 127 | // Compute the B-query in G2 128 | let b_g2_time = start_timer!(|| "Calculate B G2"); 129 | let b_g2_query = 130 | FixedBaseMSM::multi_scalar_mul::(scalar_bits, g2_window, &g2_table, &b); 131 | drop(g2_table); 132 | end_timer!(b_g2_time); 133 | 134 | // Compute G window table 135 | let g1_window_time = start_timer!(|| "Compute G1 window table"); 136 | let g1_window = 137 | FixedBaseMSM::get_mul_window_size(non_zero_a + non_zero_b + qap_num_variables + m_raw + 1); 138 | let g1_table = 139 | FixedBaseMSM::get_window_table::(scalar_bits, g1_window, g1_generator); 140 | end_timer!(g1_window_time); 141 | 142 | // Generate the R1CS proving key 143 | let proving_key_time = start_timer!(|| "Generate the R1CS proving key"); 144 | 145 | let beta_repr = beta.into_repr(); 146 | let delta_repr = delta.into_repr(); 147 | 148 | let alpha_g1 = g1_generator.mul(alpha.into_repr()); 149 | let beta_g1 = g1_generator.mul(beta_repr); 150 | let beta_g2 = g2_generator.mul(beta_repr); 151 | let delta_g1 = g1_generator.mul(delta_repr); 152 | let delta_g2 = g2_generator.mul(delta_repr); 153 | 154 | // Compute the A-query 155 | let a_time = start_timer!(|| "Calculate A"); 156 | let a_query = 157 | FixedBaseMSM::multi_scalar_mul::(scalar_bits, g1_window, &g1_table, &a); 158 | drop(a); 159 | end_timer!(a_time); 160 | 161 | // Compute the B-query in G1 162 | let b_g1_time = start_timer!(|| "Calculate B G1"); 163 | let b_g1_query = 164 | FixedBaseMSM::multi_scalar_mul::(scalar_bits, g1_window, &g1_table, &b); 165 | drop(b); 166 | end_timer!(b_g1_time); 167 | 168 | // Compute the H-query 169 | let h_time = start_timer!(|| "Calculate H"); 170 | let h_query = FixedBaseMSM::multi_scalar_mul::( 171 | scalar_bits, 172 | g1_window, 173 | &g1_table, 174 | &cfg_into_iter!(0..m_raw - 1) 175 | .map(|i| zt * &delta_inverse * &t.pow([i as u64])) 176 | .collect::>(), 177 | ); 178 | 179 | end_timer!(h_time); 180 | 181 | // Compute the L-query 182 | let l_time = start_timer!(|| "Calculate L"); 183 | let l_query = FixedBaseMSM::multi_scalar_mul::( 184 | scalar_bits, 185 | g1_window, 186 | &g1_table, 187 | &l[num_instance_variables..], 188 | ); 189 | drop(l); 190 | end_timer!(l_time); 191 | 192 | end_timer!(proving_key_time); 193 | 194 | // Generate R1CS verification key 195 | let verifying_key_time = start_timer!(|| "Generate the R1CS verification key"); 196 | let gamma_g2 = g2_generator.mul(gamma.into_repr()); 197 | let gamma_abc_g1 = FixedBaseMSM::multi_scalar_mul::( 198 | scalar_bits, 199 | g1_window, 200 | &g1_table, 201 | &gamma_abc, 202 | ); 203 | 204 | drop(g1_table); 205 | 206 | end_timer!(verifying_key_time); 207 | 208 | let eta_gamma_inv_g1 = g1_generator.mul((eta * &gamma_inverse).into_repr()); 209 | 210 | let link_rows = 2; // we're comparirng two commitments 211 | let link_cols = gamma_abc_g1.len() + 2; // we have len inputs and 1 hiding factor per row 212 | let link_pp = PP:: { 213 | l: link_rows, 214 | t: link_cols, 215 | g1: E::G1Affine::prime_subgroup_generator(), 216 | g2: E::G2Affine::prime_subgroup_generator(), 217 | }; 218 | 219 | let mut link_m = SparseMatrix::::new(link_rows, link_cols); 220 | link_m.insert_row_slice(0, 0, &pedersen_bases); 221 | link_m.insert_row_slice( 222 | 1, 223 | 0, 224 | &gamma_abc_g1 225 | .iter() 226 | .map(|p| p.into_affine()) 227 | .collect::>(), 228 | ); 229 | link_m.insert_row_slice(1, gamma_abc_g1.len() + 1, &[eta_gamma_inv_g1.into_affine()]); 230 | 231 | let (link_ek, link_vk) = PESubspaceSnark::::keygen(rng, &link_pp, link_m); 232 | 233 | let vk = VerifyingKey:: { 234 | alpha_g1: alpha_g1.into_affine(), 235 | beta_g2: beta_g2.into_affine(), 236 | gamma_g2: gamma_g2.into_affine(), 237 | delta_g2: delta_g2.into_affine(), 238 | gamma_abc_g1: E::G1Projective::batch_normalization_into_affine(&gamma_abc_g1), 239 | eta_gamma_inv_g1: eta_gamma_inv_g1.into_affine(), 240 | 241 | link_pp, 242 | link_bases: pedersen_bases.to_vec(), 243 | link_vk, 244 | }; 245 | 246 | let batch_normalization_time = start_timer!(|| "Convert proving key elements to affine"); 247 | let a_query = E::G1Projective::batch_normalization_into_affine(&a_query); 248 | let b_g1_query = E::G1Projective::batch_normalization_into_affine(&b_g1_query); 249 | let b_g2_query = E::G2Projective::batch_normalization_into_affine(&b_g2_query); 250 | let h_query = E::G1Projective::batch_normalization_into_affine(&h_query); 251 | let l_query = E::G1Projective::batch_normalization_into_affine(&l_query); 252 | end_timer!(batch_normalization_time); 253 | end_timer!(setup_time); 254 | 255 | let eta_delta_inv_g1 = g1_generator.mul((eta * &delta_inverse).into_repr()); 256 | 257 | Ok(ProvingKey { 258 | vk, 259 | beta_g1: beta_g1.into_affine(), 260 | delta_g1: delta_g1.into_affine(), 261 | eta_delta_inv_g1: eta_delta_inv_g1.into_affine(), 262 | a_query, 263 | b_g1_query, 264 | b_g2_query, 265 | h_query, 266 | l_query, 267 | 268 | link_ek, 269 | }) 270 | } 271 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! An implementation of the [`Groth16`] zkSNARK. 2 | //! 3 | //! [`Groth16`]: https://eprint.iacr.org/2016/260.pdf 4 | #![cfg_attr(not(feature = "std"), no_std)] 5 | #![warn(unused, future_incompatible, nonstandard_style, rust_2018_idioms)] 6 | #![allow(clippy::many_single_char_names, clippy::op_ref)] 7 | #![forbid(unsafe_code)] 8 | 9 | /// Reduce an R1CS instance to a *Quadratic Arithmetic Program* instance. 10 | pub(crate) mod r1cs_to_qap; 11 | 12 | /// Data structures used by the prover, verifier, and generator. 13 | pub mod data_structures; 14 | 15 | /// Generate public parameters for the Groth16 zkSNARK construction. 16 | pub mod generator; 17 | 18 | /// Create proofs for the Groth16 zkSNARK construction. 19 | pub mod prover; 20 | 21 | /// Verify proofs for the Groth16 zkSNARK construction. 22 | pub mod verifier; 23 | 24 | pub mod link; 25 | 26 | /// Constraints for the Groth16 verifier. 27 | // Cannot yet create a LegoGroth16 gadget (for recursive proof) so commenting it out. 28 | // #[cfg(feature = "r1cs")] 29 | // pub mod constraints; 30 | 31 | #[cfg(test)] 32 | mod test; 33 | 34 | pub use self::data_structures::*; 35 | pub use self::{generator::*, prover::*, verifier::*}; 36 | 37 | use ark_std::vec::Vec; 38 | -------------------------------------------------------------------------------- /src/link/matrix.rs: -------------------------------------------------------------------------------- 1 | use ark_ec::{AffineCurve, PairingEngine, ProjectiveCurve}; 2 | use ark_ff::Zero; 3 | use ark_std::marker::PhantomData; 4 | use ark_std::ops::{AddAssign, Mul}; 5 | use ark_std::vec; 6 | use ark_std::vec::Vec; 7 | 8 | /// CoeffPos: A struct to help build sparse matrices. 9 | #[derive(Clone, Debug)] 10 | pub struct CoeffPos { 11 | val: T, 12 | pos: usize, 13 | } 14 | 15 | // a column is a vector of CoeffPos-s 16 | type Col = Vec>; 17 | 18 | /* TODO: One could consider a cache-friendlier implementation for the 2-row case*/ 19 | 20 | /// Column-Major Sparse Matrix 21 | #[derive(Clone, Debug)] 22 | pub struct SparseMatrix { 23 | cols: Vec>, // a vector of columns 24 | pub nr: usize, 25 | pub nc: usize, 26 | } 27 | 28 | impl SparseMatrix { 29 | // NB: Given column by column 30 | pub fn new(nr: usize, nc: usize) -> SparseMatrix { 31 | SparseMatrix { 32 | cols: vec![vec![]; nc], 33 | nr, 34 | nc, 35 | } 36 | } 37 | 38 | pub fn insert_val(&mut self, r: usize, c: usize, v: &T) { 39 | let coeff_pos = CoeffPos { pos: r, val: *v }; 40 | self.cols[c].push(coeff_pos); 41 | } 42 | 43 | // insert a continuous sequence of values at row r starting from c_offset 44 | pub fn insert_row_slice(&mut self, r: usize, c_offset: usize, vs: &[T]) { 45 | // NB: could be improved in efficiency by first extending the vector 46 | for (i, x) in vs.iter().enumerate() { 47 | self.insert_val(r, c_offset + i, x); 48 | } 49 | } 50 | 51 | pub fn get_col(&self, c: usize) -> &Col { 52 | &self.cols[c] 53 | } 54 | } 55 | 56 | pub struct SparseLinAlgebra { 57 | pairing_engine_type: PhantomData, 58 | } 59 | 60 | impl SparseLinAlgebra { 61 | // this is basically a multi-exp 62 | pub fn sparse_inner_product(v: &Vec, w: &Col) -> PE::G1Affine { 63 | let mut res: PE::G1Projective = PE::G1Projective::zero(); 64 | for coeffpos in w { 65 | let g = coeffpos.val; 66 | let i = coeffpos.pos; 67 | // XXX: Should this be optimized for special cases 68 | // (e.g. 0 or 1) or is this already in .mul? 69 | let tmp = g.mul(v[i]); 70 | 71 | res.add_assign(&tmp); 72 | } 73 | res.into_affine() 74 | } 75 | 76 | pub fn sparse_vector_matrix_mult( 77 | v: &Vec, 78 | m: &SparseMatrix, 79 | t: usize, 80 | ) -> Vec { 81 | // the result should contain every column of m multiplied by v 82 | let mut res: Vec = Vec::with_capacity(t); 83 | for c in 0..m.nc { 84 | res.push(Self::sparse_inner_product(&v, &m.get_col(c))); 85 | } 86 | res 87 | } 88 | } 89 | 90 | pub fn inner_product(v: &[PE::Fr], w: &[PE::G1Affine]) -> PE::G1Affine { 91 | assert_eq!(v.len(), w.len()); 92 | let mut res: PE::G1Projective = PE::G1Projective::zero(); 93 | for i in 0..v.len() { 94 | let tmp = w[i].mul(v[i]); 95 | res.add_assign(&tmp); 96 | } 97 | res.into_affine() 98 | } 99 | 100 | pub fn scalar_vector_mult(a: &PE::Fr, v: &[PE::Fr], l: usize) -> Vec { 101 | let mut res: Vec = Vec::with_capacity(l); 102 | for i in 0..v.len() { 103 | let x: PE::Fr = a.mul(&v[i]); 104 | res.push(x); 105 | } 106 | res 107 | } 108 | -------------------------------------------------------------------------------- /src/link/mod.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | 3 | mod matrix; 4 | mod snark; 5 | 6 | pub use matrix::*; 7 | pub use snark::*; 8 | 9 | #[cfg(test)] 10 | mod test { 11 | use super::{PESubspaceSnark, SparseMatrix, SubspaceSnark, PP}; 12 | use ark_bls12_381::{Bls12_381, Fr, G1Affine, G1Projective, G2Affine, G2Projective}; 13 | use ark_ec::{AffineCurve, ProjectiveCurve}; 14 | use ark_ff::{One, PrimeField, UniformRand, Zero}; 15 | use ark_std::rand::{rngs::StdRng, SeedableRng}; 16 | 17 | #[test] 18 | fn test_basic() { 19 | let mut rng = StdRng::seed_from_u64(0u64); 20 | let g1 = G1Projective::rand(&mut rng).into_affine(); 21 | let g2 = G2Projective::rand(&mut rng).into_affine(); 22 | 23 | let mut pp = PP:: { l: 1, t: 2, g1, g2 }; 24 | 25 | let mut m = SparseMatrix::new(1, 2); 26 | m.insert_row_slice(0, 0, &vec![g1, g1]); 27 | 28 | let x: Vec = vec![Fr::one(), Fr::zero()]; 29 | 30 | let x_bad: Vec = vec![Fr::one(), Fr::one()]; 31 | 32 | let y: Vec = vec![g1]; 33 | 34 | let (ek, vk) = PESubspaceSnark::::keygen(&mut rng, &pp, m); 35 | 36 | let pi = PESubspaceSnark::::prove(&mut pp, &ek, &x); 37 | let pi_bad = PESubspaceSnark::::prove(&mut pp, &ek, &x_bad); 38 | 39 | let b = PESubspaceSnark::::verify(&pp, &vk, &y, &pi); 40 | let b_bad = PESubspaceSnark::::verify(&pp, &vk, &y, &pi_bad); 41 | assert!(b); 42 | assert!(!b_bad); 43 | } 44 | 45 | #[test] 46 | fn test_same_value_different_bases() { 47 | let mut rng = StdRng::seed_from_u64(0u64); 48 | let g1 = G1Projective::rand(&mut rng).into_affine(); 49 | let g2 = G2Projective::rand(&mut rng).into_affine(); 50 | 51 | let mut pp = PP:: { l: 2, t: 3, g1, g2 }; 52 | 53 | let bases1 = [G1Projective::rand(&mut rng), G1Projective::rand(&mut rng)] 54 | .iter() 55 | .map(|p| p.into_affine()) 56 | .collect::>(); 57 | let bases2 = [G1Projective::rand(&mut rng), G1Projective::rand(&mut rng)] 58 | .iter() 59 | .map(|p| p.into_affine()) 60 | .collect::>(); 61 | let mut m = SparseMatrix::new(2, 3); 62 | m.insert_row_slice(0, 0, &vec![bases1[0]]); 63 | m.insert_row_slice(0, 2, &vec![bases1[1]]); 64 | m.insert_row_slice(1, 1, &vec![bases2[0], bases2[1]]); 65 | 66 | let x: Vec = vec![Fr::rand(&mut rng), Fr::rand(&mut rng), Fr::rand(&mut rng)]; 67 | 68 | let y: Vec = vec![ 69 | bases1[0].into_projective().mul(x[0].into_repr()) + bases1[1].mul(x[2].into_repr()), 70 | bases2[0].into_projective().mul(x[1].into_repr()) + bases2[1].mul(x[2].into_repr()), 71 | ] 72 | .into_iter() 73 | .map(|p| p.into_affine()) 74 | .collect::>(); 75 | 76 | let (ek, vk) = PESubspaceSnark::::keygen(&mut rng, &pp, m); 77 | 78 | let pi = PESubspaceSnark::::prove(&mut pp, &ek, &x); 79 | 80 | let b = PESubspaceSnark::::verify(&pp, &vk, &y, &pi); 81 | assert!(b); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/link/snark.rs: -------------------------------------------------------------------------------- 1 | use crate::link::matrix::*; 2 | use ark_ec::{AffineCurve, PairingEngine, ProjectiveCurve}; 3 | use ark_ff::{bytes::ToBytes, One, UniformRand}; 4 | use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, SerializationError}; 5 | use ark_std::io::{Read, Result as IoResult, Write}; 6 | use ark_std::marker::PhantomData; 7 | use ark_std::ops::Neg; 8 | use ark_std::rand::Rng; 9 | use ark_std::vec; 10 | use ark_std::vec::Vec; 11 | 12 | #[derive(Clone, Default, PartialEq, Debug, CanonicalSerialize, CanonicalDeserialize)] 13 | pub struct PP< 14 | G1: Clone + ToBytes + Default + CanonicalSerialize + CanonicalDeserialize, 15 | G2: Clone + ToBytes + Default + CanonicalSerialize + CanonicalDeserialize, 16 | > { 17 | pub l: usize, // # of rows 18 | pub t: usize, // # of cols 19 | pub g1: G1, 20 | pub g2: G2, 21 | } 22 | 23 | impl< 24 | G1: Clone + ToBytes + Default + CanonicalSerialize + CanonicalDeserialize, 25 | G2: Clone + ToBytes + Default + CanonicalSerialize + CanonicalDeserialize, 26 | > PP 27 | { 28 | pub fn new(l: usize, t: usize, g1: &G1, g2: &G2) -> PP { 29 | PP { 30 | l, 31 | t, 32 | g1: g1.clone(), 33 | g2: g2.clone(), 34 | } 35 | } 36 | } 37 | 38 | impl< 39 | G1: Clone + ToBytes + Default + CanonicalSerialize + CanonicalDeserialize, 40 | G2: Clone + ToBytes + Default + CanonicalSerialize + CanonicalDeserialize, 41 | > ToBytes for PP 42 | { 43 | fn write(&self, _: W) -> IoResult<()> { 44 | unimplemented!(); 45 | } 46 | } 47 | 48 | #[derive(Clone, Default, PartialEq, Debug, CanonicalSerialize, CanonicalDeserialize)] 49 | pub struct EK { 50 | pub p: Vec, 51 | } 52 | 53 | impl ToBytes for EK { 54 | fn write(&self, _: W) -> IoResult<()> { 55 | unimplemented!(); 56 | } 57 | } 58 | 59 | #[derive(Clone, Default, PartialEq, Debug, CanonicalSerialize, CanonicalDeserialize)] 60 | pub struct VK { 61 | pub c: Vec, 62 | pub a: G2, 63 | } 64 | 65 | impl ToBytes for VK { 66 | fn write(&self, _: W) -> IoResult<()> { 67 | unimplemented!(); 68 | } 69 | } 70 | 71 | pub trait SubspaceSnark { 72 | type KMtx; 73 | type InVec; 74 | type OutVec; 75 | 76 | type PP; 77 | 78 | type EK; 79 | type VK; 80 | 81 | type Proof; 82 | 83 | fn keygen(rng: &mut R, pp: &Self::PP, m: Self::KMtx) -> (Self::EK, Self::VK); 84 | fn prove(pp: &Self::PP, ek: &Self::EK, x: &[Self::InVec]) -> Self::Proof; 85 | fn verify(pp: &Self::PP, vk: &Self::VK, y: &[Self::OutVec], pi: &Self::Proof) -> bool; 86 | } 87 | 88 | fn vec_to_g2( 89 | pp: &PP, 90 | v: &Vec, 91 | ) -> Vec { 92 | v.iter() 93 | .map(|x| pp.g2.mul(*x).into_affine()) 94 | .collect::>() 95 | } 96 | 97 | pub struct PESubspaceSnark { 98 | pairing_engine_type: PhantomData, 99 | } 100 | 101 | // NB: Now the system is for y = Mx 102 | impl SubspaceSnark for PESubspaceSnark { 103 | type KMtx = SparseMatrix; 104 | type InVec = PE::Fr; 105 | type OutVec = PE::G1Affine; 106 | 107 | type PP = PP; 108 | 109 | type EK = EK; 110 | type VK = VK; 111 | 112 | type Proof = PE::G1Affine; 113 | 114 | fn keygen(rng: &mut R, pp: &Self::PP, m: Self::KMtx) -> (Self::EK, Self::VK) { 115 | let mut k: Vec = Vec::with_capacity(pp.l); 116 | for _ in 0..pp.l { 117 | k.push(PE::Fr::rand(rng)); 118 | } 119 | 120 | let a = PE::Fr::rand(rng); 121 | 122 | let p = SparseLinAlgebra::::sparse_vector_matrix_mult(&k, &m, pp.t); 123 | 124 | let c = scalar_vector_mult::(&a, &k, pp.l); 125 | let ek = EK:: { p }; 126 | let vk = VK:: { 127 | c: vec_to_g2::(pp, &c), 128 | a: pp.g2.mul(a).into_affine(), 129 | }; 130 | (ek, vk) 131 | } 132 | 133 | fn prove(pp: &Self::PP, ek: &Self::EK, x: &[Self::InVec]) -> Self::Proof { 134 | assert_eq!(pp.t, x.len()); 135 | inner_product::(x, &ek.p) 136 | } 137 | 138 | fn verify(pp: &Self::PP, vk: &Self::VK, y: &[Self::OutVec], pi: &Self::Proof) -> bool { 139 | assert_eq!(pp.l, y.len()); 140 | 141 | let mut pairs = vec![]; 142 | for i in 0..y.len() { 143 | pairs.push((PE::G1Prepared::from(y[i]), PE::G2Prepared::from(vk.c[i]))); 144 | } 145 | pairs.push((PE::G1Prepared::from(*pi), PE::G2Prepared::from(vk.a.neg()))); 146 | PE::Fqk::one() == PE::product_of_pairings(pairs.iter()) 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/prover.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | link::{PESubspaceSnark, SubspaceSnark}, 3 | r1cs_to_qap::R1CStoQAP, 4 | Proof, ProvingKey, 5 | }; 6 | use ark_ec::{msm::VariableBaseMSM, AffineCurve, PairingEngine, ProjectiveCurve}; 7 | use ark_ff::{PrimeField, UniformRand, Zero}; 8 | use ark_poly::GeneralEvaluationDomain; 9 | use ark_relations::r1cs::{ 10 | ConstraintSynthesizer, ConstraintSystem, OptimizationGoal, Result as R1CSResult, 11 | }; 12 | use ark_std::rand::Rng; 13 | use ark_std::{cfg_into_iter, cfg_iter, end_timer, start_timer, vec::Vec}; 14 | 15 | #[cfg(feature = "parallel")] 16 | use rayon::prelude::*; 17 | 18 | /// Create a Groth16 proof that is zero-knowledge. 19 | /// This method samples randomness for zero knowledges via `rng`. 20 | #[inline] 21 | pub fn create_random_proof( 22 | circuit: C, 23 | v: E::Fr, 24 | link_v: E::Fr, 25 | pk: &ProvingKey, 26 | rng: &mut R, 27 | ) -> R1CSResult> 28 | where 29 | E: PairingEngine, 30 | C: ConstraintSynthesizer, 31 | R: Rng, 32 | { 33 | let r = E::Fr::rand(rng); 34 | let s = E::Fr::rand(rng); 35 | 36 | create_proof::(circuit, pk, r, s, v, link_v) 37 | } 38 | 39 | /// Create a Groth16 proof using randomness `r` and `s`. 40 | #[inline] 41 | pub fn create_proof( 42 | circuit: C, 43 | pk: &ProvingKey, 44 | r: E::Fr, 45 | s: E::Fr, 46 | v: E::Fr, 47 | link_v: E::Fr, 48 | ) -> R1CSResult> 49 | where 50 | E: PairingEngine, 51 | C: ConstraintSynthesizer, 52 | { 53 | type D = GeneralEvaluationDomain; 54 | 55 | let prover_time = start_timer!(|| "Groth16::Prover"); 56 | let cs = ConstraintSystem::new_ref(); 57 | 58 | // Set the optimization goal 59 | cs.set_optimization_goal(OptimizationGoal::Constraints); 60 | 61 | // Synthesize the circuit. 62 | let synthesis_time = start_timer!(|| "Constraint synthesis"); 63 | circuit.generate_constraints(cs.clone())?; 64 | debug_assert!(cs.is_satisfied().unwrap()); 65 | end_timer!(synthesis_time); 66 | 67 | let lc_time = start_timer!(|| "Inlining LCs"); 68 | cs.finalize(); 69 | end_timer!(lc_time); 70 | 71 | let witness_map_time = start_timer!(|| "R1CS to QAP witness map"); 72 | let h = R1CStoQAP::witness_map::>(cs.clone())?; 73 | end_timer!(witness_map_time); 74 | let h_assignment = cfg_into_iter!(h).map(|s| s.into()).collect::>(); 75 | let c_acc_time = start_timer!(|| "Compute C"); 76 | 77 | let h_acc = VariableBaseMSM::multi_scalar_mul(&pk.h_query, &h_assignment); 78 | drop(h_assignment); 79 | 80 | let s_repr = s.into_repr(); 81 | let r_repr = r.into_repr(); 82 | 83 | // Compute C 84 | let prover = cs.borrow().unwrap(); 85 | let aux_assignment = cfg_iter!(prover.witness_assignment) 86 | .map(|s| s.into_repr()) 87 | .collect::>(); 88 | 89 | let l_aux_acc = VariableBaseMSM::multi_scalar_mul(&pk.l_query, &aux_assignment); 90 | 91 | let r_s_delta_g1 = pk.delta_g1.into_projective().mul(r_repr).mul(s_repr); 92 | let v_eta_delta_inv = pk.eta_delta_inv_g1.into_projective().mul(v.into_repr()); 93 | 94 | end_timer!(c_acc_time); 95 | 96 | let num_inputs = prover.instance_assignment.len(); 97 | let input_assignment_with_one_field = prover.instance_assignment.clone(); 98 | 99 | let input_assignment_with_one = input_assignment_with_one_field[0..num_inputs] 100 | .into_iter() 101 | .map(|s| s.into_repr()) 102 | .collect::>(); 103 | 104 | let input_assignment = input_assignment_with_one[1..].to_vec(); 105 | 106 | drop(prover); 107 | drop(cs); 108 | 109 | let assignment = [&input_assignment[..], &aux_assignment[..]].concat(); 110 | drop(aux_assignment); 111 | 112 | // Compute A 113 | let a_acc_time = start_timer!(|| "Compute A"); 114 | let r_g1 = pk.delta_g1.mul(r); 115 | 116 | let g_a = calculate_coeff(r_g1, &pk.a_query, pk.vk.alpha_g1, &assignment); 117 | 118 | let s_g_a = g_a.mul(s_repr); 119 | end_timer!(a_acc_time); 120 | 121 | // Compute B in G1 if needed 122 | let g1_b = if !r.is_zero() { 123 | let b_g1_acc_time = start_timer!(|| "Compute B in G1"); 124 | let s_g1 = pk.delta_g1.mul(s); 125 | let g1_b = calculate_coeff(s_g1, &pk.b_g1_query, pk.beta_g1, &assignment); 126 | 127 | end_timer!(b_g1_acc_time); 128 | 129 | g1_b 130 | } else { 131 | E::G1Projective::zero() 132 | }; 133 | 134 | // Compute B in G2 135 | let b_g2_acc_time = start_timer!(|| "Compute B in G2"); 136 | let s_g2 = pk.vk.delta_g2.mul(s); 137 | let g2_b = calculate_coeff(s_g2, &pk.b_g2_query, pk.vk.beta_g2, &assignment); 138 | let r_g1_b = g1_b.mul(r_repr); 139 | drop(assignment); 140 | 141 | end_timer!(b_g2_acc_time); 142 | 143 | let c_time = start_timer!(|| "Finish C"); 144 | let mut g_c = s_g_a; 145 | g_c += &r_g1_b; 146 | g_c -= &r_s_delta_g1; 147 | g_c += &l_aux_acc; 148 | g_c += &h_acc; 149 | g_c -= &v_eta_delta_inv; 150 | end_timer!(c_time); 151 | 152 | // Compute D 153 | let d_acc_time = start_timer!(|| "Compute D"); 154 | 155 | let gamma_abc_inputs_source = &pk.vk.gamma_abc_g1; 156 | let gamma_abc_inputs_acc = 157 | VariableBaseMSM::multi_scalar_mul(gamma_abc_inputs_source, &input_assignment_with_one); 158 | 159 | let v_eta_gamma_inv = pk.vk.eta_gamma_inv_g1.into_projective().mul(v.into_repr()); 160 | 161 | let mut g_d = gamma_abc_inputs_acc; 162 | g_d += &v_eta_gamma_inv; 163 | end_timer!(d_acc_time); 164 | 165 | let input_assignment_with_one_with_link_hider: Vec = 166 | [&input_assignment_with_one_field, &[link_v][..]].concat(); 167 | let input_assignment_with_one_with_hiders: Vec = 168 | [&input_assignment_with_one_with_link_hider, &[v][..]].concat(); 169 | let link_time = start_timer!(|| "Compute CP_{link}"); 170 | let link_pi = PESubspaceSnark::::prove( 171 | &pk.vk.link_pp, 172 | &pk.link_ek, 173 | &input_assignment_with_one_with_hiders, 174 | ); 175 | let pedersen_bases_affine = &pk.vk.link_bases; 176 | let pedersen_values_repr = input_assignment_with_one_with_link_hider 177 | .into_iter() 178 | .map(|v| v.into_repr()) 179 | .collect::>(); 180 | let g_d_link = VariableBaseMSM::multi_scalar_mul(&pedersen_bases_affine, &pedersen_values_repr); 181 | 182 | end_timer!(link_time); 183 | 184 | end_timer!(prover_time); 185 | 186 | Ok(Proof { 187 | a: g_a.into_affine(), 188 | b: g2_b.into_affine(), 189 | c: g_c.into_affine(), 190 | d: g_d.into_affine(), 191 | link_d: g_d_link.into_affine(), 192 | link_pi, 193 | }) 194 | } 195 | 196 | fn calculate_coeff( 197 | initial: G::Projective, 198 | query: &[G], 199 | vk_param: G, 200 | assignment: &[::BigInt], 201 | ) -> G::Projective { 202 | let el = query[0]; 203 | let acc = VariableBaseMSM::multi_scalar_mul(&query[1..], assignment); 204 | 205 | let mut res = initial; 206 | res.add_assign_mixed(&el); 207 | res += &acc; 208 | res.add_assign_mixed(&vk_param); 209 | 210 | res 211 | } 212 | -------------------------------------------------------------------------------- /src/r1cs_to_qap.rs: -------------------------------------------------------------------------------- 1 | use ark_ff::{One, PrimeField, Zero}; 2 | use ark_poly::EvaluationDomain; 3 | use ark_std::{cfg_iter, cfg_iter_mut, end_timer, start_timer, vec}; 4 | 5 | use crate::Vec; 6 | use ark_relations::r1cs::{ConstraintSystemRef, Result as R1CSResult, SynthesisError}; 7 | use core::ops::{AddAssign, Deref}; 8 | 9 | #[cfg(feature = "parallel")] 10 | use rayon::prelude::*; 11 | 12 | #[inline] 13 | fn evaluate_constraint<'a, LHS, RHS, R>(terms: &'a [(LHS, usize)], assignment: &'a [RHS]) -> R 14 | where 15 | LHS: One + Send + Sync + PartialEq, 16 | RHS: Send + Sync + core::ops::Mul<&'a LHS, Output = RHS> + Copy, 17 | R: Zero + Send + Sync + AddAssign + core::iter::Sum, 18 | { 19 | // Need to wrap in a closure when using Rayon 20 | #[cfg(feature = "parallel")] 21 | let zero = || R::zero(); 22 | #[cfg(not(feature = "parallel"))] 23 | let zero = R::zero(); 24 | 25 | let res = cfg_iter!(terms).fold(zero, |mut sum, (coeff, index)| { 26 | let val = &assignment[*index]; 27 | 28 | if coeff.is_one() { 29 | sum += *val; 30 | } else { 31 | sum += val.mul(coeff); 32 | } 33 | 34 | sum 35 | }); 36 | 37 | // Need to explicitly call `.sum()` when using Rayon 38 | #[cfg(feature = "parallel")] 39 | return res.sum(); 40 | #[cfg(not(feature = "parallel"))] 41 | return res; 42 | } 43 | 44 | pub(crate) struct R1CStoQAP; 45 | 46 | impl R1CStoQAP { 47 | #[inline] 48 | #[allow(clippy::type_complexity)] 49 | pub(crate) fn instance_map_with_evaluation>( 50 | cs: ConstraintSystemRef, 51 | t: &F, 52 | ) -> R1CSResult<(Vec, Vec, Vec, F, usize, usize)> { 53 | let matrices = cs.to_matrices().unwrap(); 54 | let domain_size = cs.num_constraints() + cs.num_instance_variables(); 55 | let domain = D::new(domain_size).ok_or(SynthesisError::PolynomialDegreeTooLarge)?; 56 | let domain_size = domain.size(); 57 | 58 | let zt = domain.evaluate_vanishing_polynomial(*t); 59 | 60 | // Evaluate all Lagrange polynomials 61 | let coefficients_time = start_timer!(|| "Evaluate Lagrange coefficients"); 62 | let u = domain.evaluate_all_lagrange_coefficients(*t); 63 | end_timer!(coefficients_time); 64 | 65 | let qap_num_variables = (cs.num_instance_variables() - 1) + cs.num_witness_variables(); 66 | 67 | let mut a = vec![F::zero(); qap_num_variables + 1]; 68 | let mut b = vec![F::zero(); qap_num_variables + 1]; 69 | let mut c = vec![F::zero(); qap_num_variables + 1]; 70 | 71 | { 72 | let start = 0; 73 | let end = cs.num_instance_variables(); 74 | let num_constraints = cs.num_constraints(); 75 | a[start..end].copy_from_slice(&u[(start + num_constraints)..(end + num_constraints)]); 76 | } 77 | 78 | for (i, u_i) in u.iter().enumerate().take(cs.num_constraints()) { 79 | for &(ref coeff, index) in &matrices.a[i] { 80 | a[index] += &(*u_i * coeff); 81 | } 82 | for &(ref coeff, index) in &matrices.b[i] { 83 | b[index] += &(*u_i * coeff); 84 | } 85 | for &(ref coeff, index) in &matrices.c[i] { 86 | c[index] += &(*u_i * coeff); 87 | } 88 | } 89 | 90 | Ok((a, b, c, zt, qap_num_variables, domain_size)) 91 | } 92 | 93 | #[inline] 94 | pub(crate) fn witness_map>( 95 | prover: ConstraintSystemRef, 96 | ) -> R1CSResult> { 97 | let matrices = prover.to_matrices().unwrap(); 98 | let zero = F::zero(); 99 | let num_inputs = prover.num_instance_variables(); 100 | let num_constraints = prover.num_constraints(); 101 | let cs = prover.borrow().unwrap(); 102 | let prover = cs.deref(); 103 | 104 | let full_assignment = [ 105 | prover.instance_assignment.as_slice(), 106 | prover.witness_assignment.as_slice(), 107 | ] 108 | .concat(); 109 | 110 | let domain = 111 | D::new(num_constraints + num_inputs).ok_or(SynthesisError::PolynomialDegreeTooLarge)?; 112 | let domain_size = domain.size(); 113 | 114 | let mut a = vec![zero; domain_size]; 115 | let mut b = vec![zero; domain_size]; 116 | 117 | cfg_iter_mut!(a[..num_constraints]) 118 | .zip(cfg_iter_mut!(b[..num_constraints])) 119 | .zip(cfg_iter!(&matrices.a)) 120 | .zip(cfg_iter!(&matrices.b)) 121 | .for_each(|(((a, b), at_i), bt_i)| { 122 | *a = evaluate_constraint(&at_i, &full_assignment); 123 | *b = evaluate_constraint(&bt_i, &full_assignment); 124 | }); 125 | 126 | { 127 | let start = num_constraints; 128 | let end = start + num_inputs; 129 | a[start..end].clone_from_slice(&full_assignment[..num_inputs]); 130 | } 131 | 132 | domain.ifft_in_place(&mut a); 133 | domain.ifft_in_place(&mut b); 134 | 135 | domain.coset_fft_in_place(&mut a); 136 | domain.coset_fft_in_place(&mut b); 137 | 138 | let mut ab = domain.mul_polynomials_in_evaluation_domain(&a, &b); 139 | drop(a); 140 | drop(b); 141 | 142 | let mut c = vec![zero; domain_size]; 143 | cfg_iter_mut!(c[..prover.num_constraints]) 144 | .enumerate() 145 | .for_each(|(i, c)| { 146 | *c = evaluate_constraint(&matrices.c[i], &full_assignment); 147 | }); 148 | 149 | domain.ifft_in_place(&mut c); 150 | domain.coset_fft_in_place(&mut c); 151 | 152 | cfg_iter_mut!(ab) 153 | .zip(c) 154 | .for_each(|(ab_i, c_i)| *ab_i -= &c_i); 155 | 156 | domain.divide_by_vanishing_poly_on_coset_in_place(&mut ab); 157 | domain.coset_ifft_in_place(&mut ab); 158 | 159 | Ok(ab) 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/test.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | create_random_proof, generate_random_parameters, prepare_verifying_key, verify_commitment, 3 | verify_proof, 4 | }; 5 | use ark_ec::{PairingEngine, ProjectiveCurve}; 6 | use ark_ff::UniformRand; 7 | use ark_std::rand::{rngs::StdRng, SeedableRng}; 8 | 9 | use core::ops::MulAssign; 10 | 11 | use ark_ff::Field; 12 | use ark_relations::{ 13 | lc, 14 | r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError}, 15 | }; 16 | 17 | struct MySillyCircuit { 18 | a: Option, 19 | b: Option, 20 | } 21 | 22 | impl ConstraintSynthesizer for MySillyCircuit { 23 | fn generate_constraints( 24 | self, 25 | cs: ConstraintSystemRef, 26 | ) -> Result<(), SynthesisError> { 27 | let a = cs.new_witness_variable(|| self.a.ok_or(SynthesisError::AssignmentMissing))?; 28 | let b = cs.new_witness_variable(|| self.b.ok_or(SynthesisError::AssignmentMissing))?; 29 | let c = cs.new_input_variable(|| { 30 | let mut a = self.a.ok_or(SynthesisError::AssignmentMissing)?; 31 | let b = self.b.ok_or(SynthesisError::AssignmentMissing)?; 32 | 33 | a.mul_assign(&b); 34 | Ok(a) 35 | })?; 36 | 37 | cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c)?; 38 | cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c)?; 39 | cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c)?; 40 | cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c)?; 41 | cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c)?; 42 | cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c)?; 43 | 44 | Ok(()) 45 | } 46 | } 47 | 48 | fn test_prove_and_verify(n_iters: usize) 49 | where 50 | E: PairingEngine, 51 | { 52 | let mut rng = StdRng::seed_from_u64(0u64); 53 | 54 | let pedersen_bases = (0..3) 55 | .map(|_| E::G1Projective::rand(&mut rng).into_affine()) 56 | .collect::>(); 57 | 58 | let params = generate_random_parameters::( 59 | MySillyCircuit { a: None, b: None }, 60 | &pedersen_bases, 61 | &mut rng, 62 | ) 63 | .unwrap(); 64 | 65 | let pvk = prepare_verifying_key::(¶ms.vk); 66 | 67 | for _ in 0..n_iters { 68 | let a = E::Fr::rand(&mut rng); 69 | let b = E::Fr::rand(&mut rng); 70 | let mut c = a; 71 | c.mul_assign(&b); 72 | 73 | // Create commitment randomness 74 | let v = E::Fr::rand(&mut rng); 75 | let link_v = E::Fr::rand(&mut rng); 76 | // Create a LegoGro16 proof with our parameters. 77 | let proof = create_random_proof( 78 | MySillyCircuit { 79 | a: Some(a), 80 | b: Some(b), 81 | }, 82 | v, 83 | link_v, 84 | ¶ms, 85 | &mut rng, 86 | ) 87 | .unwrap(); 88 | 89 | assert!(verify_proof(&pvk, &proof).unwrap()); 90 | assert!(verify_commitment(&pvk, &proof, &[c], &v, &link_v).unwrap()); 91 | assert!(!verify_commitment(&pvk, &proof, &[a], &v, &link_v).unwrap()); 92 | assert!(!verify_commitment(&pvk, &proof, &[c], &a, &link_v).unwrap()); 93 | } 94 | } 95 | 96 | mod bls12_377 { 97 | use super::test_prove_and_verify; 98 | use ark_bls12_377::Bls12_377; 99 | 100 | #[test] 101 | fn prove_and_verify() { 102 | test_prove_and_verify::(100); 103 | } 104 | } 105 | 106 | mod cp6_782 { 107 | use super::test_prove_and_verify; 108 | 109 | use ark_cp6_782::CP6_782; 110 | 111 | #[test] 112 | fn prove_and_verify() { 113 | test_prove_and_verify::(1); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/verifier.rs: -------------------------------------------------------------------------------- 1 | use crate::link::{PESubspaceSnark, SubspaceSnark}; 2 | use ark_ec::{AffineCurve, PairingEngine, ProjectiveCurve}; 3 | use ark_ff::PrimeField; 4 | 5 | use super::{PreparedVerifyingKey, Proof, VerifyingKey}; 6 | 7 | use ark_relations::r1cs::{Result as R1CSResult, SynthesisError}; 8 | 9 | use ark_std::vec; 10 | use ark_std::vec::Vec; 11 | use core::ops::{AddAssign, Neg}; 12 | 13 | /// Prepare the verifying key `vk` for use in proof verification. 14 | pub fn prepare_verifying_key(vk: &VerifyingKey) -> PreparedVerifyingKey { 15 | PreparedVerifyingKey { 16 | vk: vk.clone(), 17 | alpha_g1_beta_g2: E::pairing(vk.alpha_g1, vk.beta_g2), 18 | gamma_g2_neg_pc: vk.gamma_g2.neg().into(), 19 | delta_g2_neg_pc: vk.delta_g2.neg().into(), 20 | } 21 | } 22 | 23 | /// Verify a Groth16 proof `proof` against the prepared verification key `pvk`, 24 | /// with respect to the instance `public_inputs`. 25 | pub fn verify_proof( 26 | pvk: &PreparedVerifyingKey, 27 | proof: &Proof, 28 | ) -> R1CSResult { 29 | let commitments = vec![proof.link_d.into_projective(), proof.d.into_projective()]; 30 | let link_verified = PESubspaceSnark::::verify( 31 | &pvk.vk.link_pp, 32 | &pvk.vk.link_vk, 33 | &commitments 34 | .iter() 35 | .map(|p| p.into_affine()) 36 | .collect::>(), 37 | &proof.link_pi, 38 | ); 39 | 40 | let qap = E::miller_loop( 41 | [ 42 | (proof.a.into(), proof.b.into()), 43 | (proof.c.into(), pvk.delta_g2_neg_pc.clone()), 44 | (proof.d.into(), pvk.gamma_g2_neg_pc.clone()), 45 | ] 46 | .iter(), 47 | ); 48 | 49 | let test = E::final_exponentiation(&qap).ok_or(SynthesisError::UnexpectedIdentity)?; 50 | 51 | Ok(link_verified && test == pvk.alpha_g1_beta_g2) 52 | } 53 | 54 | pub fn verify_commitment( 55 | pvk: &PreparedVerifyingKey, 56 | proof: &Proof, 57 | public_inputs: &[E::Fr], 58 | v: &E::Fr, 59 | link_v: &E::Fr, 60 | ) -> Result { 61 | if (public_inputs.len() + 1) != pvk.vk.gamma_abc_g1.len() { 62 | return Err(SynthesisError::MalformedVerifyingKey); 63 | } 64 | if (public_inputs.len() + 2) != pvk.vk.link_bases.len() { 65 | return Err(SynthesisError::MalformedVerifyingKey); 66 | } 67 | 68 | let mut g_ic = pvk.vk.gamma_abc_g1[0].into_projective(); 69 | for (i, b) in public_inputs.iter().zip(pvk.vk.gamma_abc_g1.iter().skip(1)) { 70 | g_ic.add_assign(&b.mul(i.into_repr())); 71 | } 72 | g_ic.add_assign(&pvk.vk.eta_gamma_inv_g1.mul(v.into_repr())); 73 | 74 | let mut g_link = pvk.vk.link_bases[0].into_projective(); 75 | for (i, b) in public_inputs.iter().zip(pvk.vk.link_bases.iter().skip(1)) { 76 | g_link.add_assign(&b.mul(i.into_repr())); 77 | } 78 | g_link.add_assign(&pvk.vk.link_bases.last().unwrap().mul(link_v.into_repr())); 79 | 80 | Ok(proof.d == g_ic.into_affine() && proof.link_d == g_link.into_affine()) 81 | } 82 | -------------------------------------------------------------------------------- /tests/mimc.rs: -------------------------------------------------------------------------------- 1 | #![warn(unused)] 2 | #![deny( 3 | trivial_casts, 4 | trivial_numeric_casts, 5 | variant_size_differences, 6 | stable_features, 7 | non_shorthand_field_patterns, 8 | renamed_and_removed_lints, 9 | private_in_public, 10 | unsafe_code 11 | )] 12 | 13 | // For randomness (during paramgen and proof generation) 14 | use ark_std::{rand::Rng, UniformRand}; 15 | 16 | // For benchmarking 17 | use std::time::{Duration, Instant}; 18 | 19 | // Bring in some tools for using pairing-friendly curves 20 | // We're going to use the BLS12-377 pairing-friendly elliptic curve. 21 | use ark_bls12_377::{Bls12_377, Fr}; 22 | use ark_ec::ProjectiveCurve; 23 | use ark_ff::Field; 24 | 25 | // We'll use these interfaces to construct our circuit. 26 | use ark_relations::{ 27 | lc, ns, 28 | r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError, Variable}, 29 | }; 30 | 31 | use ark_std::rand::{rngs::StdRng, SeedableRng}; 32 | 33 | const MIMC_ROUNDS: usize = 322; 34 | 35 | /// This is an implementation of MiMC, specifically a 36 | /// variant named `LongsightF322p3` for BLS12-377. 37 | /// See http://eprint.iacr.org/2016/492 for more 38 | /// information about this construction. 39 | /// 40 | /// ``` 41 | /// function LongsightF322p3(xL ⦂ Fp, xR ⦂ Fp) { 42 | /// for i from 0 up to 321 { 43 | /// xL, xR := xR + (xL + Ci)^3, xL 44 | /// } 45 | /// return xL 46 | /// } 47 | /// ``` 48 | fn mimc(mut xl: F, mut xr: F, constants: &[F]) -> F { 49 | assert_eq!(constants.len(), MIMC_ROUNDS); 50 | 51 | for i in 0..MIMC_ROUNDS { 52 | let mut tmp1 = xl; 53 | tmp1.add_assign(&constants[i]); 54 | let mut tmp2 = tmp1; 55 | tmp2.square_in_place(); 56 | tmp2.mul_assign(&tmp1); 57 | tmp2.add_assign(&xr); 58 | xr = xl; 59 | xl = tmp2; 60 | } 61 | 62 | xl 63 | } 64 | 65 | /// This is our demo circuit for proving knowledge of the 66 | /// preimage of a MiMC hash invocation. 67 | struct MiMCDemo<'a, F: Field> { 68 | xl: Option, 69 | xr: Option, 70 | constants: &'a [F], 71 | } 72 | 73 | /// Our demo circuit implements this `Circuit` trait which 74 | /// is used during paramgen and proving in order to 75 | /// synthesize the constraint system. 76 | impl<'a, F: Field> ConstraintSynthesizer for MiMCDemo<'a, F> { 77 | fn generate_constraints(self, cs: ConstraintSystemRef) -> Result<(), SynthesisError> { 78 | assert_eq!(self.constants.len(), MIMC_ROUNDS); 79 | 80 | // Allocate the first component of the preimage. 81 | let mut xl_value = self.xl; 82 | let mut xl = 83 | cs.new_witness_variable(|| xl_value.ok_or(SynthesisError::AssignmentMissing))?; 84 | 85 | // Allocate the second component of the preimage. 86 | let mut xr_value = self.xr; 87 | let mut xr = 88 | cs.new_witness_variable(|| xr_value.ok_or(SynthesisError::AssignmentMissing))?; 89 | 90 | for i in 0..MIMC_ROUNDS { 91 | // xL, xR := xR + (xL + Ci)^3, xL 92 | let ns = ns!(cs, "round"); 93 | let cs = ns.cs(); 94 | 95 | // tmp = (xL + Ci)^2 96 | let tmp_value = xl_value.map(|mut e| { 97 | e.add_assign(&self.constants[i]); 98 | e.square_in_place(); 99 | e 100 | }); 101 | let tmp = 102 | cs.new_witness_variable(|| tmp_value.ok_or(SynthesisError::AssignmentMissing))?; 103 | 104 | cs.enforce_constraint( 105 | lc!() + xl + (self.constants[i], Variable::One), 106 | lc!() + xl + (self.constants[i], Variable::One), 107 | lc!() + tmp, 108 | )?; 109 | 110 | // new_xL = xR + (xL + Ci)^3 111 | // new_xL = xR + tmp * (xL + Ci) 112 | // new_xL - xR = tmp * (xL + Ci) 113 | let new_xl_value = xl_value.map(|mut e| { 114 | e.add_assign(&self.constants[i]); 115 | e.mul_assign(&tmp_value.unwrap()); 116 | e.add_assign(&xr_value.unwrap()); 117 | e 118 | }); 119 | 120 | let new_xl = if i == (MIMC_ROUNDS - 1) { 121 | // This is the last round, xL is our image and so 122 | // we allocate a public input. 123 | cs.new_input_variable(|| new_xl_value.ok_or(SynthesisError::AssignmentMissing))? 124 | } else { 125 | cs.new_witness_variable(|| new_xl_value.ok_or(SynthesisError::AssignmentMissing))? 126 | }; 127 | 128 | cs.enforce_constraint( 129 | lc!() + tmp, 130 | lc!() + xl + (self.constants[i], Variable::One), 131 | lc!() + new_xl - xr, 132 | )?; 133 | 134 | // xR = xL 135 | xr = xl; 136 | xr_value = xl_value; 137 | 138 | // xL = new_xL 139 | xl = new_xl; 140 | xl_value = new_xl_value; 141 | } 142 | 143 | Ok(()) 144 | } 145 | } 146 | 147 | #[test] 148 | fn test_mimc_groth16() { 149 | // We're going to use the Groth16 proving system. 150 | use legogro16::{ 151 | create_random_proof, generate_random_parameters, prepare_verifying_key, verify_commitment, 152 | verify_proof, 153 | }; 154 | 155 | // This may not be cryptographically safe, use 156 | // `OsRng` (for example) in production software. 157 | let mut rng = StdRng::seed_from_u64(0u64); 158 | 159 | // Generate the MiMC round constants 160 | let constants = (0..MIMC_ROUNDS).map(|_| rng.gen()).collect::>(); 161 | 162 | println!("Creating parameters..."); 163 | 164 | // Create parameters for our circuit 165 | let params = { 166 | let c = MiMCDemo:: { 167 | xl: None, 168 | xr: None, 169 | constants: &constants, 170 | }; 171 | 172 | let pedersen_bases = (0..3) 173 | .map(|_| ark_bls12_377::G1Projective::rand(&mut rng).into_affine()) 174 | .collect::>(); 175 | generate_random_parameters::(c, &pedersen_bases, &mut rng).unwrap() 176 | }; 177 | 178 | // Prepare the verification key (for proof verification) 179 | let pvk = prepare_verifying_key(¶ms.vk); 180 | 181 | println!("Creating proofs..."); 182 | 183 | // Let's benchmark stuff! 184 | const SAMPLES: u32 = 50; 185 | let mut total_proving = Duration::new(0, 0); 186 | let mut total_verifying = Duration::new(0, 0); 187 | 188 | // Just a place to put the proof data, so we can 189 | // benchmark deserialization. 190 | // let mut proof_vec = vec![]; 191 | 192 | for _ in 0..SAMPLES { 193 | // Generate a random preimage and compute the image 194 | let xl = rng.gen(); 195 | let xr = rng.gen(); 196 | let image = mimc(xl, xr, &constants); 197 | 198 | // proof_vec.truncate(0); 199 | 200 | let start = Instant::now(); 201 | { 202 | // Create an instance of our circuit (with the 203 | // witness) 204 | let c = MiMCDemo { 205 | xl: Some(xl), 206 | xr: Some(xr), 207 | constants: &constants, 208 | }; 209 | 210 | // Create commitment randomness 211 | let v = Fr::rand(&mut rng); 212 | let link_v = Fr::rand(&mut rng); 213 | // Create a LegoGro16 proof with our parameters. 214 | let proof = create_random_proof(c, v, link_v, ¶ms, &mut rng).unwrap(); 215 | assert!(verify_proof(&pvk, &proof).unwrap()); 216 | assert!(verify_commitment(&pvk, &proof, &[image], &v, &link_v).unwrap()); 217 | 218 | // proof.write(&mut proof_vec).unwrap(); 219 | } 220 | 221 | total_proving += start.elapsed(); 222 | 223 | let start = Instant::now(); 224 | // let proof = Proof::read(&proof_vec[..]).unwrap(); 225 | // Check the proof 226 | 227 | total_verifying += start.elapsed(); 228 | } 229 | let proving_avg = total_proving / SAMPLES; 230 | let proving_avg = 231 | proving_avg.subsec_nanos() as f64 / 1_000_000_000f64 + (proving_avg.as_secs() as f64); 232 | 233 | let verifying_avg = total_verifying / SAMPLES; 234 | let verifying_avg = 235 | verifying_avg.subsec_nanos() as f64 / 1_000_000_000f64 + (verifying_avg.as_secs() as f64); 236 | 237 | println!("Average proving time: {:?} seconds", proving_avg); 238 | println!("Average verifying time: {:?} seconds", verifying_avg); 239 | } 240 | --------------------------------------------------------------------------------