├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── ci.yml │ └── linkify_changelog.yml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── SECURITY.md ├── merkle-tree-example ├── .gitignore ├── Cargo.toml ├── README.md └── src │ ├── common.rs │ ├── constraints.rs │ └── lib.rs ├── rollup ├── .gitignore ├── Cargo.toml ├── README.md └── src │ ├── account.rs │ ├── ledger.rs │ ├── lib.rs │ ├── rollup.rs │ └── transaction.rs ├── scripts └── linkify_changelog.py └── simple-payments ├── .gitignore ├── Cargo.toml ├── README.md └── src ├── account.rs ├── ledger.rs ├── lib.rs ├── random_oracle ├── blake2s │ ├── constraints.rs │ └── mod.rs ├── constraints.rs └── mod.rs ├── signature ├── constraints.rs ├── mod.rs └── schnorr │ ├── constraints.rs │ └── mod.rs └── transaction.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 (main) 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: --all -- --check 31 | 32 | test: 33 | name: Test 34 | runs-on: ubuntu-latest 35 | env: 36 | RUSTFLAGS: -Dwarnings 37 | strategy: 38 | matrix: 39 | rust: 40 | - stable 41 | - nightly 42 | steps: 43 | - name: Checkout 44 | uses: actions/checkout@v2 45 | 46 | - name: Install Rust (${{ matrix.rust }}) 47 | uses: actions-rs/toolchain@v1 48 | with: 49 | profile: minimal 50 | toolchain: ${{ matrix.rust }} 51 | override: true 52 | 53 | - 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 --all 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 --all 72 | if: matrix.rust == 'stable' 73 | 74 | - name: Check benchmarks on nightly 75 | uses: actions-rs/cargo@v1 76 | with: 77 | command: check 78 | args: --all-features --examples --workspace --benches 79 | if: matrix.rust == 'nightly' 80 | 81 | - name: Test 82 | uses: actions-rs/cargo@v1 83 | with: 84 | command: test 85 | args: "--workspace \ 86 | --all-features \ 87 | --exclude ark-poly-benches" 88 | 89 | check_no_std: 90 | name: Check no_std 91 | runs-on: ubuntu-latest 92 | steps: 93 | - name: Checkout 94 | uses: actions/checkout@v2 95 | 96 | - name: Install Rust (${{ matrix.rust }}) 97 | uses: actions-rs/toolchain@v1 98 | with: 99 | toolchain: stable 100 | target: thumbv6m-none-eabi 101 | override: true 102 | 103 | - name: Install Rust ARM64 (${{ matrix.rust }}) 104 | uses: actions-rs/toolchain@v1 105 | with: 106 | toolchain: stable 107 | target: aarch64-unknown-none 108 | override: true 109 | 110 | - uses: actions/cache@v2 111 | with: 112 | path: | 113 | ~/.cargo/registry 114 | ~/.cargo/git 115 | target 116 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 117 | 118 | - name: check 119 | uses: actions-rs/cargo@v1 120 | with: 121 | command: check 122 | args: --examples --workspace --exclude ark-poly-benches --target thumbv6m-none-eabi 123 | 124 | - name: build 125 | uses: actions-rs/cargo@v1 126 | with: 127 | command: build 128 | args: --workspace --exclude ark-poly-benches --target thumbv6m-none-eabi 129 | -------------------------------------------------------------------------------- /.github/workflows/linkify_changelog.yml: -------------------------------------------------------------------------------- 1 | name: Linkify Changelog 2 | 3 | on: 4 | workflow_dispatch 5 | 6 | jobs: 7 | linkify: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout 11 | uses: actions/checkout@v2 12 | - name: Add links 13 | run: python3 scripts/linkify_changelog.py CHANGELOG.md 14 | - name: Commit 15 | run: | 16 | git config user.name github-actions 17 | git config user.email github-actions@github.com 18 | git add . 19 | git commit -m "Linkify Changelog" 20 | git push -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Sample changelog for maintainers 2 | 3 | ## Pending 4 | 5 | ### Breaking changes 6 | - #75 Move bigint from `algebra` to `algebra/utils`. To do this upgrade, do the following find-replace: 7 | - find `algebra/bigint`, replace with `algebra/utils/bigint` 8 | 9 | ### Features 10 | - #58 Add a defined API for every field type, and ensure all fields implement it (Thanks @alexander-zw) 11 | - #71 Add BLS12-381 (Thanks @yelhousni) 12 | 13 | ### Improvements 14 | - #xx Speedup sqrt by removing unnecessary exponentiation 15 | 16 | ### Bug fixes 17 | - #75 get rid of warning for unused constant PI, in complex field 18 | - #78 Reduce prints when inhibit_profiling_info is set. 19 | 20 | ## v1.1.0 21 | 22 | _Special thanks to all downstream projects upstreaming their patches!_ 23 | 24 | ### Breaking Changes 25 | - None! 26 | 27 | ### Features 28 | - #20 Improve operator+ speed for alt_bn, correct the corresponding docs, and reduce code duplication. 29 | - #50 Add mul_by_cofactor to elliptic curve groups 30 | - #50 Add sage scripts for altbn and mnt curves, to verify cofactors and generators 31 | - #52 Change default procps build flags to work with Mac OS 32 | 33 | ### Bug fixes 34 | - #19 Fix is_little_endian always returning true 35 | - #20 Fix operator+ not contributing to alt_bn_128 profiling opcount 36 | - #26 Remove unused warnings in release build 37 | - #39 Update Travis Config for newer Ubuntu mirror defaults 38 | - #50 Fix incorrect mnt4 g2 generator 39 | - #54 Fix is_power_of_two for n > 2^32 40 | - #55 Throw informative error for division by zero in div_ceil 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | # NOTE TO MAINTAINERS 3 | # REPLACE $REPO_NAME AND $DEFAULT_BRANCH 4 | # And check .github/PULL_REQUEST_TEMPLATE's default branch 5 | 6 | Thank you for considering making contributions to `arkworks-rs/$REPO_NAME`! 7 | 8 | Contributing to this repo can be done in several forms, such as participating in discussion or proposing code changes. 9 | To ensure a smooth workflow for all contributors, the following general procedure for contributing has been established: 10 | 11 | 1) Either open or find an issue you'd like to help with 12 | 2) Participate in thoughtful discussion on that issue 13 | 3) If you would like to contribute: 14 | * If the issue is a feature proposal, ensure that the proposal has been accepted 15 | * Ensure that nobody else has already begun working on this issue. 16 | If they have, please try to contact them to collaborate 17 | * 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) 18 | * We suggest using standard Github best practices for contributing: fork the repo, branch from the HEAD of `$DEFAULT_BRANCH`, make some commits on your branch, and submit a PR from the branch to `$DEFAULT_BRANCH`. 19 | More detail on this is below 20 | * Be sure to include a relevant change log entry in the Pending section of CHANGELOG.md (see file for log format) 21 | * If the change is breaking, we may add migration instructions. 22 | 23 | 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. 24 | 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. 25 | 26 | Looking for a good place to start contributing? How about checking out some good first issues 27 | 28 | ## Branch Structure 29 | 30 | `$REPO_NAME` has its default branch as `$DEFAULT_BRANCH`, which is where PRs are merged into. Releases will be periodically made, on no set schedule. 31 | All other branches should be assumed to be miscellaneous feature development branches. 32 | 33 | All downstream users of the library should be using tagged versions of the library pulled from cargo. 34 | 35 | ## How to work on a fork 36 | Please skip this section if you're familiar with contributing to open source github projects. 37 | 38 | First fork the repo from the github UI, and clone it locally. 39 | Then in the repo, you want to add the repo you forked from as a new remote. You do this as: 40 | ```bash 41 | git remote add upstream git@github.com:arkworks-rs/$REPO_NAME.git 42 | ``` 43 | 44 | Then the way you make code contributions is to first think of a branch name that describes your change. 45 | Then do the following: 46 | ```bash 47 | git checkout $DEFAULT_BRANCH 48 | git pull upstream $DEFAULT_BRANCH 49 | git checkout -b $NEW_BRANCH_NAME 50 | ``` 51 | and then work as normal on that branch, and pull request to upstream master when you're done =) 52 | 53 | ## Updating documentation 54 | 55 | All PRs should aim to leave the code more documented than it started with. 56 | Please don't assume that its easy to infer what the code is doing, 57 | as that is almost always not the case for these complex protocols. 58 | (Even when you understand the paper!) 59 | 60 | Its often very useful to describe what is the high level view of what a code block is doing, 61 | 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. 62 | 63 | ## Performance improvements 64 | 65 | All performance improvements should be accompanied with benchmarks improving, or otherwise have it be clear that things have improved. 66 | For some areas of the codebase, performance roughly follows the number of field multiplications, but there are also many areas where 67 | hard to predict low level system effects such as cache locality and superscalar operations become important for performance. 68 | Thus performance can often become very non-intuitive / diverge from minimizing the number of arithmetic operations. -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "merkle-tree-example", 5 | "simple-payments", 6 | "rollup", 7 | ] 8 | 9 | [profile.release] 10 | opt-level = 3 11 | lto = "thin" 12 | incremental = true 13 | panic = 'abort' 14 | 15 | [profile.dev] 16 | opt-level = 0 17 | panic = 'abort' 18 | 19 | [profile.test] 20 | opt-level = 3 21 | lto = "thin" 22 | incremental = true 23 | debug-assertions = true 24 | debug = true 25 | -------------------------------------------------------------------------------- /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 |

Introduction to SNARK Development with `arkworks`

2 | 3 | In this tutorial, we will learn how to write applications for use with state-of-the-art zkSNARKs using the [`arkworks`](https://arkworks.rs) ecosystem of SNARK libraries. 4 | 5 | ## Prerequisites 6 | 7 | Because the `arkworks` ecosystem uses the Rust programming language, this tutorial assumes some familiarity with the basics of Rust. We also assume basic familiarity with zkSNARK concepts, and in particular with the following terminology: 8 | 9 | * Public input/instance: a publicly known object that the verifier can check a zkSNARK proof against. For example, in a proof of membership in a Merkle tree, the Merkle tree root would be a public input. 10 | * Private input/witness: an object that is known only to the prover, for either efficiency or privacy reasons. In the Merkle tree example, the Merkle tree authentication path would be a private input. 11 | * Circuit: an encoding of a computation in a way that can be proven using a zkSNARK. 12 | * Gadget: subcircuits corresponding to useful computations that can be used to build up the full circuit. In the Merkle tree example, a hash function gadget would be used repeatedly. 13 | 14 | ## Instructions 15 | 16 | 1. Ensure that you have the latest version of Rust installed (1.51 at the time of writing). If you do not already have Rust installed, you can do so via [`rustup`](https://rustup.rs/). Linux users, please note that `arkworks` relies on Rust 1.51, which might be more recent than the Rust version provided by your distribution's package repositories; hence, even if you have installed Rust via your package manager, please install the latest Rust via `rustup`. 17 | 18 | 2. Clone this repository via `git clone https://github.com/arkworks-rs/r1cs-tutorial.git` 19 | 20 | 3. (Optional) While Rust works out of the box with your text editor of choice, using [Visual Studio Code](https://code.visualstudio.com/) along with the [`rust-analyzer`](https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer) plugin makes Rust development easier. 21 | 22 | 4. (Optional) Join the Telegram channel for [this tutorial](https://t.me/joinchat/4HzYWAYHVfpiODZh) and for the [`arkworks` ecosystem](https://t.me/joinchat/QaIYxIqLScnonTJ4) to ask questions interactively. 23 | 24 | 5. Proceed to the exercises below. 25 | 26 | ## Exercises 27 | 28 | In this tutorial, we will construct a SNARK-based rollup for a simple payments system. In the course of doing so, you will learn how to use `arkworks` libraries for writing constraint systems, how to debug these circuits for both correctness and performance, and finally how to plug these circuits into zkSNARKs. 29 | 30 | First, checkout the `main` branch in the repository. 31 | 32 | ### Exercise 1: Merkle Tree Example 33 | 34 | We'll design a simple circuit for checking a Merkle tree membership path for a given leaf. 35 | Open [`merkle-tree-example/README.md`](./merkle-tree-example/README.md). 36 | 37 | ### Exercise 2: Validating a single transaction 38 | 39 | We'll design a circuit for validating a single transaction in a simple account-based payment system. 40 | Open [`simple-payments/README.md`](./simple-payments/README.md) to first learn more about the payment system, and then open [`rollup/README.md`](./rollup/README.md) for the instructions for this exercise. 41 | 42 | ### Exercise 3: Writing a rollup circuit 43 | 44 | We'll design a circuit for a rollup for batch verification of transactions in the foregoing payment system. 45 | Open [`rollup/README.md`](./rollup/README.md) for the instructions for this exercise. 46 | 47 | ## Solutions 48 | 49 | If you get stuck on one of the above exercises, or if you wish to compare your solution with ours, check out the [`solutions`](https://github.com/arkworks-rs/r1cs-tutorial/tree/solutions) branch on this repository. 50 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | TODO -------------------------------------------------------------------------------- /merkle-tree-example/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /merkle-tree-example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "merkle-tree-example" 3 | version = "0.3.0" 4 | authors = ["arkworks contributors"] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | ark-ff = { version = "^0.3.0", default-features = false } 9 | ark-ec = { version = "^0.3.0", default-features = false } 10 | ark-ed-on-bls12-381 = { version = "^0.3.0", features = ["r1cs"] } 11 | ark-bls12-381 = { version = "^0.3.0", default-features = false } 12 | ark-std = { version = "^0.3.0", default-features = false } 13 | ark-relations = { version = "^0.3.0", default-features = false } 14 | 15 | ark-r1cs-std = { version = "^0.3.0", default-features = false } 16 | ark-snark = { version = "^0.3.0", default-features = false } 17 | 18 | ark-serialize = { version = "^0.3.0", default-features = false } 19 | 20 | ark-crypto-primitives = { version = "^0.3.0", default-features = true, features = [ "r1cs" ] } 21 | tracing = { version = "0.1", default-features = false, features = [ "attributes" ] } 22 | tracing-subscriber = { version = "0.2" } 23 | -------------------------------------------------------------------------------- /merkle-tree-example/README.md: -------------------------------------------------------------------------------- 1 | # Checking Merkle tree paths 2 | 3 | In this example, our goal is to familiarize ourselves with the workflow of 4 | writing constraints in `arkworks`. We do this by writing a simple constraint system 5 | that just verifies a single Merkle tree authentication path, using the APIs in 6 | https://github.com/arkworks-rs/crypto-primitives/tree/main/src/merkle_tree. 7 | 8 | We will learn how to: 9 | 10 | * Allocate public and private variables in a circuit 11 | * Invoke gadgets 12 | * Invoke SNARKs on the final circuit 13 | 14 | ## Getting started 15 | 16 | Let's start by taking a look at a "native" version of the computation we want to perform. 17 | Let's go to [`src/lib.rs`](src/lib.rs) and look at the code example in `test_merkle_tree`. 18 | 19 | In this example we create a Merkle tree using the Pedersen hash function, and then we check that a claimed path for some leaf corresponds to a given root. 20 | 21 | Our goal is to replicate this check with constraints. 22 | 23 | ## Writing constraints to check Merkle tree paths 24 | 25 | We'll be adding our constraints in [`src/constraints.rs`](src/constraints.rs), inside the function `generate_constraints`. Recall that our task is to check that the prover knows a valid membership path for a given leaf inside a Merkle tree with a given root. 26 | 27 | We start by allocating the Merkle tree root `root` as a public input variable: 28 | ```rust 29 | let root = RootVar::new_input(ark_relations::ns!(cs, "root_var"), || Ok(&self.root))?; 30 | ``` 31 | Let's go over this incantation part-by-part. 32 | * `RootVar` is a [type alias](https://doc.rust-lang.org/book/ch19-04-advanced-types.html#creating-type-synonyms-with-type-aliases) for the output of the hash function used in the Merkle tree. 33 | * `new_input` is a method on the [`AllocVar`](https://docs.rs/ark-r1cs-std/0.3.0/ark_r1cs_std/alloc/trait.AllocVar.html) trait that reserves variables corresponding to the root. The reserved variables are of the public input type, as the root is a public input against which we'll check the private path. 34 | * The [`ns!`](https://docs.rs/ark-relations/0.3.0/ark_relations/macro.ns.html) macro enters a new namespace in the constraint system, with the aim of making it easier to identify failing constraints when debugging. 35 | * The closure `|| Ok(self.root)` provides an (optional) assignment to the variables reserved by `new_input`. The closure is invoked only if we need the assignment. For example, it is not invoked during SNARK setup. 36 | 37 | We similarly allocate the leaf as a public input variable, and allocate the parameters of the hash as "constants" in the constraint system. This means that these parameters are "baked" into the constraint system when it is created, and changing these parameters would result in a different constraint system. Finally, we allocate the membership path as a private witness variable. 38 | 39 | Now, we must fill in the blanks by adding constraints to check the membership path. Go ahead and follow the hint in `constraints.rs` to complete this task. 40 | 41 | ## Testing our constraints 42 | 43 | Once we've written our path-checking constraints, we have to check that the resulting constraint system satisfies two properties: that it accepts a valid membership path, and that it rejects an invalid path. We perform these checks via two tests: `merkle_tree_constraints_correctness` and `merkle_tree_constraints_soundness`. Go ahead and look at those for an example of how to test constraint systems in practice. 44 | 45 | This wraps up this part of the tutorial. Go to the `simple_payments` folder for the next step! 46 | -------------------------------------------------------------------------------- /merkle-tree-example/src/common.rs: -------------------------------------------------------------------------------- 1 | use ark_crypto_primitives::crh::constraints::{CRHGadget, TwoToOneCRHGadget}; 2 | use ark_crypto_primitives::crh::injective_map::constraints::{ 3 | PedersenCRHCompressorGadget, TECompressorGadget, 4 | }; 5 | use ark_crypto_primitives::crh::{ 6 | injective_map::{PedersenCRHCompressor, TECompressor}, 7 | pedersen, 8 | }; 9 | use ark_ed_on_bls12_381::{constraints::EdwardsVar, EdwardsProjective}; 10 | 11 | pub type TwoToOneHash = PedersenCRHCompressor; 12 | #[derive(Clone, PartialEq, Eq, Hash)] 13 | pub struct TwoToOneWindow; 14 | 15 | // `WINDOW_SIZE * NUM_WINDOWS` = 2 * 256 bits = enough for hashing two outputs. 16 | impl pedersen::Window for TwoToOneWindow { 17 | const WINDOW_SIZE: usize = 4; 18 | const NUM_WINDOWS: usize = 128; 19 | } 20 | 21 | pub type LeafHash = PedersenCRHCompressor; 22 | 23 | #[derive(Clone, PartialEq, Eq, Hash)] 24 | pub struct LeafWindow; 25 | 26 | // `WINDOW_SIZE * NUM_WINDOWS` = 2 * 256 bits = enough for hashing two outputs. 27 | impl pedersen::Window for LeafWindow { 28 | const WINDOW_SIZE: usize = 4; 29 | const NUM_WINDOWS: usize = 144; 30 | } 31 | 32 | pub type TwoToOneHashGadget = PedersenCRHCompressorGadget< 33 | EdwardsProjective, 34 | TECompressor, 35 | TwoToOneWindow, 36 | EdwardsVar, 37 | TECompressorGadget, 38 | >; 39 | 40 | pub type LeafHashGadget = PedersenCRHCompressorGadget< 41 | EdwardsProjective, 42 | TECompressor, 43 | LeafWindow, 44 | EdwardsVar, 45 | TECompressorGadget, 46 | >; 47 | 48 | pub type LeafHashParamsVar = >::ParametersVar; 49 | pub type TwoToOneHashParamsVar = 50 | >::ParametersVar; 51 | 52 | pub type ConstraintF = ark_ed_on_bls12_381::Fq; 53 | -------------------------------------------------------------------------------- /merkle-tree-example/src/constraints.rs: -------------------------------------------------------------------------------- 1 | use crate::common::*; 2 | use crate::{Root, SimplePath}; 3 | use ark_crypto_primitives::crh::{TwoToOneCRH, TwoToOneCRHGadget, CRH}; 4 | use ark_crypto_primitives::merkle_tree::constraints::PathVar; 5 | use ark_r1cs_std::prelude::*; 6 | use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError}; 7 | 8 | // (You don't need to worry about what's going on in the next two type definitions, 9 | // just know that these are types that you can use.) 10 | 11 | /// The R1CS equivalent of the the Merkle tree root. 12 | pub type RootVar = >::OutputVar; 13 | 14 | /// The R1CS equivalent of the the Merkle tree path. 15 | pub type SimplePathVar = 16 | PathVar; 17 | 18 | //////////////////////////////////////////////////////////////////////////////// 19 | 20 | pub struct MerkleTreeVerification { 21 | // These are constants that will be embedded into the circuit 22 | pub leaf_crh_params: ::Parameters, 23 | pub two_to_one_crh_params: ::Parameters, 24 | 25 | // These are the public inputs to the circuit. 26 | pub root: Root, 27 | pub leaf: u8, 28 | 29 | // This is the private witness to the circuit. 30 | pub authentication_path: Option, 31 | } 32 | 33 | impl ConstraintSynthesizer for MerkleTreeVerification { 34 | fn generate_constraints( 35 | self, 36 | cs: ConstraintSystemRef, 37 | ) -> Result<(), SynthesisError> { 38 | // First, we allocate the public inputs 39 | let root = RootVar::new_input(ark_relations::ns!(cs, "root_var"), || Ok(&self.root))?; 40 | 41 | let leaf = UInt8::new_input(ark_relations::ns!(cs, "leaf_var"), || Ok(&self.leaf))?; 42 | 43 | // Then, we allocate the public parameters as constants: 44 | let leaf_crh_params = LeafHashParamsVar::new_constant(cs.clone(), &self.leaf_crh_params)?; 45 | let two_to_one_crh_params = 46 | TwoToOneHashParamsVar::new_constant(cs.clone(), &self.two_to_one_crh_params)?; 47 | 48 | // Finally, we allocate our path as a private witness variable: 49 | let path = SimplePathVar::new_witness(ark_relations::ns!(cs, "path_var"), || { 50 | Ok(self.authentication_path.as_ref().unwrap()) 51 | })?; 52 | 53 | let leaf_bytes = vec![leaf; 1]; 54 | 55 | // Now, we have to check membership. How do we do that? 56 | // Hint: look at https://github.com/arkworks-rs/crypto-primitives/blob/6be606259eab0aec010015e2cfd45e4f134cd9bf/src/merkle_tree/constraints.rs#L135 57 | 58 | // TODO: FILL IN THE BLANK! 59 | // let is_member = XYZ 60 | // 61 | // is_member.enforce_equal(&Boolean::TRUE)?; 62 | 63 | Ok(()) 64 | } 65 | } 66 | 67 | // Run this test via `cargo test --release test_merkle_tree`. 68 | #[test] 69 | fn merkle_tree_constraints_correctness() { 70 | use ark_relations::r1cs::{ConstraintLayer, ConstraintSystem, TracingMode}; 71 | use tracing_subscriber::layer::SubscriberExt; 72 | 73 | // Let's set up an RNG for use within tests. Note that this is *not* safe 74 | // for any production use. 75 | let mut rng = ark_std::test_rng(); 76 | 77 | // First, let's sample the public parameters for the hash functions: 78 | let leaf_crh_params = ::setup(&mut rng).unwrap(); 79 | let two_to_one_crh_params = ::setup(&mut rng).unwrap(); 80 | 81 | // Next, let's construct our tree. 82 | // This follows the API in https://github.com/arkworks-rs/crypto-primitives/blob/6be606259eab0aec010015e2cfd45e4f134cd9bf/src/merkle_tree/mod.rs#L156 83 | let tree = crate::SimpleMerkleTree::new( 84 | &leaf_crh_params, 85 | &two_to_one_crh_params, 86 | &[1u8, 2u8, 3u8, 10u8, 9u8, 17u8, 70u8, 45u8], // the i-th entry is the i-th leaf. 87 | ) 88 | .unwrap(); 89 | 90 | // Now, let's try to generate a membership proof for the 5th item, i.e. 9. 91 | let proof = tree.generate_proof(4).unwrap(); // we're 0-indexing! 92 | // This should be a proof for the membership of a leaf with value 9. Let's check that! 93 | 94 | // First, let's get the root we want to verify against: 95 | let root = tree.root(); 96 | 97 | let circuit = MerkleTreeVerification { 98 | // constants 99 | leaf_crh_params, 100 | two_to_one_crh_params, 101 | 102 | // public inputs 103 | root, 104 | leaf: 9u8, 105 | 106 | // witness 107 | authentication_path: Some(proof), 108 | }; 109 | // First, some boilerplat that helps with debugging 110 | let mut layer = ConstraintLayer::default(); 111 | layer.mode = TracingMode::OnlyConstraints; 112 | let subscriber = tracing_subscriber::Registry::default().with(layer); 113 | let _guard = tracing::subscriber::set_default(subscriber); 114 | 115 | // Next, let's make the circuit! 116 | let cs = ConstraintSystem::new_ref(); 117 | circuit.generate_constraints(cs.clone()).unwrap(); 118 | // Let's check whether the constraint system is satisfied 119 | let is_satisfied = cs.is_satisfied().unwrap(); 120 | if !is_satisfied { 121 | // If it isn't, find out the offending constraint. 122 | println!("{:?}", cs.which_is_unsatisfied()); 123 | } 124 | assert!(is_satisfied); 125 | } 126 | 127 | // Run this test via `cargo test --release test_merkle_tree_constraints_soundness`. 128 | // This tests that a given invalid authentication path will fail. 129 | #[test] 130 | fn merkle_tree_constraints_soundness() { 131 | use ark_relations::r1cs::{ConstraintLayer, ConstraintSystem, TracingMode}; 132 | use tracing_subscriber::layer::SubscriberExt; 133 | 134 | // Let's set up an RNG for use within tests. Note that this is *not* safe 135 | // for any production use. 136 | let mut rng = ark_std::test_rng(); 137 | 138 | // First, let's sample the public parameters for the hash functions: 139 | let leaf_crh_params = ::setup(&mut rng).unwrap(); 140 | let two_to_one_crh_params = ::setup(&mut rng).unwrap(); 141 | 142 | // Next, let's construct our tree. 143 | // This follows the API in https://github.com/arkworks-rs/crypto-primitives/blob/6be606259eab0aec010015e2cfd45e4f134cd9bf/src/merkle_tree/mod.rs#L156 144 | let tree = crate::SimpleMerkleTree::new( 145 | &leaf_crh_params, 146 | &two_to_one_crh_params, 147 | &[1u8, 2u8, 3u8, 10u8, 9u8, 17u8, 70u8, 45u8], // the i-th entry is the i-th leaf. 148 | ) 149 | .unwrap(); 150 | 151 | // We just mutate the first leaf 152 | let second_tree = crate::SimpleMerkleTree::new( 153 | &leaf_crh_params, 154 | &two_to_one_crh_params, 155 | &[4u8, 2u8, 3u8, 10u8, 9u8, 17u8, 70u8, 45u8], // the i-th entry is the i-th leaf. 156 | ) 157 | .unwrap(); 158 | 159 | // Now, let's try to generate a membership proof for the 5th item, i.e. 9. 160 | let proof = tree.generate_proof(4).unwrap(); // we're 0-indexing! 161 | 162 | // But, let's get the root we want to verify against: 163 | let wrong_root = second_tree.root(); 164 | 165 | let circuit = MerkleTreeVerification { 166 | // constants 167 | leaf_crh_params, 168 | two_to_one_crh_params, 169 | 170 | // public inputs 171 | root: wrong_root, 172 | leaf: 9u8, 173 | 174 | // witness 175 | authentication_path: Some(proof), 176 | }; 177 | // First, some boilerplate that helps with debugging 178 | let mut layer = ConstraintLayer::default(); 179 | layer.mode = TracingMode::OnlyConstraints; 180 | let subscriber = tracing_subscriber::Registry::default().with(layer); 181 | let _guard = tracing::subscriber::set_default(subscriber); 182 | 183 | // Next, let's make the constraint system! 184 | let cs = ConstraintSystem::new_ref(); 185 | circuit.generate_constraints(cs.clone()).unwrap(); 186 | // Let's check whether the constraint system is satisfied 187 | let is_satisfied = cs.is_satisfied().unwrap(); 188 | // We expect this to fail! 189 | assert!(!is_satisfied); 190 | } 191 | -------------------------------------------------------------------------------- /merkle-tree-example/src/lib.rs: -------------------------------------------------------------------------------- 1 | use ark_crypto_primitives::crh::TwoToOneCRH; 2 | use ark_crypto_primitives::merkle_tree::{Config, MerkleTree, Path}; 3 | 4 | pub mod common; 5 | use common::*; 6 | 7 | mod constraints; 8 | // mod constraints_test; 9 | 10 | #[derive(Clone)] 11 | pub struct MerkleConfig; 12 | impl Config for MerkleConfig { 13 | // Our Merkle tree relies on two hashes: one to hash leaves, and one to hash pairs 14 | // of internal nodes. 15 | type LeafHash = LeafHash; 16 | type TwoToOneHash = TwoToOneHash; 17 | } 18 | 19 | /// A Merkle tree containing account information. 20 | pub type SimpleMerkleTree = MerkleTree; 21 | /// The root of the account Merkle tree. 22 | pub type Root = ::Output; 23 | /// A membership proof for a given account. 24 | pub type SimplePath = Path; 25 | 26 | // Run this test via `cargo test --release test_merkle_tree`. 27 | #[test] 28 | fn test_merkle_tree() { 29 | use ark_crypto_primitives::crh::CRH; 30 | // Let's set up an RNG for use within tests. Note that this is *not* safe 31 | // for any production use. 32 | let mut rng = ark_std::test_rng(); 33 | 34 | // First, let's sample the public parameters for the hash functions: 35 | let leaf_crh_params = ::setup(&mut rng).unwrap(); 36 | let two_to_one_crh_params = ::setup(&mut rng).unwrap(); 37 | 38 | // Next, let's construct our tree. 39 | // This follows the API in https://github.com/arkworks-rs/crypto-primitives/blob/6be606259eab0aec010015e2cfd45e4f134cd9bf/src/merkle_tree/mod.rs#L156 40 | let tree = SimpleMerkleTree::new( 41 | &leaf_crh_params, 42 | &two_to_one_crh_params, 43 | &[1u8, 2u8, 3u8, 10u8, 9u8, 17u8, 70u8, 45u8], // the i-th entry is the i-th leaf. 44 | ) 45 | .unwrap(); 46 | 47 | // Now, let's try to generate a membership proof for the 5th item. 48 | let proof = tree.generate_proof(4).unwrap(); // we're 0-indexing! 49 | // This should be a proof for the membership of a leaf with value 9. Let's check that! 50 | 51 | // First, let's get the root we want to verify against: 52 | let root = tree.root(); 53 | // Next, let's verify the proof! 54 | let result = proof 55 | .verify( 56 | &leaf_crh_params, 57 | &two_to_one_crh_params, 58 | &root, 59 | &[9u8], // The claimed leaf 60 | ) 61 | .unwrap(); 62 | assert!(result); 63 | } 64 | -------------------------------------------------------------------------------- /rollup/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /rollup/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ark-rollup" 3 | version = "0.3.0" 4 | authors = [ "arkworks contributors" ] 5 | description = "A SNARK-based rollup for a simple payments system" 6 | repository = "https://github.com/arkworks-rs/r1cs-tutorial" 7 | keywords = ["cryptography", "relations", "r1cs"] 8 | categories = ["cryptography"] 9 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 10 | license = "MIT/Apache-2.0" 11 | edition = "2018" 12 | 13 | [dependencies] 14 | ark-ff = { version = "^0.3.0", default-features = false } 15 | ark-ec = { version = "^0.3.0", default-features = false } 16 | ark-ed-on-bls12-381 = { version = "^0.3.0", features = ["r1cs"] } 17 | ark-bls12-381 = { version = "^0.3.0" } 18 | ark-std = { version = "^0.3.0", default-features = false } 19 | ark-relations = { version = "^0.3.0", default-features = false, optional = true } 20 | 21 | ark-r1cs-std = { version = "^0.3.0", optional = true, default-features = false } 22 | ark-snark = { version = "^0.3.0", default-features = false } 23 | ark-groth16 = { version = "^0.3.0" } 24 | ark-gm17 = { version = "^0.3.0" } 25 | 26 | ark-serialize = { version = "^0.3.0", default-features = false } 27 | 28 | ark-crypto-primitives = { version = "^0.3.0", default-features = true } 29 | ark-simple-payments = { path = "../simple-payments", default-features = true } 30 | blake2 = { version = "0.9" } 31 | digest = "0.9" 32 | tracing = { version = "0.1", default-features = false, features = [ "attributes" ] } 33 | tracing-subscriber = { version = "0.2" } 34 | derivative = { version = "2.0", features = ["use_core"] } 35 | 36 | [features] 37 | default = [ "std", "parallel", "r1cs" ] 38 | std = [ "ark-ff/std", "ark-ec/std", "ark-std/std", "ark-relations/std", "ark-serialize/std", "ark-crypto-primitives/std" ] 39 | r1cs = [ "ark-relations", "ark-r1cs-std", "ark-crypto-primitives/r1cs" ] 40 | parallel = [ "std", "ark-ff/parallel", "ark-ec/parallel", "ark-std/parallel" ] 41 | -------------------------------------------------------------------------------- /rollup/README.md: -------------------------------------------------------------------------------- 1 | # SNARK-based batch verification of transactions 2 | 3 | SNARK proofs of validity of a batch of transactions are one way increasingly popular to increase the throughput of blockchains while also reducing the size of the blockchain. For example, they are being deployed in the Ethereum community under then name of "rollups". In this crate, we will design a constraint system for proving the validity of a batch of payments in the payment system in `simple-payments`. The high-level specification of this constraint system is defined next. 4 | 5 | ## Batch verification 6 | 7 | At a high level, the constraint system for batch verification works as follows: 8 | 9 | * Public input: initial state root (i.e., before applying current batch of transactions) and final state root (i.e., after applying current batch) 10 | * Private inputs: current batch of transactions 11 | * Checks: 12 | 13 | For each transaction in the batch, check the validity of applying that transaction: 14 | 1) Check a Merkle Tree path wrt initial root that demonstrates the existence of the sender's account. 15 | 2) Check a Merkle Tree path wrt initial root that demonstrates the existence of the receiver's account. 16 | 3) Verify the signature in the transaction with respect to the sender's public key. 17 | 4) Verify that sender.balance >= tx.amount (i.e., sender has sufficient funds). 18 | 5) Compute new balances for both the sender and the receiver. 19 | 6) Check a Merkle Tree path wrt final root for the new sender balance. 20 | 7) Check a Merkle Tree path wrt final root for the new receiver balance. 21 | 22 | To make it easier to write out this constraint system, we've provided gadget equivalents of the key data structures from `simple-payments`. Find these via `cargo doc --open --no-deps`. 23 | 24 | ## Verifying a single transaction 25 | 26 | Our first task will be to verify the state transitions involved when applying a single transaction. Go to [`transaction.rs`](./src/transaction.rs) and fill in the blanks in the `validate` method, following the hints there. Use the pseudocode [above](#batch-verification) and the logic in `simple_payments::transaction::Transaction::validate` as guides. To check if your code works, run `cargo test unary_rollup_validity_test`. 27 | 28 | 29 | ## Verifying a batch of transactions 30 | 31 | Use the foregoing validation logic to verify a batch of transactions in the `generate_constraints` method in [`rollup.rs#148`], and verify that your circuit works via `cargo test single_tx_validity_test` and `cargo test end_to_end`, and then test that you can generate a valid proof via `cargo test snark_verification`. 32 | -------------------------------------------------------------------------------- /rollup/src/account.rs: -------------------------------------------------------------------------------- 1 | use crate::ledger::*; 2 | use crate::ConstraintF; 3 | use ark_ed_on_bls12_381::{constraints::EdwardsVar, EdwardsProjective}; 4 | use ark_r1cs_std::bits::{uint8::UInt8, ToBytesGadget}; 5 | use ark_r1cs_std::prelude::*; 6 | use ark_relations::r1cs::{Namespace, SynthesisError}; 7 | use ark_simple_payments::account::*; 8 | use ark_simple_payments::signature::schnorr::constraints::*; 9 | use std::borrow::Borrow; 10 | 11 | /// Account public key used to verify transaction signatures. 12 | pub type AccountPublicKeyVar = PublicKeyVar; 13 | 14 | /// Account identifier. This prototype supports only 256 accounts at a time. 15 | #[derive(Clone, Debug)] 16 | pub struct AccountIdVar(pub UInt8); 17 | 18 | impl AccountIdVar { 19 | /// Convert the account identifier to bytes. 20 | #[tracing::instrument(target = "r1cs", skip(self))] 21 | pub fn to_bytes_le(&self) -> Vec> { 22 | vec![self.0.clone()] 23 | } 24 | } 25 | 26 | impl AllocVar for AccountIdVar { 27 | #[tracing::instrument(target = "r1cs", skip(cs, f, mode))] 28 | fn new_variable>( 29 | cs: impl Into>, 30 | f: impl FnOnce() -> Result, 31 | mode: AllocationMode, 32 | ) -> Result { 33 | UInt8::new_variable(cs, || f().map(|u| u.borrow().0), mode).map(Self) 34 | } 35 | } 36 | 37 | /// Information about the account, such as the balance and the associated public key. 38 | #[derive(Clone)] 39 | pub struct AccountInformationVar { 40 | /// The account public key. 41 | pub public_key: AccountPublicKeyVar, 42 | /// The balance associated with this this account. 43 | pub balance: AmountVar, 44 | } 45 | 46 | impl AccountInformationVar { 47 | /// Convert the account information to bytes. 48 | #[tracing::instrument(target = "r1cs", skip(self))] 49 | pub fn to_bytes_le(&self) -> Vec> { 50 | self.public_key 51 | .to_bytes() 52 | .unwrap() 53 | .into_iter() 54 | .chain(self.balance.to_bytes_le()) 55 | .collect() 56 | } 57 | } 58 | 59 | impl AllocVar for AccountInformationVar { 60 | #[tracing::instrument(target = "r1cs", skip(cs, f, mode))] 61 | fn new_variable>( 62 | cs: impl Into>, 63 | f: impl FnOnce() -> Result, 64 | mode: AllocationMode, 65 | ) -> Result { 66 | f().and_then(|info| { 67 | let info = info.borrow(); 68 | let cs = cs.into(); 69 | let public_key = 70 | AccountPublicKeyVar::new_variable(cs.clone(), || Ok(&info.public_key), mode)?; 71 | let balance = AmountVar::new_variable(cs, || Ok(&info.balance), mode)?; 72 | Ok(Self { 73 | public_key, 74 | balance, 75 | }) 76 | }) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /rollup/src/ledger.rs: -------------------------------------------------------------------------------- 1 | use crate::ConstraintF; 2 | use ark_crypto_primitives::crh::injective_map::constraints::{ 3 | PedersenCRHCompressorGadget, TECompressorGadget, 4 | }; 5 | use ark_crypto_primitives::crh::{ 6 | constraints::{CRHGadget, TwoToOneCRHGadget}, 7 | injective_map::TECompressor, 8 | }; 9 | use ark_crypto_primitives::merkle_tree::constraints::PathVar; 10 | use ark_ed_on_bls12_381::{constraints::EdwardsVar, EdwardsProjective}; 11 | use ark_r1cs_std::bits::uint64::UInt64; 12 | use ark_r1cs_std::prelude::*; 13 | use ark_relations::r1cs::{Namespace, SynthesisError}; 14 | use ark_simple_payments::ledger::*; 15 | use ark_simple_payments::signature::schnorr::constraints::ParametersVar as SchnorrParamsVar; 16 | use std::borrow::Borrow; 17 | 18 | /// Represents transaction amounts and account balances. 19 | #[derive(Clone, Debug)] 20 | pub struct AmountVar(pub UInt64); 21 | 22 | impl AmountVar { 23 | #[tracing::instrument(target = "r1cs", skip(self))] 24 | pub fn to_bytes_le(&self) -> Vec> { 25 | self.0.to_bytes().unwrap() 26 | } 27 | 28 | #[tracing::instrument(target = "r1cs", skip(self, other))] 29 | pub fn checked_add(&self, other: &Self) -> Result { 30 | // To do a checked add, we add two uint64's directly. 31 | // We also check for overflow, by casting them to field elements, 32 | // adding the field element representation 33 | // converting the field elements to bits 34 | // and then checking if the 65th bit is 0. 35 | // TODO: Demonstrate via circuit profiling if this needs optimization. 36 | let self_bits = self.0.to_bits_le(); 37 | let self_fe = Boolean::le_bits_to_fp_var(&self_bits)?; 38 | let other_bits = other.0.to_bits_le(); 39 | let other_fe = Boolean::le_bits_to_fp_var(&other_bits)?; 40 | let res_fe = self_fe + other_fe; 41 | let res_bz = res_fe.to_bytes()?; 42 | // Ensure 65th bit is 0 43 | // implies 8th word (0-indexed) is 0 44 | res_bz[8].enforce_equal(&UInt8::::constant(0))?; 45 | // Add sum 46 | let result = UInt64::addmany(&[self.0.clone(), other.0.clone()])?; 47 | Ok(AmountVar(result)) 48 | } 49 | 50 | #[tracing::instrument(target = "r1cs", skip(self, other))] 51 | pub fn checked_sub(&self, other: &Self) -> Result { 52 | // To do a checked sub, we convert the uints to a field element. 53 | // We do the sub on the field element. 54 | // We then cast the field element to bits, and ensure the top bits are 0. 55 | // We then convert these bits to a field element 56 | // TODO: Demonstrate via circuit profiling if this needs optimization. 57 | let self_bits = self.0.to_bits_le(); 58 | let self_fe = Boolean::le_bits_to_fp_var(&self_bits)?; 59 | let other_bits = other.0.to_bits_le(); 60 | let other_fe = Boolean::le_bits_to_fp_var(&other_bits)?; 61 | let res_fe = self_fe - other_fe; 62 | let res_bz = res_fe.to_bytes()?; 63 | // Ensure top bit is 0 64 | res_bz[res_bz.len() - 1].enforce_equal(&UInt8::::constant(0))?; 65 | // Convert to UInt64 66 | let res = UInt64::from_bits_le(&res_fe.to_bits_le()?[..64]); 67 | Ok(AmountVar(res)) 68 | } 69 | } 70 | 71 | impl AllocVar for AmountVar { 72 | #[tracing::instrument(target = "r1cs", skip(cs, f, mode))] 73 | fn new_variable>( 74 | cs: impl Into>, 75 | f: impl FnOnce() -> Result, 76 | mode: AllocationMode, 77 | ) -> Result { 78 | UInt64::new_variable(cs.into(), || f().map(|u| u.borrow().0), mode).map(Self) 79 | } 80 | } 81 | 82 | pub type TwoToOneHashGadget = PedersenCRHCompressorGadget< 83 | EdwardsProjective, 84 | TECompressor, 85 | TwoToOneWindow, 86 | EdwardsVar, 87 | TECompressorGadget, 88 | >; 89 | 90 | pub type LeafHashGadget = PedersenCRHCompressorGadget< 91 | EdwardsProjective, 92 | TECompressor, 93 | LeafWindow, 94 | EdwardsVar, 95 | TECompressorGadget, 96 | >; 97 | 98 | pub type AccRootVar = 99 | >::OutputVar; 100 | pub type AccPathVar = PathVar; 101 | pub type LeafHashParamsVar = >::ParametersVar; 102 | pub type TwoToOneHashParamsVar = 103 | >::ParametersVar; 104 | 105 | /// The parameters that are used in transaction creation and validation. 106 | pub struct ParametersVar { 107 | pub sig_params: SchnorrParamsVar, 108 | pub leaf_crh_params: LeafHashParamsVar, 109 | pub two_to_one_crh_params: TwoToOneHashParamsVar, 110 | } 111 | 112 | impl AllocVar for ParametersVar { 113 | #[tracing::instrument(target = "r1cs", skip(cs, f, _mode))] 114 | fn new_variable>( 115 | cs: impl Into>, 116 | f: impl FnOnce() -> Result, 117 | _mode: AllocationMode, 118 | ) -> Result { 119 | let cs = cs.into(); 120 | f().and_then(|params| { 121 | let params: &Parameters = params.borrow(); 122 | let sig_params = SchnorrParamsVar::new_constant(cs.clone(), ¶ms.sig_params)?; 123 | let leaf_crh_params = 124 | LeafHashParamsVar::new_constant(cs.clone(), ¶ms.leaf_crh_params)?; 125 | let two_to_one_crh_params = 126 | TwoToOneHashParamsVar::new_constant(cs.clone(), ¶ms.two_to_one_crh_params)?; 127 | Ok(Self { 128 | sig_params, 129 | leaf_crh_params, 130 | two_to_one_crh_params, 131 | }) 132 | }) 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /rollup/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub type ConstraintF = ark_bls12_381::Fr; 2 | 3 | pub mod account; 4 | pub mod ledger; 5 | pub mod transaction; 6 | 7 | pub mod rollup; 8 | -------------------------------------------------------------------------------- /rollup/src/rollup.rs: -------------------------------------------------------------------------------- 1 | use crate::account::AccountInformationVar; 2 | use crate::ledger::*; 3 | use crate::transaction::TransactionVar; 4 | use crate::ConstraintF; 5 | use ark_r1cs_std::prelude::*; 6 | use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError}; 7 | use ark_simple_payments::{ 8 | account::AccountInformation, 9 | ledger::{AccPath, AccRoot, Parameters, State}, 10 | transaction::Transaction, 11 | }; 12 | 13 | pub struct Rollup { 14 | /// The ledger parameters. 15 | pub ledger_params: Parameters, 16 | /// The Merkle tree root before applying this batch of transactions. 17 | pub initial_root: Option, 18 | /// The Merkle tree root after applying this batch of transactions. 19 | pub final_root: Option, 20 | /// The current batch of transactions. 21 | pub transactions: Option>, 22 | /// The sender's account information and corresponding authentication path, 23 | /// *before* applying the transactions. 24 | pub sender_pre_tx_info_and_paths: Option>, 25 | /// The authentication path corresponding to the sender's account information 26 | /// *after* applying the transactions. 27 | pub sender_post_paths: Option>, 28 | /// The recipient's account information and corresponding authentication path, 29 | /// *before* applying the transactions. 30 | pub recv_pre_tx_info_and_paths: Option>, 31 | /// The authentication path corresponding to the recipient's account information 32 | /// *after* applying the transactions. 33 | pub recv_post_paths: Option>, 34 | /// List of state roots, so that the i-th root is the state roots before applying 35 | /// the i-th transaction. This means that `pre_tx_roots[0] == initial_root`. 36 | pub pre_tx_roots: Option>, 37 | /// List of state roots, so that the i-th root is the state root after applying 38 | /// the i-th transaction. This means that `post_tx_roots[NUM_TX - 1] == final_root`. 39 | pub post_tx_roots: Option>, 40 | } 41 | 42 | impl Rollup { 43 | pub fn new_empty(ledger_params: Parameters) -> Self { 44 | Self { 45 | ledger_params, 46 | initial_root: None, 47 | final_root: None, 48 | transactions: None, 49 | sender_pre_tx_info_and_paths: None, 50 | sender_post_paths: None, 51 | recv_pre_tx_info_and_paths: None, 52 | recv_post_paths: None, 53 | pre_tx_roots: None, 54 | post_tx_roots: None, 55 | } 56 | } 57 | 58 | pub fn only_initial_and_final_roots( 59 | ledger_params: Parameters, 60 | initial_root: AccRoot, 61 | final_root: AccRoot, 62 | ) -> Self { 63 | Self { 64 | ledger_params, 65 | initial_root: Some(initial_root), 66 | final_root: Some(final_root), 67 | transactions: None, 68 | sender_pre_tx_info_and_paths: None, 69 | sender_post_paths: None, 70 | recv_pre_tx_info_and_paths: None, 71 | recv_post_paths: None, 72 | pre_tx_roots: None, 73 | post_tx_roots: None, 74 | } 75 | } 76 | 77 | pub fn with_state_and_transactions( 78 | ledger_params: Parameters, 79 | transactions: &[Transaction], 80 | state: &mut State, 81 | validate_transactions: bool, 82 | ) -> Option { 83 | assert_eq!(transactions.len(), NUM_TX); 84 | let initial_root = Some(state.root()); 85 | let mut sender_pre_tx_info_and_paths = Vec::with_capacity(NUM_TX); 86 | let mut recipient_pre_tx_info_and_paths = Vec::with_capacity(NUM_TX); 87 | let mut sender_post_paths = Vec::with_capacity(NUM_TX); 88 | let mut recipient_post_paths = Vec::with_capacity(NUM_TX); 89 | let mut pre_tx_roots = Vec::with_capacity(NUM_TX); 90 | let mut post_tx_roots = Vec::with_capacity(NUM_TX); 91 | for tx in transactions { 92 | if !tx.validate(&ledger_params, &*state) && validate_transactions { 93 | return None; 94 | } 95 | } 96 | for tx in transactions { 97 | let sender_id = tx.sender; 98 | let recipient_id = tx.recipient; 99 | let pre_tx_root = state.root(); 100 | let sender_pre_acc_info = *state.id_to_account_info.get(&sender_id)?; 101 | let sender_pre_path = state 102 | .account_merkle_tree 103 | .generate_proof(sender_id.0 as usize) 104 | .unwrap(); 105 | let recipient_pre_acc_info = *state.id_to_account_info.get(&recipient_id)?; 106 | let recipient_pre_path = state 107 | .account_merkle_tree 108 | .generate_proof(recipient_id.0 as usize) 109 | .unwrap(); 110 | 111 | if validate_transactions { 112 | state.apply_transaction(&ledger_params, tx)?; 113 | } else { 114 | let _ = state.apply_transaction(&ledger_params, tx); 115 | } 116 | let post_tx_root = state.root(); 117 | let sender_post_path = state 118 | .account_merkle_tree 119 | .generate_proof(sender_id.0 as usize) 120 | .unwrap(); 121 | let recipient_post_path = state 122 | .account_merkle_tree 123 | .generate_proof(recipient_id.0 as usize) 124 | .unwrap(); 125 | sender_pre_tx_info_and_paths.push((sender_pre_acc_info, sender_pre_path)); 126 | recipient_pre_tx_info_and_paths.push((recipient_pre_acc_info, recipient_pre_path)); 127 | sender_post_paths.push(sender_post_path); 128 | recipient_post_paths.push(recipient_post_path); 129 | pre_tx_roots.push(pre_tx_root); 130 | post_tx_roots.push(post_tx_root); 131 | } 132 | 133 | Some(Self { 134 | ledger_params, 135 | initial_root, 136 | final_root: Some(state.root()), 137 | transactions: Some(transactions.to_vec()), 138 | sender_pre_tx_info_and_paths: Some(sender_pre_tx_info_and_paths), 139 | recv_pre_tx_info_and_paths: Some(recipient_pre_tx_info_and_paths), 140 | sender_post_paths: Some(sender_post_paths), 141 | recv_post_paths: Some(recipient_post_paths), 142 | pre_tx_roots: Some(pre_tx_roots), 143 | post_tx_roots: Some(post_tx_roots), 144 | }) 145 | } 146 | } 147 | 148 | impl ConstraintSynthesizer for Rollup { 149 | #[tracing::instrument(target = "r1cs", skip(self, cs))] 150 | fn generate_constraints( 151 | self, 152 | cs: ConstraintSystemRef, 153 | ) -> Result<(), SynthesisError> { 154 | // Declare the parameters as constants. 155 | let ledger_params = ParametersVar::new_constant( 156 | ark_relations::ns!(cs, "Ledger parameters"), 157 | &self.ledger_params, 158 | )?; 159 | // Declare the initial root as a public input. 160 | let initial_root = AccRootVar::new_input(ark_relations::ns!(cs, "Initial root"), || { 161 | self.initial_root.ok_or(SynthesisError::AssignmentMissing) 162 | })?; 163 | 164 | // Declare the final root as a public input. 165 | let final_root = AccRootVar::new_input(ark_relations::ns!(cs, "Final root"), || { 166 | self.final_root.ok_or(SynthesisError::AssignmentMissing) 167 | })?; 168 | let mut prev_root = initial_root; 169 | 170 | for i in 0..NUM_TX { 171 | let tx = self.transactions.as_ref().and_then(|t| t.get(i)); 172 | 173 | let sender_acc_info = self.sender_pre_tx_info_and_paths.as_ref().map(|t| t[i].0); 174 | let sender_pre_path = self.sender_pre_tx_info_and_paths.as_ref().map(|t| &t[i].1); 175 | 176 | let recipient_acc_info = self.recv_pre_tx_info_and_paths.as_ref().map(|t| t[i].0); 177 | let recipient_pre_path = self.recv_pre_tx_info_and_paths.as_ref().map(|t| &t[i].1); 178 | 179 | let sender_post_path = self.sender_post_paths.as_ref().map(|t| &t[i]); 180 | let recipient_post_path = self.recv_post_paths.as_ref().map(|t| &t[i]); 181 | 182 | let pre_tx_root = self.pre_tx_roots.as_ref().map(|t| t[i]); 183 | let post_tx_root = self.post_tx_roots.as_ref().map(|t| t[i]); 184 | 185 | // Let's declare all these things! 186 | 187 | let tx = TransactionVar::new_witness(ark_relations::ns!(cs, "Transaction"), || { 188 | tx.ok_or(SynthesisError::AssignmentMissing) 189 | })?; 190 | // Declare the sender's initial account balance... 191 | let sender_acc_info = AccountInformationVar::new_witness( 192 | ark_relations::ns!(cs, "Sender Account Info"), 193 | || sender_acc_info.ok_or(SynthesisError::AssignmentMissing), 194 | )?; 195 | // ..., corresponding authentication path, ... 196 | let sender_pre_path = 197 | AccPathVar::new_witness(ark_relations::ns!(cs, "Sender Pre-Path"), || { 198 | sender_pre_path.ok_or(SynthesisError::AssignmentMissing) 199 | })?; 200 | // ... and authentication path after the update. 201 | // TODO: Fill in the following 202 | // let sender_post_path = ??? 203 | 204 | // Declare the recipient's initial account balance... 205 | let recipient_acc_info = AccountInformationVar::new_witness( 206 | ark_relations::ns!(cs, "Recipient Account Info"), 207 | || recipient_acc_info.ok_or(SynthesisError::AssignmentMissing), 208 | )?; 209 | // ..., corresponding authentication path, ... 210 | let recipient_pre_path = 211 | AccPathVar::new_witness(ark_relations::ns!(cs, "Recipient Pre-Path"), || { 212 | recipient_pre_path.ok_or(SynthesisError::AssignmentMissing) 213 | })?; 214 | 215 | // ... and authentication path after the update. 216 | // TODO: Fill in the following 217 | // let recipient_post_path = ??? 218 | 219 | // Declare the state root before the transaction... 220 | let pre_tx_root = 221 | AccRootVar::new_witness(ark_relations::ns!(cs, "Pre-tx Root"), || { 222 | pre_tx_root.ok_or(SynthesisError::AssignmentMissing) 223 | })?; 224 | // ... and after the transaction. 225 | let post_tx_root = 226 | AccRootVar::new_witness(ark_relations::ns!(cs, "Post-tx Root"), || { 227 | post_tx_root.ok_or(SynthesisError::AssignmentMissing) 228 | })?; 229 | 230 | // Enforce that the state root after the previous transaction equals 231 | // the starting state root for this transaction 232 | // TODO: Write this 233 | 234 | // Validate that the transaction signature and amount is correct. 235 | // TODO: Uncomment this 236 | // tx.validate( 237 | // &ledger_params, 238 | // &sender_acc_info, 239 | // &sender_pre_path, 240 | // &sender_post_path, 241 | // &recipient_acc_info, 242 | // &recipient_pre_path, 243 | // &recipient_post_path, 244 | // &pre_tx_root, 245 | // &post_tx_root, 246 | // )? 247 | // .enforce_equal(&Boolean::TRUE)?; 248 | 249 | // Set the root for the next transaction. 250 | prev_root = post_tx_root; 251 | } 252 | // Check that the final root is consistent with the root computed after 253 | // applying all state transitions 254 | // TODO: implement this 255 | Ok(()) 256 | } 257 | } 258 | 259 | #[cfg(test)] 260 | mod test { 261 | use super::*; 262 | use ark_relations::r1cs::{ 263 | ConstraintLayer, ConstraintSynthesizer, ConstraintSystem, TracingMode::OnlyConstraints, 264 | }; 265 | use ark_simple_payments::account::AccountId; 266 | use ark_simple_payments::ledger::{Amount, Parameters, State}; 267 | use ark_simple_payments::transaction::Transaction; 268 | use tracing_subscriber::layer::SubscriberExt; 269 | 270 | fn test_cs(rollup: Rollup) -> bool { 271 | let mut layer = ConstraintLayer::default(); 272 | layer.mode = OnlyConstraints; 273 | let subscriber = tracing_subscriber::Registry::default().with(layer); 274 | let _guard = tracing::subscriber::set_default(subscriber); 275 | let cs = ConstraintSystem::new_ref(); 276 | rollup.generate_constraints(cs.clone()).unwrap(); 277 | let result = cs.is_satisfied().unwrap(); 278 | if !result { 279 | println!("{:?}", cs.which_is_unsatisfied()); 280 | } 281 | result 282 | } 283 | 284 | #[test] 285 | fn single_tx_validity_test() { 286 | let mut rng = ark_std::test_rng(); 287 | let pp = Parameters::sample(&mut rng); 288 | let mut state = State::new(32, &pp); 289 | // Let's make an account for Alice. 290 | let (alice_id, _alice_pk, alice_sk) = 291 | state.sample_keys_and_register(&pp, &mut rng).unwrap(); 292 | // Let's give her some initial balance to start with. 293 | state 294 | .update_balance(alice_id, Amount(20)) 295 | .expect("Alice's account should exist"); 296 | // Let's make an account for Bob. 297 | let (bob_id, _bob_pk, bob_sk) = state.sample_keys_and_register(&pp, &mut rng).unwrap(); 298 | 299 | // Alice wants to transfer 5 units to Bob. 300 | let mut temp_state = state.clone(); 301 | let tx1 = Transaction::create(&pp, alice_id, bob_id, Amount(5), &alice_sk, &mut rng); 302 | assert!(tx1.validate(&pp, &temp_state)); 303 | let rollup = Rollup::<1>::with_state_and_transactions( 304 | pp.clone(), 305 | &[tx1.clone()], 306 | &mut temp_state, 307 | true, 308 | ) 309 | .unwrap(); 310 | assert!(test_cs(rollup)); 311 | 312 | let mut temp_state = state.clone(); 313 | let bad_tx = Transaction::create(&pp, alice_id, bob_id, Amount(5), &bob_sk, &mut rng); 314 | assert!(!bad_tx.validate(&pp, &temp_state)); 315 | assert!(matches!(temp_state.apply_transaction(&pp, &bad_tx), None)); 316 | let rollup = Rollup::<1>::with_state_and_transactions( 317 | pp.clone(), 318 | &[bad_tx.clone()], 319 | &mut temp_state, 320 | false, 321 | ) 322 | .unwrap(); 323 | assert!(!test_cs(rollup)); 324 | } 325 | 326 | #[test] 327 | fn end_to_end() { 328 | let mut rng = ark_std::test_rng(); 329 | let pp = Parameters::sample(&mut rng); 330 | let mut state = State::new(32, &pp); 331 | // Let's make an account for Alice. 332 | let (alice_id, _alice_pk, alice_sk) = 333 | state.sample_keys_and_register(&pp, &mut rng).unwrap(); 334 | // Let's give her some initial balance to start with. 335 | state 336 | .update_balance(alice_id, Amount(20)) 337 | .expect("Alice's account should exist"); 338 | // Let's make an account for Bob. 339 | let (bob_id, _bob_pk, bob_sk) = state.sample_keys_and_register(&pp, &mut rng).unwrap(); 340 | 341 | // Alice wants to transfer 5 units to Bob. 342 | let mut temp_state = state.clone(); 343 | let tx1 = Transaction::create(&pp, alice_id, bob_id, Amount(5), &alice_sk, &mut rng); 344 | assert!(tx1.validate(&pp, &temp_state)); 345 | let rollup = Rollup::<1>::with_state_and_transactions( 346 | pp.clone(), 347 | &[tx1.clone()], 348 | &mut temp_state, 349 | true, 350 | ) 351 | .unwrap(); 352 | assert!(test_cs(rollup)); 353 | 354 | let mut temp_state = state.clone(); 355 | let rollup = Rollup::<2>::with_state_and_transactions( 356 | pp.clone(), 357 | &[tx1.clone(), tx1.clone()], 358 | &mut temp_state, 359 | true, 360 | ) 361 | .unwrap(); 362 | assert!(test_cs(rollup)); 363 | assert_eq!( 364 | temp_state 365 | .id_to_account_info 366 | .get(&alice_id) 367 | .unwrap() 368 | .balance, 369 | Amount(10) 370 | ); 371 | assert_eq!( 372 | temp_state.id_to_account_info.get(&bob_id).unwrap().balance, 373 | Amount(10) 374 | ); 375 | 376 | // Let's try creating invalid transactions: 377 | // First, let's try a transaction where the amount is larger than Alice's balance. 378 | let mut temp_state = state.clone(); 379 | let bad_tx = Transaction::create(&pp, alice_id, bob_id, Amount(21), &alice_sk, &mut rng); 380 | assert!(!bad_tx.validate(&pp, &temp_state)); 381 | assert!(matches!(temp_state.apply_transaction(&pp, &bad_tx), None)); 382 | let rollup = Rollup::<1>::with_state_and_transactions( 383 | pp.clone(), 384 | &[bad_tx.clone()], 385 | &mut temp_state, 386 | false, 387 | ) 388 | .unwrap(); 389 | assert!(!test_cs(rollup)); 390 | 391 | // Next, let's try a transaction where the signature is incorrect: 392 | let mut temp_state = state.clone(); 393 | let bad_tx = Transaction::create(&pp, alice_id, bob_id, Amount(5), &bob_sk, &mut rng); 394 | assert!(!bad_tx.validate(&pp, &temp_state)); 395 | assert!(matches!(temp_state.apply_transaction(&pp, &bad_tx), None)); 396 | let rollup = Rollup::<1>::with_state_and_transactions( 397 | pp.clone(), 398 | &[bad_tx.clone()], 399 | &mut temp_state, 400 | false, 401 | ) 402 | .unwrap(); 403 | assert!(!test_cs(rollup)); 404 | 405 | // Finally, let's try a transaction to an non-existant account: 406 | let bad_tx = 407 | Transaction::create(&pp, alice_id, AccountId(10), Amount(5), &alice_sk, &mut rng); 408 | assert!(!bad_tx.validate(&pp, &state)); 409 | assert!(matches!(temp_state.apply_transaction(&pp, &bad_tx), None)); 410 | } 411 | 412 | // Builds a circuit with two txs, using different pubkeys & amounts every time. 413 | // It returns this circuit 414 | fn build_two_tx_circuit() -> Rollup<2> { 415 | use ark_std::rand::Rng; 416 | let mut rng = ark_std::test_rng(); 417 | let pp = Parameters::sample(&mut rng); 418 | let mut state = State::new(32, &pp); 419 | // Let's make an account for Alice. 420 | let (alice_id, _alice_pk, alice_sk) = 421 | state.sample_keys_and_register(&pp, &mut rng).unwrap(); 422 | // Let's give her some initial balance to start with. 423 | state 424 | .update_balance(alice_id, Amount(1000)) 425 | .expect("Alice's account should exist"); 426 | // Let's make an account for Bob. 427 | let (bob_id, _bob_pk, bob_sk) = state.sample_keys_and_register(&pp, &mut rng).unwrap(); 428 | 429 | let amount_to_send = rng.gen_range(0..200); 430 | 431 | // Alice wants to transfer amount_to_send units to Bob, and does this twice 432 | let mut temp_state = state.clone(); 433 | let tx1 = Transaction::create( 434 | &pp, 435 | alice_id, 436 | bob_id, 437 | Amount(amount_to_send), 438 | &alice_sk, 439 | &mut rng, 440 | ); 441 | let rollup = Rollup::<2>::with_state_and_transactions( 442 | pp.clone(), 443 | &[tx1.clone(), tx1.clone()], 444 | &mut temp_state, 445 | true, 446 | ) 447 | .unwrap(); 448 | rollup 449 | } 450 | 451 | #[test] 452 | fn snark_verification() { 453 | use ark_bls12_381::Bls12_381; 454 | use ark_groth16::Groth16; 455 | use ark_snark::SNARK; 456 | // Use a circuit just to generate the circuit 457 | let circuit_defining_cs = build_two_tx_circuit(); 458 | 459 | let mut rng = ark_std::test_rng(); 460 | let (pk, vk) = 461 | Groth16::::circuit_specific_setup(circuit_defining_cs, &mut rng).unwrap(); 462 | 463 | // Use the same circuit but with different inputs to verify against 464 | // This test checks that the SNARK passes on the provided input 465 | let circuit_to_verify_against = build_two_tx_circuit(); 466 | let public_input = [ 467 | circuit_to_verify_against.initial_root.unwrap(), 468 | circuit_to_verify_against.final_root.unwrap(), 469 | ]; 470 | 471 | let proof = Groth16::prove(&pk, circuit_to_verify_against, &mut rng).unwrap(); 472 | let valid_proof = Groth16::verify(&vk, &public_input, &proof).unwrap(); 473 | assert!(valid_proof); 474 | 475 | // Use the same circuit but with different inputs to verify against 476 | // This test checks that the SNARK fails on the wrong input 477 | let circuit_to_verify_against = build_two_tx_circuit(); 478 | // Error introduced, used the final root twice! 479 | let public_input = [ 480 | circuit_to_verify_against.final_root.unwrap(), 481 | circuit_to_verify_against.final_root.unwrap(), 482 | ]; 483 | 484 | let proof = Groth16::prove(&pk, circuit_to_verify_against, &mut rng).unwrap(); 485 | let valid_proof = Groth16::verify(&vk, &public_input, &proof).unwrap(); 486 | assert!(!valid_proof); 487 | } 488 | } 489 | // Optimization ideas: remove `pre_tx_roots` entirely. 490 | -------------------------------------------------------------------------------- /rollup/src/transaction.rs: -------------------------------------------------------------------------------- 1 | use crate::account::{AccountIdVar, AccountInformationVar, AccountPublicKeyVar}; 2 | use crate::ledger::{self, AccPathVar, AccRootVar, AmountVar, ParametersVar}; 3 | use crate::ConstraintF; 4 | use ark_ed_on_bls12_381::{constraints::EdwardsVar, EdwardsProjective}; 5 | use ark_r1cs_std::prelude::*; 6 | use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError}; 7 | use ark_simple_payments::account::AccountInformation; 8 | use ark_simple_payments::ledger::{AccPath, AccRoot, Parameters, State}; 9 | use ark_simple_payments::signature::schnorr::constraints::{ 10 | ParametersVar as SchnorrParamsVar, SchnorrSignatureVerifyGadget, SignatureVar, 11 | }; 12 | use ark_simple_payments::signature::SigVerifyGadget; 13 | use ark_simple_payments::transaction::Transaction; 14 | use std::borrow::Borrow; 15 | 16 | /// Transaction transferring some amount from one account to another. 17 | pub struct TransactionVar { 18 | /// The account information of the sender. 19 | pub sender: AccountIdVar, 20 | /// The account information of the recipient. 21 | pub recipient: AccountIdVar, 22 | /// The amount being transferred from the sender to the receiver. 23 | pub amount: AmountVar, 24 | /// The spend authorization is a signature over the sender, the recipient, 25 | /// and the amount. 26 | pub signature: SignatureVar, 27 | } 28 | 29 | impl TransactionVar { 30 | /// Verify just the signature in the transaction. 31 | #[tracing::instrument(target = "r1cs", skip(self, pp, pub_key))] 32 | fn verify_signature( 33 | &self, 34 | pp: &SchnorrParamsVar, 35 | pub_key: &AccountPublicKeyVar, 36 | ) -> Result, SynthesisError> { 37 | // The authorized message consists of 38 | // (SenderAccId || SenderPubKey || RecipientAccId || RecipientPubKey || Amount) 39 | let mut message = self.sender.to_bytes_le(); 40 | message.extend(self.recipient.to_bytes_le()); 41 | message.extend(self.amount.to_bytes_le()); 42 | SchnorrSignatureVerifyGadget::verify(pp, pub_key, &message, &self.signature) 43 | } 44 | 45 | /// Check that the transaction is valid for the given ledger state. This checks 46 | /// the following conditions: 47 | /// 1. Verify that the signature is valid with respect to the public key 48 | /// corresponding to `self.sender`. 49 | /// 2. Verify that the sender's account has sufficient balance to finance 50 | /// the transaction. 51 | /// 3. Verify that the recipient's account exists. 52 | #[allow(clippy::too_many_arguments)] 53 | #[tracing::instrument( 54 | target = "r1cs", 55 | skip( 56 | self, 57 | parameters, 58 | pre_sender_acc_info, 59 | pre_sender_path, 60 | post_sender_path, 61 | pre_recipient_acc_info, 62 | pre_recipient_path, 63 | post_recipient_path, 64 | pre_root, 65 | post_root 66 | ) 67 | )] 68 | pub fn validate( 69 | &self, 70 | parameters: &ledger::ParametersVar, 71 | pre_sender_acc_info: &AccountInformationVar, 72 | pre_sender_path: &AccPathVar, 73 | post_sender_path: &AccPathVar, 74 | pre_recipient_acc_info: &AccountInformationVar, 75 | pre_recipient_path: &AccPathVar, 76 | post_recipient_path: &AccPathVar, 77 | pre_root: &AccRootVar, 78 | post_root: &AccRootVar, 79 | ) -> Result, SynthesisError> { 80 | // Verify the signature against the sender pubkey. 81 | // TODO: FILL IN THE BLANK 82 | // let sig_verifies = ???; 83 | 84 | // Compute the new sender balance. 85 | let mut post_sender_acc_info = pre_sender_acc_info.clone(); 86 | // TODO: Safely subtract amount sent from the sender's balance 87 | // post_sender_acc_info.balance = ???; 88 | 89 | // TODO: Compute the new receiver balance, ensure its overflow safe. 90 | let mut post_recipient_acc_info = pre_recipient_acc_info.clone(); 91 | // post_recipient_acc_info.balance = ??? 92 | 93 | // Check that the pre-tx sender account information is correct with 94 | // respect to `pre_tx_root`, and that the post-tx sender account 95 | // information is correct with respect to `post_tx_root`. 96 | // HINT: Use the path structs 97 | // TODO: FILL IN THE FOLLOWING 98 | // let sender_exists = ??? 99 | 100 | // let sender_updated_correctly = ??? 101 | 102 | // Check that the pre-tx recipient account information is correct with 103 | // respect to `pre_tx_root`, and that the post-tx recipient account 104 | // information is correct with respect to `post_tx_root`. 105 | // TODO: FILL IN THE FOLLOWING 106 | // let recipient_exists = ??? 107 | 108 | // let recipient_updated_correctly = ??? 109 | 110 | // TODO: Uncomment the following 111 | // sender_exists 112 | // .and(&sender_updated_correctly)? 113 | // .and(&recipient_exists)? 114 | // .and(&recipient_updated_correctly)? 115 | // .and(&sig_verifies) 116 | Err(SynthesisError::Unsatisfiable) 117 | } 118 | } 119 | 120 | impl AllocVar for TransactionVar { 121 | #[tracing::instrument(target = "r1cs", skip(cs, f, mode))] 122 | fn new_variable>( 123 | cs: impl Into>, 124 | f: impl FnOnce() -> Result, 125 | mode: AllocationMode, 126 | ) -> Result { 127 | let cs = cs.into(); 128 | f().and_then(|tx| { 129 | let tx: &Transaction = tx.borrow(); 130 | let sender = AccountIdVar::new_variable(cs.clone(), || Ok(&tx.sender), mode)?; 131 | let recipient = AccountIdVar::new_variable(cs.clone(), || Ok(&tx.recipient), mode)?; 132 | let amount = AmountVar::new_variable(cs.clone(), || Ok(&tx.amount), mode)?; 133 | let signature = SignatureVar::new_variable(cs.clone(), || Ok(&tx.signature), mode)?; 134 | Ok(Self { 135 | sender, 136 | recipient, 137 | amount, 138 | signature, 139 | }) 140 | }) 141 | } 142 | } 143 | 144 | pub struct UnaryRollup { 145 | /// The ledger parameters. 146 | pub ledger_params: Parameters, 147 | /// The Merkle tree root before applying this batch of transactions. 148 | pub initial_root: AccRoot, 149 | /// The Merkle tree root after applying this batch of transactions. 150 | pub final_root: AccRoot, 151 | /// The current batch of transactions. 152 | pub transaction: Transaction, 153 | /// The sender's account information *before* applying the transaction. 154 | pub sender_acc_info: AccountInformation, 155 | /// The sender's authentication path, *before* applying the transaction. 156 | pub sender_pre_path: AccPath, 157 | /// The authentication path corresponding to the sender's account information *after* applying 158 | /// the transactions. 159 | pub sender_post_path: AccPath, 160 | /// The recipient's account information *before* applying the transaction. 161 | pub recv_acc_info: AccountInformation, 162 | /// The recipient's authentication path, *before* applying the transaction. 163 | pub recv_pre_path: AccPath, 164 | /// The authentication path corresponding to the recipient's account information *after* 165 | /// applying the transactions. 166 | pub recv_post_path: AccPath, 167 | } 168 | 169 | impl UnaryRollup { 170 | pub fn with_state_and_transaction( 171 | ledger_params: Parameters, 172 | transaction: Transaction, 173 | state: &mut State, 174 | validate: bool, 175 | ) -> Option { 176 | if validate && !transaction.validate(&ledger_params, &*state) { 177 | return None; 178 | } 179 | 180 | let initial_root = state.root(); 181 | let sender_id = transaction.sender; 182 | let recipient_id = transaction.recipient; 183 | 184 | let sender_acc_info = *state.id_to_account_info.get(&sender_id)?; 185 | let sender_pre_path = state 186 | .account_merkle_tree 187 | .generate_proof(sender_id.0 as usize) 188 | .unwrap(); 189 | 190 | let recv_acc_info = *state.id_to_account_info.get(&recipient_id)?; 191 | let recv_pre_path = state 192 | .account_merkle_tree 193 | .generate_proof(recipient_id.0 as usize) 194 | .unwrap(); 195 | 196 | if validate { 197 | state.apply_transaction(&ledger_params, &transaction)?; 198 | } else { 199 | let _ = state.apply_transaction(&ledger_params, &transaction); 200 | } 201 | 202 | let final_root = state.root(); 203 | let sender_post_path = state 204 | .account_merkle_tree 205 | .generate_proof(sender_id.0 as usize) 206 | .unwrap(); 207 | let recv_post_path = state 208 | .account_merkle_tree 209 | .generate_proof(recipient_id.0 as usize) 210 | .unwrap(); 211 | 212 | Some(UnaryRollup { 213 | ledger_params, 214 | initial_root, 215 | final_root, 216 | transaction, 217 | sender_acc_info, 218 | sender_pre_path, 219 | sender_post_path, 220 | recv_acc_info, 221 | recv_pre_path, 222 | recv_post_path, 223 | }) 224 | } 225 | } 226 | 227 | impl ConstraintSynthesizer for UnaryRollup { 228 | fn generate_constraints( 229 | self, 230 | cs: ConstraintSystemRef, 231 | ) -> Result<(), SynthesisError> { 232 | // Declare the parameters as constants. 233 | let ledger_params = ParametersVar::new_constant( 234 | ark_relations::ns!(cs, "Ledger parameters"), 235 | &self.ledger_params, 236 | )?; 237 | // Declare the initial root as a public input. 238 | let initial_root = AccRootVar::new_input(ark_relations::ns!(cs, "Initial root"), || { 239 | Ok(self.initial_root) 240 | })?; 241 | // Declare the final root as a public input. 242 | let final_root = 243 | AccRootVar::new_input(ark_relations::ns!(cs, "Final root"), || Ok(self.final_root))?; 244 | 245 | // Declare transaction as a witness. 246 | let tx = TransactionVar::new_witness(ark_relations::ns!(cs, "Transaction"), || { 247 | Ok(self.transaction.clone()) 248 | })?; 249 | 250 | // Declare the sender's initial account balance... 251 | let sender_acc_info = AccountInformationVar::new_witness( 252 | ark_relations::ns!(cs, "Sender Account Info"), 253 | || Ok(self.sender_acc_info), 254 | )?; 255 | // ..., corresponding authentication path, ... 256 | let sender_pre_path = 257 | AccPathVar::new_witness(ark_relations::ns!(cs, "Sender Pre-Path"), || { 258 | Ok(self.sender_pre_path.clone()) 259 | })?; 260 | // ... and authentication path after the update. 261 | let sender_post_path = 262 | AccPathVar::new_witness(ark_relations::ns!(cs, "Sender Post-Path"), || { 263 | Ok(self.sender_post_path.clone()) 264 | })?; 265 | 266 | // Declare the recipient's initial account balance... 267 | let recipient_acc_info = AccountInformationVar::new_witness( 268 | ark_relations::ns!(cs, "Recipient Account Info"), 269 | || Ok(self.recv_acc_info), 270 | )?; 271 | // ..., corresponding authentication path, ... 272 | let recipient_pre_path = 273 | AccPathVar::new_witness(ark_relations::ns!(cs, "Recipient Pre-Path"), || { 274 | Ok(self.recv_pre_path.clone()) 275 | })?; 276 | // ... and authentication path after the update. 277 | let recipient_post_path = 278 | AccPathVar::new_witness(ark_relations::ns!(cs, "Recipient Post-Path"), || { 279 | Ok(self.recv_post_path.clone()) 280 | })?; 281 | 282 | // Validate that the transaction signature and amount is correct. 283 | tx.validate( 284 | &ledger_params, 285 | &sender_acc_info, 286 | &sender_pre_path, 287 | &sender_post_path, 288 | &recipient_acc_info, 289 | &recipient_pre_path, 290 | &recipient_post_path, 291 | &initial_root, 292 | &final_root, 293 | )? 294 | .enforce_equal(&Boolean::TRUE) 295 | } 296 | } 297 | 298 | #[cfg(test)] 299 | mod test { 300 | use super::*; 301 | use ark_relations::r1cs::{ 302 | ConstraintLayer, ConstraintSynthesizer, ConstraintSystem, TracingMode::OnlyConstraints, 303 | }; 304 | use ark_simple_payments::ledger::{Amount, Parameters, State}; 305 | use ark_simple_payments::transaction::Transaction; 306 | use tracing_subscriber::layer::SubscriberExt; 307 | 308 | fn test_cs(rollup: UnaryRollup) -> bool { 309 | let mut layer = ConstraintLayer::default(); 310 | layer.mode = OnlyConstraints; 311 | let subscriber = tracing_subscriber::Registry::default().with(layer); 312 | let _guard = tracing::subscriber::set_default(subscriber); 313 | let cs = ConstraintSystem::new_ref(); 314 | rollup.generate_constraints(cs.clone()).unwrap(); 315 | let result = cs.is_satisfied().unwrap(); 316 | if !result { 317 | println!("{:?}", cs.which_is_unsatisfied()); 318 | } 319 | result 320 | } 321 | 322 | #[test] 323 | fn unary_rollup_validity_test() { 324 | let mut rng = ark_std::test_rng(); 325 | let pp = Parameters::sample(&mut rng); 326 | let mut state = State::new(32, &pp); 327 | // Let's make an account for Alice. 328 | let (alice_id, _alice_pk, alice_sk) = 329 | state.sample_keys_and_register(&pp, &mut rng).unwrap(); 330 | // Let's give her some initial balance to start with. 331 | state 332 | .update_balance(alice_id, Amount(20)) 333 | .expect("Alice's account should exist"); 334 | // Let's make an account for Bob. 335 | let (bob_id, _bob_pk, bob_sk) = state.sample_keys_and_register(&pp, &mut rng).unwrap(); 336 | 337 | // Alice wants to transfer 5 units to Bob. 338 | let mut temp_state = state.clone(); 339 | let tx1 = Transaction::create(&pp, alice_id, bob_id, Amount(5), &alice_sk, &mut rng); 340 | assert!(tx1.validate(&pp, &temp_state)); 341 | let rollup = 342 | UnaryRollup::with_state_and_transaction(pp.clone(), tx1, &mut temp_state, true) 343 | .unwrap(); 344 | assert!(test_cs(rollup)); 345 | 346 | let mut temp_state = state.clone(); 347 | let bad_tx = Transaction::create(&pp, alice_id, bob_id, Amount(5), &bob_sk, &mut rng); 348 | assert!(!bad_tx.validate(&pp, &temp_state)); 349 | assert!(matches!(temp_state.apply_transaction(&pp, &bad_tx), None)); 350 | let rollup = 351 | UnaryRollup::with_state_and_transaction(pp.clone(), bad_tx, &mut temp_state, false) 352 | .unwrap(); 353 | assert!(!test_cs(rollup)); 354 | } 355 | } 356 | -------------------------------------------------------------------------------- /scripts/linkify_changelog.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | import fileinput 4 | import os 5 | 6 | # Set this to the name of the repo, if you don't want it to be read from the filesystem. 7 | # It assumes the changelog file is in the root of the repo. 8 | repo_name = "" 9 | 10 | # This script goes through the provided file, and replaces any " \#", 11 | # with the valid mark down formatted link to it. e.g. 12 | # " [\#number](https://github.com/arkworks-rs/template/pull/) 13 | # Note that if the number is for a an issue, github will auto-redirect you when you click the link. 14 | # It is safe to run the script multiple times in succession. 15 | # 16 | # Example usage $ python3 linkify_changelog.py ../CHANGELOG.md 17 | if len(sys.argv) < 2: 18 | print("Must include path to changelog as the first argument to the script") 19 | print("Example Usage: python3 linkify_changelog.py ../CHANGELOG.md") 20 | exit() 21 | 22 | changelog_path = sys.argv[1] 23 | if repo_name == "": 24 | path = os.path.abspath(changelog_path) 25 | components = path.split(os.path.sep) 26 | repo_name = components[-2] 27 | 28 | for line in fileinput.input(inplace=True): 29 | line = re.sub(r"\- #([0-9]*)", r"- [\\#\1](https://github.com/arkworks-rs/" + repo_name + r"/pull/\1)", line.rstrip()) 30 | # edits the current file 31 | print(line) -------------------------------------------------------------------------------- /simple-payments/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /simple-payments/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ark-simple-payments" 3 | version = "0.3.0" 4 | authors = [ "arkworks contributors" ] 5 | description = "A simple payments system" 6 | repository = "https://github.com/arkworks-rs/r1cs-tutorial" 7 | keywords = ["cryptography", "relations", "r1cs"] 8 | categories = ["cryptography"] 9 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 10 | license = "MIT/Apache-2.0" 11 | edition = "2018" 12 | 13 | [dependencies] 14 | ark-ff = { version = "^0.3.0", default-features = false } 15 | ark-ec = { version = "^0.3.0", default-features = false } 16 | ark-ed-on-bls12-381 = { version = "^0.3.0", features = ["r1cs"] } 17 | ark-bls12-381 = { version = "^0.3.0", default-features = false } 18 | ark-std = { version = "^0.3.0", default-features = false } 19 | ark-relations = { version = "^0.3.0", default-features = false, optional = true } 20 | 21 | ark-r1cs-std = { version = "^0.3.0", optional = true, default-features = false } 22 | ark-snark = { version = "^0.3.0", default-features = false } 23 | 24 | ark-serialize = { version = "^0.3.0", default-features = false } 25 | 26 | ark-crypto-primitives = { version = "^0.3.0", default-features = true } 27 | blake2 = { version = "0.9" } 28 | digest = "0.9" 29 | derivative = { version = "2.0", features = ["use_core"] } 30 | tracing = { version = "0.1", default-features = false, features = [ "attributes" ], optional = true } 31 | 32 | [features] 33 | default = [ "std", "parallel", "r1cs" ] 34 | std = [ "ark-ff/std", "ark-ec/std", "ark-std/std", "ark-relations/std", "ark-serialize/std", "ark-crypto-primitives/std" ] 35 | r1cs = [ "ark-relations", "ark-r1cs-std", "ark-crypto-primitives/r1cs" ] 36 | parallel = [ "std", "ark-ff/parallel", "ark-ec/parallel", "ark-std/parallel" ] 37 | -------------------------------------------------------------------------------- /simple-payments/README.md: -------------------------------------------------------------------------------- 1 | # Applying simple transactions inside SNARKs 2 | 3 | In this part of the tutorial, we will look into how a simple account-based payment system can be designed on top of `arkworks` APIs in Rust. At the end of this step, you should be familiar with APIs for cryptographic primitives in `arkworks`. 4 | 5 | ## High-level architecture 6 | 7 | Our payment system maintains a ledger consisting of accounts with corresponding balances. In more detail, an "account" is a `(AccountID, SigPubKey, Balance)` triple. The ledger maintains a Merkle tree atop this list of accounts, so that the i-th leaf corresponds to the i-th AccountID. For simplicity and efficiency, in this tutorial we fix the number of accounts to be a small number (say, 256). 8 | 9 | To register an account via `ledger::State::register`, a user provides their signature public key to the ledger, and receives a unique AccountID in return. The ledger stores the public key and an initial balance of 0 for this identifier. 10 | `AccountID`s are generated sequentially. That is, if `n` accounts have been registered so far, then the next registration will return `AccountID = n+1`. 11 | 12 | To transfer value from their account to another account, the user first creates a `Transaction` consisting of the following pieces of information: 13 | * Sender's account identifier 14 | * Recipient's account identifier 15 | * Transaction amount 16 | * Signature on the previous three parts, using the signature public key associated with the sender's account. 17 | 18 | The user then publishes this to the ledger, which applies the transaction via `ledger::State::apply_transaction`. 19 | 20 | The latter method updates the ledger's information if the following conditions are satisfied: 21 | * The sender's account exists 22 | * The recipient's account exists 23 | * The sender's account contains a balance greater than or equal to the transaction amount 24 | * The signature is valid with respect to the public key stored in the sender's account 25 | 26 | To enforce this logic, `Transaction::verify` performs the following steps on input a transaction `tx` and existing ledger state `State`. 27 | * Look up the `(SigPubKey, Balance)` tuple corresponding to the sender's ID in the Merkle tree in `State`. 28 | * Verify the transaction signature with respect to `SigPubKey`. 29 | * Check that the `tx.amount <= Balance`. 30 | * Check that the Merkle tree in `State` contains a path corresponding to the current recipient's ID. 31 | 32 | If these checks pass, the ledger decrements the sender's account balance by `tx.amount`, increments the recipient's balance by `tx.amount`, and updates the appropriate paths in the Merkle tree. 33 | 34 | ## Cryptographic primitives 35 | 36 | ### Signature scheme 37 | 38 | We use a simple custom implementation of Schnorr signatures over the prime order subgroup of the [Jubjub](https://z.cash/technology/jubjub/) curve. This curve is implemented in the [ark-ed-on-bls12-381](https://docs.rs/ark-ed-on-bls12-381/0.3.0/ark_ed_on_bls12_381/) crate. Our Schnorr signature implementation can be found in [`src/signature/schnorr/mod.rs`](./src/signature/schnorr/mod.rs). 39 | 40 | ### Merkle tree 41 | 42 | Our implementation uses the Merkle tree of [`ark-crypto-primitives`](https://docs.rs/ark-crypto-primitives/0.3.0/ark_crypto_primitives/merkle_tree/index.html). This is the same tree that we saw in the `merkle-tree-example` step. In our system, the concrete underlying hash function is the Pedersen hash function, as implemented in the [`ark-crypto-primitives` crate](https://docs.rs/ark-crypto-primitives/0.3.0/ark_crypto_primitives/crh/pedersen/index.html). This hash is implemented over the prime-order subgroup of the Jubjub curve. 43 | 44 | 45 | ## Code walk-through 46 | 47 | To get an overview of important data structures as well as their associated methods, run `cargo doc --open --no-deps`. 48 | -------------------------------------------------------------------------------- /simple-payments/src/account.rs: -------------------------------------------------------------------------------- 1 | use crate::ledger::*; 2 | use crate::signature::schnorr; 3 | use ark_ed_on_bls12_381::EdwardsProjective; 4 | 5 | /// Account public key used to verify transaction signatures. 6 | pub type AccountPublicKey = schnorr::PublicKey; 7 | /// Account secret key used to create transaction signatures. 8 | pub type AccountSecretKey = schnorr::SecretKey; 9 | 10 | /// Account identifier. This prototype supports only 256 accounts at a time. 11 | #[derive(Hash, Eq, PartialEq, Copy, Clone, Ord, PartialOrd, Debug)] 12 | pub struct AccountId(pub u8); 13 | 14 | impl AccountId { 15 | /// Convert the account identifier to bytes. 16 | pub fn to_bytes_le(&self) -> Vec { 17 | vec![self.0] 18 | } 19 | } 20 | 21 | impl AccountId { 22 | /// Increment the identifier in place. 23 | pub(crate) fn checked_increment(&mut self) -> Option<()> { 24 | self.0.checked_add(1).map(|result| self.0 = result) 25 | } 26 | } 27 | 28 | /// Information about the account, such as the balance and the associated public key. 29 | #[derive(Hash, Eq, PartialEq, Copy, Clone)] 30 | pub struct AccountInformation { 31 | /// The account public key. 32 | pub public_key: AccountPublicKey, 33 | /// The balance associated with this this account. 34 | pub balance: Amount, 35 | } 36 | 37 | impl AccountInformation { 38 | /// Convert the account information to bytes. 39 | pub fn to_bytes_le(&self) -> Vec { 40 | ark_ff::to_bytes![self.public_key, self.balance.to_bytes_le()].unwrap() 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /simple-payments/src/ledger.rs: -------------------------------------------------------------------------------- 1 | use crate::account::{AccountId, AccountInformation, AccountPublicKey, AccountSecretKey}; 2 | use crate::signature::{schnorr, SignatureScheme}; 3 | use crate::transaction::Transaction; 4 | use ark_crypto_primitives::crh::{ 5 | injective_map::{PedersenCRHCompressor, TECompressor}, 6 | pedersen, TwoToOneCRH, CRH, 7 | }; 8 | use ark_crypto_primitives::merkle_tree::{self, MerkleTree, Path}; 9 | use ark_ed_on_bls12_381::EdwardsProjective; 10 | use ark_std::rand::Rng; 11 | use std::collections::HashMap; 12 | 13 | /// Represents transaction amounts and account balances. 14 | #[derive(Hash, Eq, PartialEq, Copy, Clone, PartialOrd, Ord, Debug)] 15 | pub struct Amount(pub u64); 16 | 17 | impl Amount { 18 | pub fn to_bytes_le(&self) -> Vec { 19 | self.0.to_le_bytes().to_vec() 20 | } 21 | 22 | pub fn checked_add(self, other: Self) -> Option { 23 | self.0.checked_add(other.0).map(Self) 24 | } 25 | 26 | pub fn checked_sub(self, other: Self) -> Option { 27 | self.0.checked_sub(other.0).map(Self) 28 | } 29 | } 30 | 31 | /// The parameters that are used in transaction creation and validation. 32 | #[derive(Clone)] 33 | pub struct Parameters { 34 | pub sig_params: schnorr::Parameters, 35 | pub leaf_crh_params: ::Parameters, 36 | pub two_to_one_crh_params: ::Parameters, 37 | } 38 | 39 | impl Parameters { 40 | pub fn sample(rng: &mut R) -> Self { 41 | let sig_params = schnorr::Schnorr::setup(rng).unwrap(); 42 | let leaf_crh_params = ::setup(rng).unwrap(); 43 | let two_to_one_crh_params = ::setup(rng).unwrap(); 44 | Self { 45 | sig_params, 46 | leaf_crh_params, 47 | two_to_one_crh_params, 48 | } 49 | } 50 | } 51 | 52 | pub type TwoToOneHash = PedersenCRHCompressor; 53 | 54 | #[derive(Clone, PartialEq, Eq, Hash)] 55 | pub struct TwoToOneWindow; 56 | 57 | // `WINDOW_SIZE * NUM_WINDOWS` = 2 * 256 bits = enough for hashing two outputs. 58 | impl pedersen::Window for TwoToOneWindow { 59 | const WINDOW_SIZE: usize = 128; 60 | const NUM_WINDOWS: usize = 4; 61 | } 62 | 63 | pub type LeafHash = PedersenCRHCompressor; 64 | 65 | #[derive(Clone, PartialEq, Eq, Hash)] 66 | pub struct LeafWindow; 67 | 68 | // `WINDOW_SIZE * NUM_WINDOWS` = 2 * 256 bits = enough for hashing two outputs. 69 | impl pedersen::Window for LeafWindow { 70 | const WINDOW_SIZE: usize = 144; 71 | const NUM_WINDOWS: usize = 4; 72 | } 73 | 74 | #[derive(Clone)] 75 | pub struct MerkleConfig; 76 | impl merkle_tree::Config for MerkleConfig { 77 | type LeafHash = LeafHash; 78 | type TwoToOneHash = TwoToOneHash; 79 | } 80 | 81 | /// A Merkle tree containing account information. 82 | pub type AccMerkleTree = MerkleTree; 83 | /// The root of the account Merkle tree. 84 | pub type AccRoot = ::Output; 85 | /// A membership proof for a given account. 86 | pub type AccPath = Path; 87 | 88 | #[derive(Clone)] 89 | pub struct State { 90 | /// What is the next available account identifier? 91 | pub next_available_account: Option, 92 | /// A merkle tree mapping where the i-th leaf corresponds to the i-th account's 93 | /// information (= balance and public key). 94 | pub account_merkle_tree: AccMerkleTree, 95 | /// A mapping from an account's identifier to its information (= balance and public key). 96 | pub id_to_account_info: HashMap, 97 | /// A mapping from a public key to an account's identifier. 98 | pub pub_key_to_id: HashMap, AccountId>, 99 | } 100 | 101 | impl State { 102 | /// Create an empty ledger that supports `num_accounts` accounts. 103 | pub fn new(num_accounts: usize, parameters: &Parameters) -> Self { 104 | let height = ark_std::log2(num_accounts); 105 | let account_merkle_tree = MerkleTree::blank( 106 | ¶meters.leaf_crh_params, 107 | ¶meters.two_to_one_crh_params, 108 | height as usize, 109 | ) 110 | .unwrap(); 111 | let pub_key_to_id = HashMap::with_capacity(num_accounts); 112 | let id_to_account_info = HashMap::with_capacity(num_accounts); 113 | Self { 114 | next_available_account: Some(AccountId(1)), 115 | account_merkle_tree, 116 | id_to_account_info, 117 | pub_key_to_id, 118 | } 119 | } 120 | 121 | /// Return the root of the account Merkle tree. 122 | pub fn root(&self) -> AccRoot { 123 | self.account_merkle_tree.root() 124 | } 125 | 126 | /// Create a new account with public key `pub_key`. Returns a fresh account identifier 127 | /// if there is space for a new account, and returns `None` otherwise. 128 | /// The initial balance of the new account is 0. 129 | pub fn register(&mut self, public_key: AccountPublicKey) -> Option { 130 | self.next_available_account.and_then(|id| { 131 | // Construct account information for the new account. 132 | let account_info = AccountInformation { 133 | public_key, 134 | balance: Amount(0), 135 | }; 136 | // Insert information into the relevant accounts. 137 | self.pub_key_to_id.insert(public_key, id); 138 | self.account_merkle_tree 139 | .update(id.0 as usize, &account_info.to_bytes_le()) 140 | .expect("should exist"); 141 | self.id_to_account_info.insert(id, account_info); 142 | // Increment the next account identifier. 143 | self.next_available_account 144 | .as_mut() 145 | .and_then(|cur| cur.checked_increment())?; 146 | Some(id) 147 | }) 148 | } 149 | 150 | /// Samples keys and registers these in the ledger. 151 | pub fn sample_keys_and_register( 152 | &mut self, 153 | ledger_params: &Parameters, 154 | rng: &mut R, 155 | ) -> Option<(AccountId, AccountPublicKey, AccountSecretKey)> { 156 | let (pub_key, secret_key) = 157 | schnorr::Schnorr::keygen(&ledger_params.sig_params, rng).unwrap(); 158 | self.register(pub_key).map(|id| (id, pub_key, secret_key)) 159 | } 160 | 161 | /// Update the balance of `id` to `new_amount`. 162 | /// Returns `Some(())` if an account with identifier `id` exists already, and `None` 163 | /// otherwise. 164 | pub fn update_balance(&mut self, id: AccountId, new_amount: Amount) -> Option<()> { 165 | let tree = &mut self.account_merkle_tree; 166 | self.id_to_account_info.get_mut(&id).map(|account_info| { 167 | account_info.balance = new_amount; 168 | tree.update(id.0 as usize, &account_info.to_bytes_le()) 169 | .expect("should exist"); 170 | }) 171 | } 172 | 173 | /// Update the state by applying the transaction `tx`, if `tx` is valid. 174 | pub fn apply_transaction(&mut self, pp: &Parameters, tx: &Transaction) -> Option<()> { 175 | if tx.validate(pp, self) { 176 | let old_sender_bal = self.id_to_account_info.get(&tx.sender)?.balance; 177 | let old_receiver_bal = self.id_to_account_info.get(&tx.recipient)?.balance; 178 | let new_sender_bal = old_sender_bal.checked_sub(tx.amount)?; 179 | let new_receiver_bal = old_receiver_bal.checked_add(tx.amount)?; 180 | self.update_balance(tx.sender, new_sender_bal); 181 | self.update_balance(tx.recipient, new_receiver_bal); 182 | Some(()) 183 | } else { 184 | None 185 | } 186 | } 187 | } 188 | 189 | #[cfg(test)] 190 | mod test { 191 | use super::{AccountId, Amount, Parameters, State}; 192 | use crate::transaction::Transaction; 193 | 194 | #[test] 195 | fn end_to_end() { 196 | let mut rng = ark_std::test_rng(); 197 | let pp = Parameters::sample(&mut rng); 198 | let mut state = State::new(32, &pp); 199 | // Let's make an account for Alice. 200 | let (alice_id, _alice_pk, alice_sk) = 201 | state.sample_keys_and_register(&pp, &mut rng).unwrap(); 202 | // Let's give her some initial balance to start with. 203 | state 204 | .update_balance(alice_id, Amount(10)) 205 | .expect("Alice's account should exist"); 206 | // Let's make an account for Bob. 207 | let (bob_id, _bob_pk, bob_sk) = state.sample_keys_and_register(&pp, &mut rng).unwrap(); 208 | 209 | // Alice wants to transfer 5 units to Bob. 210 | let tx1 = Transaction::create(&pp, alice_id, bob_id, Amount(5), &alice_sk, &mut rng); 211 | assert!(tx1.validate(&pp, &state)); 212 | state.apply_transaction(&pp, &tx1).expect("should work"); 213 | // Let's try creating invalid transactions: 214 | // First, let's try a transaction where the amount is larger than Alice's balance. 215 | let bad_tx = Transaction::create(&pp, alice_id, bob_id, Amount(6), &alice_sk, &mut rng); 216 | assert!(!bad_tx.validate(&pp, &state)); 217 | assert!(matches!(state.apply_transaction(&pp, &bad_tx), None)); 218 | // Next, let's try a transaction where the signature is incorrect: 219 | let bad_tx = Transaction::create(&pp, alice_id, bob_id, Amount(5), &bob_sk, &mut rng); 220 | assert!(!bad_tx.validate(&pp, &state)); 221 | assert!(matches!(state.apply_transaction(&pp, &bad_tx), None)); 222 | 223 | // Finally, let's try a transaction to an non-existant account: 224 | let bad_tx = 225 | Transaction::create(&pp, alice_id, AccountId(10), Amount(5), &alice_sk, &mut rng); 226 | assert!(!bad_tx.validate(&pp, &state)); 227 | assert!(matches!(state.apply_transaction(&pp, &bad_tx), None)); 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /simple-payments/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod account; 2 | pub mod ledger; 3 | pub mod transaction; 4 | 5 | pub mod random_oracle; 6 | pub mod signature; 7 | 8 | extern crate derivative; 9 | -------------------------------------------------------------------------------- /simple-payments/src/random_oracle/blake2s/constraints.rs: -------------------------------------------------------------------------------- 1 | use crate::random_oracle::{blake2s, RandomOracleGadget}; 2 | use ark_crypto_primitives::prf::blake2s::constraints::{evaluate_blake2s, OutputVar}; 3 | use ark_ff::{Field, PrimeField}; 4 | use ark_r1cs_std::prelude::*; 5 | use ark_relations::r1cs::{Namespace, SynthesisError}; 6 | use ark_std::vec::Vec; 7 | 8 | use core::borrow::Borrow; 9 | 10 | #[derive(Clone)] 11 | pub struct ParametersVar; 12 | 13 | pub struct ROGadget; 14 | 15 | impl RandomOracleGadget for ROGadget { 16 | type OutputVar = OutputVar; 17 | type ParametersVar = ParametersVar; 18 | 19 | // #[tracing::instrument(target = "r1cs", skip(input, r))] 20 | fn evaluate( 21 | _: &Self::ParametersVar, 22 | input: &[UInt8], 23 | ) -> Result { 24 | let mut input_bits = Vec::with_capacity(512); 25 | for byte in input.iter() { 26 | input_bits.extend_from_slice(&byte.to_bits_le()?); 27 | } 28 | let mut result = Vec::new(); 29 | for int in evaluate_blake2s(&input_bits)?.into_iter() { 30 | let chunk = int.to_bytes()?; 31 | result.extend_from_slice(&chunk); 32 | } 33 | Ok(OutputVar(result)) 34 | } 35 | } 36 | 37 | impl AllocVar<(), ConstraintF> for ParametersVar { 38 | // #[tracing::instrument(target = "r1cs", skip(_cs, _f))] 39 | fn new_variable>( 40 | _cs: impl Into>, 41 | _f: impl FnOnce() -> Result, 42 | _mode: AllocationMode, 43 | ) -> Result { 44 | Ok(ParametersVar) 45 | } 46 | } 47 | 48 | #[cfg(test)] 49 | mod test { 50 | use crate::random_oracle::{ 51 | blake2s::{constraints::ROGadget, RO}, 52 | RandomOracle, RandomOracleGadget, 53 | }; 54 | use ark_ed_on_bls12_381::Fq as Fr; 55 | use ark_r1cs_std::prelude::*; 56 | use ark_relations::r1cs::ConstraintSystem; 57 | 58 | #[test] 59 | fn random_oracle_gadget_test() { 60 | let cs = ConstraintSystem::::new_ref(); 61 | 62 | let input = [1u8; 32]; 63 | 64 | type TestRO = RO; 65 | type TestROGadget = ROGadget; 66 | 67 | let parameters = (); 68 | let primitive_result = RO::evaluate(¶meters, &input).unwrap(); 69 | 70 | let mut input_var = vec![]; 71 | for byte in &input { 72 | input_var.push(UInt8::new_witness(cs.clone(), || Ok(*byte)).unwrap()); 73 | } 74 | 75 | let parameters_var = 76 | >::ParametersVar::new_witness( 77 | ark_relations::ns!(cs, "gadget_parameters"), 78 | || Ok(¶meters), 79 | ) 80 | .unwrap(); 81 | let result_var = 82 | >::evaluate(¶meters_var, &input_var) 83 | .unwrap(); 84 | 85 | for i in 0..32 { 86 | assert_eq!(primitive_result[i], result_var.0[i].value().unwrap()); 87 | } 88 | assert!(cs.is_satisfied().unwrap()); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /simple-payments/src/random_oracle/blake2s/mod.rs: -------------------------------------------------------------------------------- 1 | use super::RandomOracle; 2 | use ark_crypto_primitives::Error; 3 | use ark_std::rand::Rng; 4 | use blake2::Blake2s as b2s; 5 | use digest::Digest; 6 | 7 | pub struct RO; 8 | 9 | #[cfg(feature = "r1cs")] 10 | pub mod constraints; 11 | 12 | impl RandomOracle for RO { 13 | type Parameters = (); 14 | type Output = [u8; 32]; 15 | 16 | fn setup(_: &mut R) -> Result { 17 | Ok(()) 18 | } 19 | 20 | fn evaluate(_: &Self::Parameters, input: &[u8]) -> Result { 21 | let mut h = b2s::new(); 22 | h.update(input); 23 | let mut result = [0u8; 32]; 24 | result.copy_from_slice(&h.finalize()); 25 | Ok(result) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /simple-payments/src/random_oracle/constraints.rs: -------------------------------------------------------------------------------- 1 | use ark_ff::Field; 2 | use core::fmt::Debug; 3 | 4 | use crate::random_oracle::RandomOracle; 5 | use ark_relations::r1cs::SynthesisError; 6 | 7 | use ark_r1cs_std::prelude::*; 8 | 9 | pub trait RandomOracleGadget: Sized { 10 | type OutputVar: EqGadget 11 | + ToBytesGadget 12 | + AllocVar 13 | + R1CSVar 14 | + Debug 15 | + Clone 16 | + Sized; 17 | 18 | type ParametersVar: AllocVar + Clone; 19 | 20 | fn evaluate( 21 | parameters: &Self::ParametersVar, 22 | input: &[UInt8], 23 | ) -> Result; 24 | } 25 | -------------------------------------------------------------------------------- /simple-payments/src/random_oracle/mod.rs: -------------------------------------------------------------------------------- 1 | use ark_ff::bytes::ToBytes; 2 | use ark_std::hash::Hash; 3 | use ark_std::rand::Rng; 4 | 5 | pub mod blake2s; 6 | 7 | use ark_crypto_primitives::Error; 8 | 9 | #[cfg(feature = "r1cs")] 10 | pub mod constraints; 11 | #[cfg(feature = "r1cs")] 12 | pub use constraints::*; 13 | 14 | /// Interface to a RandomOracle 15 | pub trait RandomOracle { 16 | type Output: ToBytes + Clone + Eq + core::fmt::Debug + Hash + Default; 17 | type Parameters: Clone + Default; 18 | 19 | fn setup(r: &mut R) -> Result; 20 | fn evaluate(parameters: &Self::Parameters, input: &[u8]) -> Result; 21 | } 22 | -------------------------------------------------------------------------------- /simple-payments/src/signature/constraints.rs: -------------------------------------------------------------------------------- 1 | use ark_ff::Field; 2 | use ark_r1cs_std::prelude::*; 3 | use ark_relations::r1cs::SynthesisError; 4 | 5 | use crate::signature::SignatureScheme; 6 | 7 | pub trait SigVerifyGadget { 8 | type ParametersVar: AllocVar + Clone; 9 | 10 | type PublicKeyVar: ToBytesGadget + AllocVar + Clone; 11 | 12 | type SignatureVar: AllocVar + Clone; 13 | 14 | fn verify( 15 | parameters: &Self::ParametersVar, 16 | public_key: &Self::PublicKeyVar, 17 | // TODO: Should we make this take in bytes or something different? 18 | message: &[UInt8], 19 | signature: &Self::SignatureVar, 20 | ) -> Result, SynthesisError>; 21 | } 22 | 23 | pub trait SigRandomizePkGadget { 24 | type ParametersVar: AllocVar + Clone; 25 | 26 | type PublicKeyVar: ToBytesGadget 27 | + EqGadget 28 | + AllocVar 29 | + Clone; 30 | 31 | fn randomize( 32 | parameters: &Self::ParametersVar, 33 | public_key: &Self::PublicKeyVar, 34 | randomness: &[UInt8], 35 | ) -> Result; 36 | } 37 | 38 | #[cfg(test)] 39 | mod test { 40 | use crate::signature::{schnorr, schnorr::constraints::*, *}; 41 | use ark_ec::ProjectiveCurve; 42 | use ark_ed_on_bls12_381::constraints::EdwardsVar as JubJubVar; 43 | use ark_ed_on_bls12_381::EdwardsProjective as JubJub; 44 | use ark_ff::PrimeField; 45 | use ark_r1cs_std::prelude::*; 46 | use ark_relations::r1cs::ConstraintSystem; 47 | use ark_std::test_rng; 48 | 49 | fn sign_and_verify>( 50 | message: &[u8], 51 | ) { 52 | let rng = &mut test_rng(); 53 | let parameters = S::setup::<_>(rng).unwrap(); 54 | let (pk, sk) = S::keygen(¶meters, rng).unwrap(); 55 | let sig = S::sign(¶meters, &sk, &message, rng).unwrap(); 56 | assert!(S::verify(¶meters, &pk, &message, &sig).unwrap()); 57 | 58 | let cs = ConstraintSystem::::new_ref(); 59 | 60 | let parameters_var = SG::ParametersVar::new_constant(cs.clone(), parameters).unwrap(); 61 | let signature_var = SG::SignatureVar::new_witness(cs.clone(), || Ok(&sig)).unwrap(); 62 | let pk_var = SG::PublicKeyVar::new_witness(cs.clone(), || Ok(&pk)).unwrap(); 63 | let mut msg_var = Vec::new(); 64 | for i in 0..message.len() { 65 | msg_var.push(UInt8::new_witness(cs.clone(), || Ok(&message[i])).unwrap()) 66 | } 67 | let valid_sig_var = SG::verify(¶meters_var, &pk_var, &msg_var, &signature_var).unwrap(); 68 | 69 | valid_sig_var.enforce_equal(&Boolean::::TRUE).unwrap(); 70 | assert!(cs.is_satisfied().unwrap()); 71 | } 72 | 73 | fn failed_verification(message: &[u8], bad_message: &[u8]) { 74 | let rng = &mut test_rng(); 75 | let parameters = S::setup::<_>(rng).unwrap(); 76 | let (pk, sk) = S::keygen(¶meters, rng).unwrap(); 77 | let sig = S::sign(¶meters, &sk, message, rng).unwrap(); 78 | assert!(!S::verify(¶meters, &pk, bad_message, &sig).unwrap()); 79 | } 80 | 81 | #[test] 82 | fn schnorr_signature_test() { 83 | type F = ::BaseField; 84 | let message = "Hi, I am a Schnorr signature!"; 85 | sign_and_verify::< 86 | F, 87 | schnorr::Schnorr, 88 | SchnorrSignatureVerifyGadget, 89 | >(message.as_bytes()); 90 | failed_verification::>( 91 | message.as_bytes(), 92 | "Bad message".as_bytes(), 93 | ); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /simple-payments/src/signature/mod.rs: -------------------------------------------------------------------------------- 1 | use ark_crypto_primitives::Error; 2 | use ark_ff::bytes::ToBytes; 3 | use ark_std::hash::Hash; 4 | use ark_std::rand::Rng; 5 | 6 | #[cfg(feature = "r1cs")] 7 | pub mod constraints; 8 | #[cfg(feature = "r1cs")] 9 | pub use constraints::*; 10 | 11 | pub mod schnorr; 12 | 13 | pub trait SignatureScheme { 14 | type Parameters: Clone + Send + Sync; 15 | type PublicKey: ToBytes + Hash + Eq + Clone + Default + Send + Sync; 16 | type SecretKey: ToBytes + Clone + Default; 17 | type Signature: Clone + Default + Send + Sync; 18 | 19 | fn setup(rng: &mut R) -> Result; 20 | 21 | fn keygen( 22 | pp: &Self::Parameters, 23 | rng: &mut R, 24 | ) -> Result<(Self::PublicKey, Self::SecretKey), Error>; 25 | 26 | fn sign( 27 | pp: &Self::Parameters, 28 | sk: &Self::SecretKey, 29 | message: &[u8], 30 | rng: &mut R, 31 | ) -> Result; 32 | 33 | fn verify( 34 | pp: &Self::Parameters, 35 | pk: &Self::PublicKey, 36 | message: &[u8], 37 | signature: &Self::Signature, 38 | ) -> Result; 39 | } 40 | 41 | #[cfg(test)] 42 | mod test { 43 | use crate::signature::{schnorr, *}; 44 | use ark_ed_on_bls12_381::EdwardsProjective as JubJub; 45 | use ark_std::test_rng; 46 | 47 | fn sign_and_verify(message: &[u8]) { 48 | let rng = &mut test_rng(); 49 | let parameters = S::setup::<_>(rng).unwrap(); 50 | let (pk, sk) = S::keygen(¶meters, rng).unwrap(); 51 | let sig = S::sign(¶meters, &sk, &message, rng).unwrap(); 52 | assert!(S::verify(¶meters, &pk, &message, &sig).unwrap()); 53 | } 54 | 55 | fn failed_verification(message: &[u8], bad_message: &[u8]) { 56 | let rng = &mut test_rng(); 57 | let parameters = S::setup::<_>(rng).unwrap(); 58 | let (pk, sk) = S::keygen(¶meters, rng).unwrap(); 59 | let sig = S::sign(¶meters, &sk, message, rng).unwrap(); 60 | assert!(!S::verify(¶meters, &pk, bad_message, &sig).unwrap()); 61 | } 62 | 63 | #[test] 64 | fn schnorr_signature_test() { 65 | let message = "Hi, I am a Schnorr signature!"; 66 | sign_and_verify::>(message.as_bytes()); 67 | failed_verification::>( 68 | message.as_bytes(), 69 | "Bad message".as_bytes(), 70 | ); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /simple-payments/src/signature/schnorr/constraints.rs: -------------------------------------------------------------------------------- 1 | use ark_ec::ProjectiveCurve; 2 | use ark_ff::{to_bytes, Field}; 3 | use ark_r1cs_std::{bits::uint8::UInt8, prelude::*}; 4 | use ark_relations::r1cs::ConstraintSystemRef; 5 | use ark_relations::r1cs::{Namespace, SynthesisError}; 6 | use ark_std::vec::Vec; 7 | 8 | use crate::random_oracle::blake2s::constraints::{ParametersVar as B2SParamsVar, ROGadget}; 9 | use crate::random_oracle::RandomOracleGadget; 10 | use crate::signature::SigVerifyGadget; 11 | 12 | use derivative::Derivative; 13 | 14 | use core::{borrow::Borrow, marker::PhantomData}; 15 | 16 | use crate::signature::schnorr::{Parameters, PublicKey, Schnorr, Signature}; 17 | 18 | type ConstraintF = <::BaseField as Field>::BasePrimeField; 19 | 20 | #[derive(Clone)] 21 | pub struct ParametersVar>> 22 | where 23 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 24 | { 25 | generator: GC, 26 | salt: Option>>>, 27 | _curve: PhantomData, 28 | } 29 | 30 | #[derive(Derivative)] 31 | #[derivative( 32 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 33 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 34 | )] 35 | pub struct PublicKeyVar>> 36 | where 37 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 38 | { 39 | pub_key: GC, 40 | #[doc(hidden)] 41 | _group: PhantomData<*const C>, 42 | } 43 | 44 | #[derive(Derivative)] 45 | #[derivative( 46 | Debug(bound = "C: ProjectiveCurve, GC: CurveVar>"), 47 | Clone(bound = "C: ProjectiveCurve, GC: CurveVar>") 48 | )] 49 | pub struct SignatureVar>> 50 | where 51 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 52 | { 53 | prover_response: Vec>>, 54 | verifier_challenge: Vec>>, 55 | #[doc(hidden)] 56 | _group: PhantomData, 57 | } 58 | 59 | pub struct SchnorrSignatureVerifyGadget>> 60 | where 61 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 62 | { 63 | #[doc(hidden)] 64 | _group: PhantomData<*const C>, 65 | #[doc(hidden)] 66 | _group_gadget: PhantomData<*const GC>, 67 | } 68 | 69 | impl SigVerifyGadget, ConstraintF> for SchnorrSignatureVerifyGadget 70 | where 71 | C: ProjectiveCurve, 72 | GC: CurveVar>, 73 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 74 | { 75 | type ParametersVar = ParametersVar; 76 | type PublicKeyVar = PublicKeyVar; 77 | type SignatureVar = SignatureVar; 78 | 79 | fn verify( 80 | parameters: &Self::ParametersVar, 81 | public_key: &Self::PublicKeyVar, 82 | message: &[UInt8>], 83 | signature: &Self::SignatureVar, 84 | ) -> Result>, SynthesisError> { 85 | let prover_response = signature.prover_response.clone(); 86 | let verifier_challenge = signature.verifier_challenge.clone(); 87 | let mut claimed_prover_commitment = parameters 88 | .generator 89 | .scalar_mul_le(prover_response.to_bits_le()?.iter())?; 90 | let public_key_times_verifier_challenge = public_key 91 | .pub_key 92 | .scalar_mul_le(verifier_challenge.to_bits_le()?.iter())?; 93 | claimed_prover_commitment += &public_key_times_verifier_challenge; 94 | 95 | let mut hash_input = Vec::new(); 96 | if parameters.salt.is_some() { 97 | hash_input.extend_from_slice(parameters.salt.as_ref().unwrap()); 98 | } 99 | hash_input.extend_from_slice(&public_key.pub_key.to_bytes()?); 100 | hash_input.extend_from_slice(&claimed_prover_commitment.to_bytes()?); 101 | hash_input.extend_from_slice(message); 102 | 103 | let b2s_params = >>::new_constant( 104 | ConstraintSystemRef::None, 105 | (), 106 | )?; 107 | let obtained_verifier_challenge = ROGadget::evaluate(&b2s_params, &hash_input)?.0; 108 | 109 | obtained_verifier_challenge.is_eq(&verifier_challenge.to_vec()) 110 | } 111 | } 112 | 113 | impl AllocVar, ConstraintF> for ParametersVar 114 | where 115 | C: ProjectiveCurve, 116 | GC: CurveVar>, 117 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 118 | { 119 | fn new_variable>>( 120 | cs: impl Into>>, 121 | f: impl FnOnce() -> Result, 122 | mode: AllocationMode, 123 | ) -> Result { 124 | f().and_then(|val| { 125 | let cs = cs.into(); 126 | let generator = GC::new_variable(cs.clone(), || Ok(val.borrow().generator), mode)?; 127 | let native_salt = val.borrow().salt; 128 | let mut constraint_salt = Vec::>>::new(); 129 | if native_salt.is_some() { 130 | for i in 0..32 { 131 | constraint_salt.push(UInt8::>::new_variable( 132 | cs.clone(), 133 | || Ok(native_salt.unwrap()[i]), 134 | mode, 135 | )?); 136 | } 137 | 138 | return Ok(Self { 139 | generator, 140 | salt: Some(constraint_salt), 141 | _curve: PhantomData, 142 | }); 143 | } 144 | Ok(Self { 145 | generator, 146 | salt: None, 147 | _curve: PhantomData, 148 | }) 149 | }) 150 | } 151 | } 152 | 153 | impl AllocVar, ConstraintF> for PublicKeyVar 154 | where 155 | C: ProjectiveCurve, 156 | GC: CurveVar>, 157 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 158 | { 159 | fn new_variable>>( 160 | cs: impl Into>>, 161 | f: impl FnOnce() -> Result, 162 | mode: AllocationMode, 163 | ) -> Result { 164 | let pub_key = GC::new_variable(cs, f, mode)?; 165 | Ok(Self { 166 | pub_key, 167 | _group: PhantomData, 168 | }) 169 | } 170 | } 171 | 172 | impl AllocVar, ConstraintF> for SignatureVar 173 | where 174 | C: ProjectiveCurve, 175 | GC: CurveVar>, 176 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 177 | { 178 | fn new_variable>>( 179 | cs: impl Into>>, 180 | f: impl FnOnce() -> Result, 181 | mode: AllocationMode, 182 | ) -> Result { 183 | f().and_then(|val| { 184 | let cs = cs.into(); 185 | let response_bytes = to_bytes![val.borrow().prover_response].unwrap(); 186 | let challenge_bytes = val.borrow().verifier_challenge; 187 | let mut prover_response = Vec::>>::new(); 188 | let mut verifier_challenge = Vec::>>::new(); 189 | for byte in &response_bytes { 190 | prover_response.push(UInt8::>::new_variable( 191 | cs.clone(), 192 | || Ok(byte), 193 | mode, 194 | )?); 195 | } 196 | for byte in &challenge_bytes { 197 | verifier_challenge.push(UInt8::>::new_variable( 198 | cs.clone(), 199 | || Ok(byte), 200 | mode, 201 | )?); 202 | } 203 | Ok(SignatureVar { 204 | prover_response, 205 | verifier_challenge, 206 | _group: PhantomData, 207 | }) 208 | }) 209 | } 210 | } 211 | 212 | impl EqGadget> for PublicKeyVar 213 | where 214 | C: ProjectiveCurve, 215 | GC: CurveVar>, 216 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 217 | { 218 | #[inline] 219 | fn is_eq(&self, other: &Self) -> Result>, SynthesisError> { 220 | self.pub_key.is_eq(&other.pub_key) 221 | } 222 | 223 | #[inline] 224 | fn conditional_enforce_equal( 225 | &self, 226 | other: &Self, 227 | condition: &Boolean>, 228 | ) -> Result<(), SynthesisError> { 229 | self.pub_key 230 | .conditional_enforce_equal(&other.pub_key, condition) 231 | } 232 | 233 | #[inline] 234 | fn conditional_enforce_not_equal( 235 | &self, 236 | other: &Self, 237 | condition: &Boolean>, 238 | ) -> Result<(), SynthesisError> { 239 | self.pub_key 240 | .conditional_enforce_not_equal(&other.pub_key, condition) 241 | } 242 | } 243 | 244 | impl ToBytesGadget> for PublicKeyVar 245 | where 246 | C: ProjectiveCurve, 247 | GC: CurveVar>, 248 | for<'a> &'a GC: GroupOpsBounds<'a, C, GC>, 249 | { 250 | fn to_bytes(&self) -> Result>>, SynthesisError> { 251 | self.pub_key.to_bytes() 252 | } 253 | } 254 | -------------------------------------------------------------------------------- /simple-payments/src/signature/schnorr/mod.rs: -------------------------------------------------------------------------------- 1 | use super::SignatureScheme; 2 | use ark_crypto_primitives::Error; 3 | use ark_ec::{AffineCurve, ProjectiveCurve}; 4 | use ark_ff::{ 5 | bytes::ToBytes, 6 | fields::{Field, PrimeField}, 7 | to_bytes, ToConstraintField, UniformRand, 8 | }; 9 | use ark_std::io::{Result as IoResult, Write}; 10 | use ark_std::rand::Rng; 11 | use ark_std::{hash::Hash, marker::PhantomData, vec::Vec}; 12 | use blake2::Blake2s; 13 | use digest::Digest; 14 | 15 | use derivative::Derivative; 16 | #[cfg(feature = "r1cs")] 17 | pub mod constraints; 18 | 19 | pub struct Schnorr { 20 | _group: PhantomData, 21 | } 22 | 23 | #[derive(Derivative)] 24 | #[derivative(Clone(bound = "C: ProjectiveCurve"), Debug)] 25 | pub struct Parameters { 26 | pub generator: C::Affine, 27 | pub salt: Option<[u8; 32]>, 28 | } 29 | 30 | pub type PublicKey = ::Affine; 31 | 32 | #[derive(Clone, Default, Debug)] 33 | pub struct SecretKey { 34 | pub secret_key: C::ScalarField, 35 | pub public_key: PublicKey, 36 | } 37 | 38 | impl ToBytes for SecretKey { 39 | #[inline] 40 | fn write(&self, writer: W) -> IoResult<()> { 41 | self.secret_key.write(writer) 42 | } 43 | } 44 | 45 | #[derive(Clone, Default, Debug)] 46 | pub struct Signature { 47 | pub prover_response: C::ScalarField, 48 | pub verifier_challenge: [u8; 32], 49 | } 50 | 51 | impl SignatureScheme for Schnorr 52 | where 53 | C::ScalarField: PrimeField, 54 | { 55 | type Parameters = Parameters; 56 | type PublicKey = PublicKey; 57 | type SecretKey = SecretKey; 58 | type Signature = Signature; 59 | 60 | fn setup(_rng: &mut R) -> Result { 61 | // let setup_time = start_timer!(|| "SchnorrSig::Setup"); 62 | 63 | let salt = None; 64 | let generator = C::prime_subgroup_generator().into(); 65 | 66 | // end_timer!(setup_time); 67 | Ok(Parameters { generator, salt }) 68 | } 69 | 70 | fn keygen( 71 | parameters: &Self::Parameters, 72 | rng: &mut R, 73 | ) -> Result<(Self::PublicKey, Self::SecretKey), Error> { 74 | // let keygen_time = start_timer!(|| "SchnorrSig::KeyGen"); 75 | 76 | // Secret is a random scalar x 77 | // the pubkey is y = xG 78 | let secret_key = C::ScalarField::rand(rng); 79 | let public_key = parameters.generator.mul(secret_key).into(); 80 | 81 | // end_timer!(keygen_time); 82 | Ok(( 83 | public_key, 84 | SecretKey { 85 | secret_key, 86 | public_key, 87 | }, 88 | )) 89 | } 90 | 91 | fn sign( 92 | parameters: &Self::Parameters, 93 | sk: &Self::SecretKey, 94 | message: &[u8], 95 | rng: &mut R, 96 | ) -> Result { 97 | // let sign_time = start_timer!(|| "SchnorrSig::Sign"); 98 | // (k, e); 99 | let (random_scalar, verifier_challenge) = { 100 | // Sample a random scalar `k` from the prime scalar field. 101 | let random_scalar: C::ScalarField = C::ScalarField::rand(rng); 102 | // Commit to the random scalar via r := k · G. 103 | // This is the prover's first msg in the Sigma protocol. 104 | let prover_commitment = parameters.generator.mul(random_scalar).into_affine(); 105 | 106 | // Hash everything to get verifier challenge. 107 | // e := H(salt || pubkey || r || msg); 108 | let mut hash_input = Vec::new(); 109 | if parameters.salt != None { 110 | hash_input.extend_from_slice(¶meters.salt.unwrap()); 111 | } 112 | hash_input.extend_from_slice(&to_bytes![sk.public_key]?); 113 | hash_input.extend_from_slice(&to_bytes![prover_commitment]?); 114 | hash_input.extend_from_slice(message); 115 | 116 | let hash_digest = Blake2s::digest(&hash_input); 117 | assert!(hash_digest.len() >= 32); 118 | let mut verifier_challenge = [0u8; 32]; 119 | verifier_challenge.copy_from_slice(&hash_digest); 120 | 121 | (random_scalar, verifier_challenge) 122 | }; 123 | 124 | let verifier_challenge_fe = C::ScalarField::from_le_bytes_mod_order(&verifier_challenge); 125 | 126 | // k - xe; 127 | let prover_response = random_scalar - (verifier_challenge_fe * sk.secret_key); 128 | let signature = Signature { 129 | prover_response, 130 | verifier_challenge, 131 | }; 132 | 133 | // end_timer!(sign_time); 134 | Ok(signature) 135 | } 136 | 137 | fn verify( 138 | parameters: &Self::Parameters, 139 | pk: &Self::PublicKey, 140 | message: &[u8], 141 | signature: &Self::Signature, 142 | ) -> Result { 143 | // let verify_time = start_timer!(|| "SchnorrSig::Verify"); 144 | 145 | let Signature { 146 | prover_response, 147 | verifier_challenge, 148 | } = signature; 149 | let verifier_challenge_fe = C::ScalarField::from_le_bytes_mod_order(verifier_challenge); 150 | // sG = kG - eY 151 | // kG = sG + eY 152 | // so we first solve for kG. 153 | let mut claimed_prover_commitment = parameters.generator.mul(*prover_response); 154 | let public_key_times_verifier_challenge = pk.mul(verifier_challenge_fe); 155 | claimed_prover_commitment += &public_key_times_verifier_challenge; 156 | let claimed_prover_commitment = claimed_prover_commitment.into_affine(); 157 | 158 | // e = H(salt, kG, msg) 159 | let mut hash_input = Vec::new(); 160 | if parameters.salt != None { 161 | hash_input.extend_from_slice(¶meters.salt.unwrap()); 162 | } 163 | hash_input.extend_from_slice(&to_bytes![pk]?); 164 | hash_input.extend_from_slice(&to_bytes![claimed_prover_commitment]?); 165 | hash_input.extend_from_slice(message); 166 | 167 | // cast the hash output to get e 168 | let obtained_verifier_challenge = &Blake2s::digest(&hash_input)[..]; 169 | // end_timer!(verify_time); 170 | // The signature is valid iff the computed verifier challenge is the same as the one 171 | // provided in the signature 172 | Ok(verifier_challenge == obtained_verifier_challenge) 173 | } 174 | } 175 | 176 | pub fn bytes_to_bits(bytes: &[u8]) -> Vec { 177 | let mut bits = Vec::with_capacity(bytes.len() * 8); 178 | for byte in bytes { 179 | for i in 0..8 { 180 | let bit = (*byte >> (8 - i - 1)) & 1; 181 | bits.push(bit == 1); 182 | } 183 | } 184 | bits 185 | } 186 | 187 | impl> 188 | ToConstraintField for Parameters 189 | { 190 | #[inline] 191 | fn to_field_elements(&self) -> Option> { 192 | self.generator.into_projective().to_field_elements() 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /simple-payments/src/transaction.rs: -------------------------------------------------------------------------------- 1 | use crate::account::{AccountId, AccountPublicKey, AccountSecretKey}; 2 | use crate::ledger::{self, Amount}; 3 | use crate::signature::{ 4 | schnorr::{self, Schnorr}, 5 | SignatureScheme, 6 | }; 7 | use ark_ed_on_bls12_381::EdwardsProjective; 8 | use ark_std::rand::Rng; 9 | 10 | /// Transaction transferring some amount from one account to another. 11 | #[derive(Clone, Debug)] 12 | pub struct Transaction { 13 | /// The account information of the sender. 14 | pub sender: AccountId, 15 | /// The account information of the recipient. 16 | pub recipient: AccountId, 17 | /// The amount being transferred from the sender to the receiver. 18 | pub amount: Amount, 19 | /// The spend authorization is a signature over the sender, the recipient, 20 | /// and the amount. 21 | pub signature: schnorr::Signature, 22 | } 23 | 24 | impl Transaction { 25 | /// Verify just the signature in the transaction. 26 | fn verify_signature( 27 | &self, 28 | pp: &schnorr::Parameters, 29 | pub_key: &AccountPublicKey, 30 | ) -> bool { 31 | // The authorized message consists of 32 | // (SenderAccId || SenderPubKey || RecipientAccId || RecipientPubKey || Amount) 33 | let mut message = self.sender.to_bytes_le(); 34 | message.extend(self.recipient.to_bytes_le()); 35 | message.extend(self.amount.to_bytes_le()); 36 | Schnorr::verify(pp, pub_key, &message, &self.signature).unwrap() 37 | } 38 | 39 | /// Check that the transaction is valid for the given ledger state. This checks 40 | /// the following conditions: 41 | /// 1. Verify that the signature is valid with respect to the public key 42 | /// corresponding to `self.sender`. 43 | /// 2. Verify that the sender's account has sufficient balance to finance 44 | /// the transaction. 45 | /// 3. Verify that the recipient's account exists. 46 | pub fn validate(&self, parameters: &ledger::Parameters, state: &ledger::State) -> bool { 47 | // Lookup public key corresponding to sender ID 48 | if let Some(sender_acc_info) = state.id_to_account_info.get(&self.sender) { 49 | let mut result = true; 50 | // Check that the account_info exists in the Merkle tree. 51 | result &= { 52 | let path = state 53 | .account_merkle_tree 54 | .generate_proof(self.sender.0 as usize) 55 | .expect("path should exist"); 56 | path.verify( 57 | ¶meters.leaf_crh_params, 58 | ¶meters.two_to_one_crh_params, 59 | &state.account_merkle_tree.root(), 60 | &sender_acc_info.to_bytes_le(), 61 | ) 62 | .unwrap() 63 | }; 64 | // Verify the signature against the sender pubkey. 65 | result &= self.verify_signature(¶meters.sig_params, &sender_acc_info.public_key); 66 | // assert!(result, "signature verification failed"); 67 | // Verify the amount is available in the sender account. 68 | result &= self.amount <= sender_acc_info.balance; 69 | // Verify that recipient account exists. 70 | result &= state.id_to_account_info.get(&self.recipient).is_some(); 71 | result 72 | } else { 73 | false 74 | } 75 | } 76 | 77 | /// Create a (possibly invalid) transaction. 78 | pub fn create( 79 | parameters: &ledger::Parameters, 80 | sender: AccountId, 81 | recipient: AccountId, 82 | amount: Amount, 83 | sender_sk: &AccountSecretKey, 84 | rng: &mut R, 85 | ) -> Self { 86 | // The authorized message consists of (SenderAccId || RecipientAccId || Amount) 87 | let mut message = sender.to_bytes_le(); 88 | message.extend(recipient.to_bytes_le()); 89 | message.extend(amount.to_bytes_le()); 90 | let signature = Schnorr::sign(¶meters.sig_params, sender_sk, &message, rng).unwrap(); 91 | Self { 92 | sender, 93 | recipient, 94 | amount, 95 | signature, 96 | } 97 | } 98 | } 99 | 100 | // Ideas to make exercises more interesting/complex: 101 | // 1. Add fees 102 | // 2. Add recipient confirmation requirement if tx amount is too large. 103 | // 3. Add authority confirmation if tx amount is too large. 104 | // 4. Create account if it doesn't exist. 105 | // 5. Add idea for compressing state transitions with repeated senders and recipients. 106 | --------------------------------------------------------------------------------