├── relations ├── LICENSE-MIT ├── LICENSE-APACHE ├── src │ ├── lib.rs │ └── r1cs │ │ ├── error.rs │ │ ├── mod.rs │ │ ├── trace.rs │ │ ├── impl_lc.rs │ │ └── constraint_system.rs └── Cargo.toml ├── .gitignore ├── rustfmt.toml ├── scripts ├── install-hook.sh └── linkify_changelog.py ├── Cargo.toml ├── .github ├── workflows │ ├── linkify_changelog.yml │ └── ci.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── PULL_REQUEST_TEMPLATE.md ├── snark ├── Cargo.toml └── src │ └── lib.rs ├── LICENSE-MIT ├── CHANGELOG.md ├── .hooks └── pre-commit ├── CONTRIBUTING.md ├── README.md └── LICENSE-APACHE /relations/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /relations/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .DS_Store 4 | .idea 5 | *.iml 6 | *.ipynb_checkpoints 7 | *.pyc 8 | *.sage.py 9 | params 10 | *.swp 11 | *.swo 12 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | reorder_imports = true 2 | wrap_comments = true 3 | normalize_comments = true 4 | use_try_shorthand = true 5 | match_block_trailing_comma = true 6 | use_field_init_shorthand = true 7 | edition = "2018" 8 | condense_wildcard_suffixes = true 9 | merge_imports = true 10 | -------------------------------------------------------------------------------- /scripts/install-hook.sh: -------------------------------------------------------------------------------- 1 | #!/bin/env bash 2 | # This script will install the provided directory ../.hooks as the hook 3 | # directory for the present repo. See there for hooks, including a pre-commit 4 | # hook that runs rustfmt on files before a commit. 5 | 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | HOOKS_DIR="${DIR}/../.hooks" 8 | 9 | git config core.hooksPath "$HOOKS_DIR" 10 | -------------------------------------------------------------------------------- /relations/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Core interface for working with various relations that are useful in 2 | //! zkSNARKs. At the moment, we only implement APIs for working with Rank-1 3 | //! Constraint Systems (R1CS). 4 | 5 | #![cfg_attr(not(feature = "std"), no_std)] 6 | #![warn( 7 | unused, 8 | future_incompatible, 9 | nonstandard_style, 10 | rust_2018_idioms, 11 | missing_docs 12 | )] 13 | #![deny(unsafe_code)] 14 | 15 | #[macro_use] 16 | extern crate ark_std; 17 | 18 | pub mod r1cs; 19 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "relations", 5 | "snark", 6 | ] 7 | 8 | resolver = "2" 9 | 10 | [profile.release] 11 | opt-level = 3 12 | lto = "thin" 13 | incremental = true 14 | panic = 'abort' 15 | 16 | [profile.bench] 17 | opt-level = 3 18 | debug = false 19 | rpath = false 20 | lto = "thin" 21 | incremental = true 22 | debug-assertions = false 23 | 24 | [profile.dev] 25 | opt-level = 0 26 | panic = 'abort' 27 | 28 | [profile.test] 29 | opt-level = 3 30 | lto = "thin" 31 | incremental = true 32 | debug-assertions = true 33 | debug = true 34 | -------------------------------------------------------------------------------- /.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 21 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /snark/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ark-snark" 3 | version = "0.4.0" 4 | authors = [ "arkworks contributors" ] 5 | description = "A library for SNARK traits" 6 | homepage = "https://arkworks.rs" 7 | repository = "https://github.com/arkworks-rs/snark" 8 | documentation = "https://docs.rs/ark-snark/" 9 | keywords = ["zero-knowledge", "cryptography", "zkSNARK", "SNARK"] 10 | categories = ["cryptography"] 11 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 12 | license = "MIT/Apache-2.0" 13 | edition = "2021" 14 | 15 | [dependencies] 16 | ark-std = { version = "0.4.0", default-features = false } 17 | ark-ff = { git = "https://github.com/Antalpha-Labs/algebra/" } 18 | ark-serialize = { git = "https://github.com/Antalpha-Labs/algebra/", features = [ "derive" ] } 19 | ark-relations = { git = "https://github.com/Antalpha-Labs/snark/", default-features = false } 20 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /relations/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ark-relations" 3 | version = "0.4.0" 4 | authors = [ "arkworks contributors" ] 5 | description = "A library for rank-one constraint systems" 6 | homepage = "https://arkworks.rs" 7 | repository = "https://github.com/arkworks-rs/snark" 8 | documentation = "https://docs.rs/ark-relations/" 9 | keywords = ["zero-knowledge", "cryptography", "zkSNARK", "SNARK", "constraint-systems"] 10 | categories = ["cryptography"] 11 | include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 12 | license = "MIT/Apache-2.0" 13 | edition = "2021" 14 | 15 | [dependencies] 16 | ark-ff = { git = "https://github.com/Antalpha-Labs/algebra/" } 17 | ark-std = { version = "0.4.0" } 18 | tracing = { version = "0.1", default-features = false } 19 | tracing-subscriber = { version = "0.2", default-features = false, optional = true } 20 | 21 | [dev-dependencies] 22 | ark-test-curves = { version = "0.4.0", default-features = false, features = [ "bls12_381_scalar_field" ] } 23 | ark-std = { version = "0.4.0" } 24 | 25 | [features] 26 | default = [] 27 | std = [ "ark-std/std", "ark-ff/std", "tracing-subscriber", "tracing/std" ] 28 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | 3 | ## Pending 4 | 5 | ### Breaking changes 6 | 7 | ### Features 8 | 9 | ### Improvements 10 | 11 | ### Bug fixes 12 | 13 | ## v0.3.0 14 | 15 | ### Breaking changes 16 | 17 | ### Features 18 | - [\#347](https://github.com/arkworks-rs/snark/pull/347) Add `into_inner` function for `ConstraintSystemRef`. 19 | 20 | ### Improvements 21 | 22 | ### Bug fixes 23 | 24 | ## v0.2.0 25 | 26 | ### Breaking changes 27 | - [\#334](https://github.com/arkworks-rs/snark/pull/334) Outlining linear combinations is now specified via the optimization goal interface. 28 | 29 | ### Features 30 | 31 | ### Improvements 32 | - [\#325](https://github.com/arkworks-rs/snark/pull/325) Reduce memory consumption during inlining 33 | 34 | ### Bug fixes 35 | - [\#340](https://github.com/arkworks-rs/snark/pull/340) Compile with `panic='abort'` in release mode, for safety of the library across FFI boundaries. 36 | 37 | ## v0.1.0 38 | 39 | This tag corresponds to the old `zexe` codebase. 40 | After this release, all of the code has been split up into 41 | more modular repositories in the github organization `arkworks-rs`. 42 | See #320 for guides in migration of old codebases. 43 | -------------------------------------------------------------------------------- /.hooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rustfmt --version &>/dev/null 4 | if [ $? != 0 ]; then 5 | printf "[pre_commit] \033[0;31merror\033[0m: \"rustfmt\" not available. \n" 6 | printf "[pre_commit] \033[0;31merror\033[0m: rustfmt can be installed via - \n" 7 | printf "[pre_commit] $ rustup component add rustfmt \n" 8 | exit 1 9 | fi 10 | 11 | problem_files=() 12 | 13 | # collect ill-formatted files 14 | for file in $(git diff --name-only --cached); do 15 | if [ ${file: -3} == ".rs" ]; then 16 | rustfmt +stable --check $file &>/dev/null 17 | if [ $? != 0 ]; then 18 | problem_files+=($file) 19 | fi 20 | fi 21 | done 22 | 23 | if [ ${#problem_files[@]} == 0 ]; then 24 | # done 25 | printf "[pre_commit] rustfmt \033[0;32mok\033[0m \n" 26 | else 27 | # reformat the files that need it and re-stage them. 28 | printf "[pre_commit] the following files were rustfmt'd before commit: \n" 29 | for file in ${problem_files[@]}; do 30 | rustfmt +stable $file 31 | git add $file 32 | printf "\033[0;32m $file\033[0m \n" 33 | done 34 | fi 35 | 36 | exit 0 37 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | ## Description 8 | 9 | 12 | 13 | closes: #XXXX 14 | 15 | --- 16 | 17 | Before we can merge this PR, please make sure that all the following items have been 18 | checked off. If any of the checklist items are not applicable, please leave them but 19 | write a little note why. 20 | 21 | - [ ] Targeted PR against correct branch (master) 22 | - [ ] Linked to Github issue with discussion and accepted design OR have an explanation in the PR that describes this work. 23 | - [ ] Wrote unit tests 24 | - [ ] Updated relevant documentation in the code 25 | - [ ] Added a relevant changelog entry to the `Pending` section in `CHANGELOG.md` 26 | - [ ] Re-reviewed `Files changed` in the Github PR explorer 27 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /relations/src/r1cs/error.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | /// This is an error that could occur during circuit synthesis contexts, 4 | /// such as CRS generation, proving or verification. 5 | #[derive(PartialEq, Eq, Clone, Copy, Debug)] 6 | pub enum SynthesisError { 7 | /// During synthesis, we tried to allocate a variable when 8 | /// `ConstraintSystemRef` was `None`. 9 | MissingCS, 10 | /// During synthesis, we lacked knowledge of a variable assignment. 11 | AssignmentMissing, 12 | /// During synthesis, we divided by zero. 13 | DivisionByZero, 14 | /// During synthesis, we constructed an unsatisfiable constraint system. 15 | Unsatisfiable, 16 | /// During synthesis, our polynomials ended up being too high of degree 17 | PolynomialDegreeTooLarge, 18 | /// During proof generation, we encountered an identity in the CRS 19 | UnexpectedIdentity, 20 | /// During verification, our verifying key was malformed. 21 | MalformedVerifyingKey, 22 | /// During CRS generation, we observed an unconstrained auxiliary variable 23 | UnconstrainedVariable, 24 | } 25 | 26 | impl ark_std::error::Error for SynthesisError {} 27 | 28 | impl fmt::Display for SynthesisError { 29 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 30 | match self { 31 | SynthesisError::MissingCS => write!(f, "the constraint system was `None`"), 32 | SynthesisError::AssignmentMissing => { 33 | write!(f, "an assignment for a variable could not be computed") 34 | }, 35 | SynthesisError::DivisionByZero => write!(f, "division by zero"), 36 | SynthesisError::Unsatisfiable => write!(f, "unsatisfiable constraint system"), 37 | SynthesisError::PolynomialDegreeTooLarge => write!(f, "polynomial degree is too large"), 38 | SynthesisError::UnexpectedIdentity => { 39 | write!(f, "encountered an identity element in the CRS") 40 | }, 41 | SynthesisError::MalformedVerifyingKey => write!(f, "malformed verifying key"), 42 | SynthesisError::UnconstrainedVariable => { 43 | write!(f, "auxiliary variable was unconstrained") 44 | }, 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.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 --workspace 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 --workspace 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 | 88 | check_no_std: 89 | name: Check no_std 90 | runs-on: ubuntu-latest 91 | steps: 92 | - name: Checkout 93 | uses: actions/checkout@v2 94 | 95 | - name: Install Rust (${{ matrix.rust }}) 96 | uses: actions-rs/toolchain@v1 97 | with: 98 | toolchain: stable 99 | target: aarch64-unknown-none 100 | override: true 101 | 102 | - name: Check 103 | uses: actions-rs/cargo@v1 104 | with: 105 | command: check 106 | args: --examples --workspace --target aarch64-unknown-none 107 | 108 | - name: Build 109 | uses: actions-rs/cargo@v1 110 | with: 111 | command: build 112 | args: --workspace --target aarch64-unknown-none 113 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thank you for considering making contributions to `arkworks-rs/snark`! 4 | 5 | Contributing to this repo can be done in several forms, such as participating in discussion or proposing code changes. 6 | To ensure a smooth workflow for all contributors, the following general procedure for contributing has been established: 7 | 8 | 1) Either open or find an issue you'd like to help with 9 | 2) Participate in thoughtful discussion on that issue 10 | 3) If you would like to contribute: 11 | * If the issue is a feature proposal, ensure that the proposal has been accepted 12 | * Ensure that nobody else has already begun working on this issue. 13 | If they have, please try to contact them to collaborate 14 | * 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) 15 | * We suggest using standard Github best practices for contributing: fork the repo, branch from the HEAD of `master`, make some commits on your branch, and submit a PR from the branch to `master`. 16 | More detail on this is below 17 | * Be sure to include a relevant change log entry in the Pending section of CHANGELOG.md (see file for log format) 18 | * If the change is breaking, we may add migration instructions. 19 | 20 | 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. 21 | 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. 22 | 23 | Looking for a good place to start contributing? How about checking out some good first issues 24 | 25 | ## Branch Structure 26 | 27 | `snark` has its default branch as `master`, which is where PRs are merged into. Releases will be periodically made, on no set schedule. 28 | All other branches should be assumed to be miscellaneous feature development branches. 29 | 30 | All downstream users of the library should be using tagged versions of the library pulled from cargo. 31 | 32 | ## How to work on a fork 33 | Please skip this section if you're familiar with contributing to opensource github projects. 34 | 35 | First fork the repo from the github UI, and clone it locally. 36 | Then in the repo, you want to add the repo you forked from as a new remote. You do this as: 37 | ```bash 38 | git remote add upstream git@github.com:arkworks-rs/snark.git 39 | ``` 40 | 41 | Then the way you make code contributions is to first think of a branch name that describes your change. 42 | Then do the following: 43 | ```bash 44 | git checkout master 45 | git pull upstream master 46 | git checkout -b $NEW_BRANCH_NAME 47 | ``` 48 | and then work as normal on that branch, and pull request to upstream master when you're done =) 49 | 50 | ## Updating documentation 51 | 52 | All PRs should aim to leave the code more documented than it started with. 53 | Please don't assume that its easy to infer what the code is doing, 54 | as that is usually not the case for these complex protocols. 55 | (Even when you understand the paper!) 56 | 57 | Its often very useful to describe what is the high level view of what a code block is doing, 58 | 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. 59 | 60 | ## Performance improvements 61 | 62 | All performance improvements should be accompanied with benchmarks improving, or otherwise have it be clear that things have improved. 63 | For some areas of the codebase, performance roughly follows the number of field multiplications, but there are also many areas where 64 | hard to predict low level system effects such as cache locality and superscalar operations become important for performance. 65 | Thus performance can often become very non-intuitive / diverge from minimizing the number of arithmetic operations. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

SNARK and Relation Traits

2 | 3 |

4 | 5 | 6 | 7 | 8 |

9 | 10 | The arkworks ecosystem consists of Rust libraries for designing and working with __zero knowledge succinct non-interactive arguments (zkSNARKs)__. This repository contains efficient libraries that describe interfaces for zkSNARKs, as well as interfaces for programming them. 11 | 12 | This library is released under the MIT License and the Apache v2 License (see [License](#license)). 13 | 14 | **WARNING:** This is an academic proof-of-concept prototype, and in particular has not received careful code review. This implementation is NOT ready for production use. 15 | 16 | ## Directory structure 17 | 18 | This repository contains two Rust crates: 19 | 20 | * [`ark-snark`](snark): Provides generic traits for zkSNARKs 21 | * [`ark-relations`](relations): Provides generic traits for NP relations used in programming zkSNARKs, such as R1CS 22 | 23 | ## Overview 24 | 25 | This repository provides the core infrastructure for using the succinct argument systems that arkworks provides. Users who want to produce arguments about various problems of interest will first reduce those problems to an NP relation, various examples of which are defined in the `ark-relations` crate. Then a SNARK system defined over that relation is used to produce a succinct argument. The `ark-snark` crate defines a `SNARK` trait that encapsulates the general functionality, as well as specific traits for various types of SNARK (those with transparent and universal setup, for instance). Different repositories within the arkworks ecosystem implement this trait for various specific SNARK constructions, such as [Groth16](https://github.com/arkworks-rs/groth16), [GM17](https://github.com/arkworks-rs/gm17), and [Marlin](https://github.com/arkworks-rs/marlin). 26 | 27 | ## Build guide 28 | 29 | The library compiles on the `stable` toolchain of the Rust compiler. To install the latest version of Rust, first install `rustup` by following the instructions [here](https://rustup.rs/), or via your platform's package manager. Once `rustup` is installed, install the Rust toolchain by invoking: 30 | ```bash 31 | rustup install stable 32 | ``` 33 | 34 | After that, use `cargo`, the standard Rust build tool, to build the libraries: 35 | ```bash 36 | git clone https://github.com/arkworks-rs/snark.git 37 | cd snark 38 | cargo build --release 39 | ``` 40 | 41 | ## Tests 42 | This library comes with comprehensive unit and integration tests for each of the provided crates. Run the tests with: 43 | ```bash 44 | cargo test --all 45 | ``` 46 | 47 | ## License 48 | 49 | The crates in this repo are licensed under either of the following licenses, at your discretion. 50 | 51 | * Apache License Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 52 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 53 | 54 | Unless you explicitly state otherwise, any contribution submitted for inclusion in this library by you shall be dual licensed as above (as defined in the Apache v2 License), without any additional terms or conditions. 55 | 56 | [zexe]: https://ia.cr/2018/962 57 | 58 | ## Acknowledgements 59 | 60 | This work was supported by: 61 | a Google Faculty Award; 62 | the National Science Foundation; 63 | the UC Berkeley Center for Long-Term Cybersecurity; 64 | and donations from the Ethereum Foundation, the Interchain Foundation, and Qtum. 65 | 66 | An earlier version of this library was developed as part of the paper *"[ZEXE: Enabling Decentralized Private Computation][zexe]"*. 67 | -------------------------------------------------------------------------------- /relations/src/r1cs/mod.rs: -------------------------------------------------------------------------------- 1 | //! Core interface for working with Rank-1 Constraint Systems (R1CS). 2 | 3 | use ark_std::vec::Vec; 4 | 5 | /// A result type specialized to `SynthesisError`. 6 | pub type Result = core::result::Result; 7 | 8 | #[macro_use] 9 | mod impl_lc; 10 | mod constraint_system; 11 | mod error; 12 | #[cfg(feature = "std")] 13 | mod trace; 14 | 15 | #[cfg(feature = "std")] 16 | pub use crate::r1cs::trace::{ConstraintLayer, ConstraintTrace, TraceStep, TracingMode}; 17 | 18 | pub use tracing::info_span; 19 | 20 | pub use ark_ff::{Field, ToConstraintField}; 21 | pub use constraint_system::{ 22 | ConstraintMatrices, ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, Namespace, 23 | OptimizationGoal, SynthesisMode, 24 | }; 25 | pub use error::SynthesisError; 26 | 27 | use core::cmp::Ordering; 28 | 29 | /// A sparse representation of constraint matrices. 30 | pub type Matrix = Vec>; 31 | 32 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] 33 | /// An opaque counter for symbolic linear combinations. 34 | pub struct LcIndex(usize); 35 | 36 | /// Represents the different kinds of variables present in a constraint system. 37 | #[derive(Copy, Clone, PartialEq, Debug, Eq)] 38 | pub enum Variable { 39 | /// Represents the "zero" constant. 40 | Zero, 41 | /// Represents of the "one" constant. 42 | One, 43 | /// Represents a public instance variable. 44 | Instance(usize), 45 | /// Represents a private witness variable. 46 | Witness(usize), 47 | /// Represents of a linear combination. 48 | SymbolicLc(LcIndex), 49 | } 50 | 51 | /// A linear combination of variables according to associated coefficients. 52 | #[derive(Debug, Clone, PartialEq, Eq, Default)] 53 | pub struct LinearCombination(pub Vec<(F, Variable)>); 54 | 55 | /// Generate a `Namespace` with name `name` from `ConstraintSystem` `cs`. 56 | /// `name` must be a `&'static str`. 57 | #[macro_export] 58 | macro_rules! ns { 59 | ($cs:expr, $name:expr) => {{ 60 | let span = $crate::r1cs::info_span!(target: "r1cs", $name); 61 | let id = span.id(); 62 | let _enter_guard = span.enter(); 63 | core::mem::forget(_enter_guard); 64 | core::mem::forget(span); 65 | $crate::r1cs::Namespace::new($cs.clone(), id) 66 | }}; 67 | } 68 | 69 | impl Variable { 70 | /// Is `self` the zero variable? 71 | #[inline] 72 | pub fn is_zero(&self) -> bool { 73 | matches!(self, Variable::Zero) 74 | } 75 | 76 | /// Is `self` the one variable? 77 | #[inline] 78 | pub fn is_one(&self) -> bool { 79 | matches!(self, Variable::One) 80 | } 81 | 82 | /// Is `self` an instance variable? 83 | #[inline] 84 | pub fn is_instance(&self) -> bool { 85 | matches!(self, Variable::Instance(_)) 86 | } 87 | 88 | /// Is `self` a witness variable? 89 | #[inline] 90 | pub fn is_witness(&self) -> bool { 91 | matches!(self, Variable::Witness(_)) 92 | } 93 | 94 | /// Is `self` a linear combination? 95 | #[inline] 96 | pub fn is_lc(&self) -> bool { 97 | matches!(self, Variable::SymbolicLc(_)) 98 | } 99 | 100 | /// Get the `LcIndex` in `self` if `self.is_lc()`. 101 | #[inline] 102 | pub fn get_lc_index(&self) -> Option { 103 | match self { 104 | Variable::SymbolicLc(index) => Some(*index), 105 | _ => None, 106 | } 107 | } 108 | 109 | /// Returns `Some(usize)` if `!self.is_lc()`, and `None` otherwise. 110 | #[inline] 111 | pub fn get_index_unchecked(&self, witness_offset: usize) -> Option { 112 | match self { 113 | // The one variable always has index 0 114 | Variable::One => Some(0), 115 | Variable::Instance(i) => Some(*i), 116 | Variable::Witness(i) => Some(witness_offset + *i), 117 | _ => None, 118 | } 119 | } 120 | } 121 | 122 | impl PartialOrd for Variable { 123 | fn partial_cmp(&self, other: &Self) -> Option { 124 | use Variable::*; 125 | match (self, other) { 126 | (Zero, Zero) => Some(Ordering::Equal), 127 | (One, One) => Some(Ordering::Equal), 128 | (Zero, _) => Some(Ordering::Less), 129 | (One, _) => Some(Ordering::Less), 130 | (_, Zero) => Some(Ordering::Greater), 131 | (_, One) => Some(Ordering::Greater), 132 | 133 | (Instance(i), Instance(j)) | (Witness(i), Witness(j)) => i.partial_cmp(j), 134 | (Instance(_), Witness(_)) => Some(Ordering::Less), 135 | (Witness(_), Instance(_)) => Some(Ordering::Greater), 136 | 137 | (SymbolicLc(i), SymbolicLc(j)) => i.partial_cmp(j), 138 | (_, SymbolicLc(_)) => Some(Ordering::Less), 139 | (SymbolicLc(_), _) => Some(Ordering::Greater), 140 | } 141 | } 142 | } 143 | 144 | impl Ord for Variable { 145 | fn cmp(&self, other: &Self) -> Ordering { 146 | self.partial_cmp(other).unwrap() 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /snark/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate contains traits that define the basic behaviour of SNARKs. 2 | 3 | #![cfg_attr(not(feature = "std"), no_std)] 4 | #![warn( 5 | unused, 6 | future_incompatible, 7 | nonstandard_style, 8 | rust_2018_idioms, 9 | missing_docs 10 | )] 11 | #![forbid(unsafe_code)] 12 | 13 | use ark_ff::PrimeField; 14 | use ark_relations::r1cs::ConstraintSynthesizer; 15 | use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; 16 | use ark_std::fmt::Debug; 17 | use ark_std::rand::{CryptoRng, RngCore}; 18 | 19 | /// The basic functionality for a SNARK. 20 | pub trait SNARK { 21 | /// The information required by the prover to produce a proof for a specific 22 | /// circuit *C*. 23 | type ProvingKey: Clone + CanonicalSerialize + CanonicalDeserialize; 24 | 25 | /// The information required by the verifier to check a proof for a specific 26 | /// circuit *C*. 27 | type VerifyingKey: Clone + CanonicalSerialize + CanonicalDeserialize; 28 | 29 | /// The proof output by the prover. 30 | type Proof: Clone + CanonicalSerialize + CanonicalDeserialize; 31 | 32 | /// This contains the verification key, but preprocessed to enable faster 33 | /// verification. 34 | type ProcessedVerifyingKey: Clone + CanonicalSerialize + CanonicalDeserialize; 35 | 36 | /// Errors encountered during setup, proving, or verification. 37 | type Error: 'static + ark_std::error::Error; 38 | 39 | /// Takes in a description of a computation (specified in R1CS constraints), 40 | /// and samples proving and verification keys for that circuit. 41 | fn circuit_specific_setup, R: RngCore + CryptoRng>( 42 | circuit: C, 43 | rng: &mut R, 44 | ) -> Result<(Self::ProvingKey, Self::VerifyingKey), Self::Error>; 45 | 46 | /// Generates a proof of satisfaction of the arithmetic circuit C (specified 47 | /// as R1CS constraints). 48 | fn prove, R: RngCore + CryptoRng>( 49 | circuit_pk: &Self::ProvingKey, 50 | circuit: C, 51 | rng: &mut R, 52 | ) -> Result; 53 | 54 | /// Checks that `proof` is a valid proof of the satisfaction of circuit 55 | /// encoded in `circuit_vk`, with respect to the public input `public_input`, 56 | /// specified as R1CS constraints. 57 | fn verify( 58 | circuit_vk: &Self::VerifyingKey, 59 | public_input: &[F], 60 | proof: &Self::Proof, 61 | ) -> Result { 62 | let pvk = Self::process_vk(circuit_vk)?; 63 | Self::verify_with_processed_vk(&pvk, public_input, proof) 64 | } 65 | 66 | /// Preprocesses `circuit_vk` to enable faster verification. 67 | fn process_vk( 68 | circuit_vk: &Self::VerifyingKey, 69 | ) -> Result; 70 | 71 | /// Checks that `proof` is a valid proof of the satisfaction of circuit 72 | /// encoded in `circuit_pvk`, with respect to the public input `public_input`, 73 | /// specified as R1CS constraints. 74 | fn verify_with_processed_vk( 75 | circuit_pvk: &Self::ProcessedVerifyingKey, 76 | public_input: &[F], 77 | proof: &Self::Proof, 78 | ) -> Result; 79 | } 80 | 81 | /// A SNARK with (only) circuit-specific setup. 82 | pub trait CircuitSpecificSetupSNARK: SNARK { 83 | /// The setup algorithm for circuit-specific SNARKs. By default, this 84 | /// just invokes `>::circuit_specific_setup(...)`. 85 | fn setup, R: RngCore + CryptoRng>( 86 | circuit: C, 87 | rng: &mut R, 88 | ) -> Result<(Self::ProvingKey, Self::VerifyingKey), Self::Error> { 89 | >::circuit_specific_setup(circuit, rng) 90 | } 91 | } 92 | 93 | /// A helper type for universal-setup SNARKs, which must infer their computation 94 | /// size bounds. 95 | pub enum UniversalSetupIndexError { 96 | /// The provided universal public parameters were insufficient to encode 97 | /// the given circuit. 98 | NeedLargerBound(Bound), 99 | /// Other errors occurred during indexing. 100 | Other(E), 101 | } 102 | 103 | /// A SNARK with universal setup. That is, a SNARK where the trusted setup is 104 | /// circuit-independent. 105 | pub trait UniversalSetupSNARK: SNARK { 106 | /// Specifies how to bound the size of public parameters required to 107 | /// generate the index proving and verification keys for a given 108 | /// circuit. 109 | type ComputationBound: Clone + Default + Debug; 110 | /// Specifies the type of universal public parameters. 111 | type PublicParameters: Clone + Debug; 112 | 113 | /// Specifies how to bound the size of public parameters required to 114 | /// generate the index proving and verification keys for a given 115 | /// circuit. 116 | fn universal_setup( 117 | compute_bound: &Self::ComputationBound, 118 | rng: &mut R, 119 | ) -> Result; 120 | 121 | /// Indexes the public parameters according to the circuit `circuit`, and 122 | /// outputs circuit-specific proving and verification keys. 123 | fn index, R: RngCore + CryptoRng>( 124 | pp: &Self::PublicParameters, 125 | circuit: C, 126 | rng: &mut R, 127 | ) -> Result< 128 | (Self::ProvingKey, Self::VerifyingKey), 129 | UniversalSetupIndexError, 130 | >; 131 | } 132 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /relations/src/r1cs/trace.rs: -------------------------------------------------------------------------------- 1 | // adapted from `tracing_error::{SpanTrace, ErrorLayer}`. 2 | 3 | use core::{ 4 | any::{type_name, TypeId}, 5 | fmt, 6 | marker::PhantomData, 7 | }; 8 | use tracing::{span, Dispatch, Metadata, Subscriber}; 9 | use tracing_subscriber::{ 10 | layer::{self, Layer}, 11 | registry::LookupSpan, 12 | }; 13 | 14 | /// A subscriber [`Layer`] that enables capturing a trace of R1CS constraint 15 | /// generation. 16 | /// 17 | /// [`Layer`]: https://docs.rs/tracing-subscriber/0.2.10/tracing_subscriber/layer/trait.Layer.html 18 | /// [field formatter]: https://docs.rs/tracing-subscriber/0.2.10/tracing_subscriber/fmt/trait.FormatFields.html 19 | /// [default format]: https://docs.rs/tracing-subscriber/0.2.10/tracing_subscriber/fmt/format/struct.DefaultFields.html 20 | pub struct ConstraintLayer { 21 | /// Mode of filtering. 22 | pub mode: TracingMode, 23 | 24 | get_context: WithContext, 25 | _subscriber: PhantomData, 26 | } 27 | 28 | /// Instructs `ConstraintLayer` to conditionally filter out spans. 29 | #[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] 30 | pub enum TracingMode { 31 | /// Instructs `ConstraintLayer` to filter out any spans that *do not* have 32 | /// `target == "r1cs"`. 33 | OnlyConstraints, 34 | /// Instructs `ConstraintLayer` to filter out any spans that *do* have 35 | /// `target == "r1cs"`. 36 | NoConstraints, 37 | /// Instructs `ConstraintLayer` to not filter out any spans. 38 | All, 39 | } 40 | 41 | // this function "remembers" the types of the subscriber and the formatter, 42 | // so that we can downcast to something aware of them without knowing those 43 | // types at the callsite. 44 | pub(crate) struct WithContext( 45 | fn(&Dispatch, &span::Id, f: &mut dyn FnMut(&'static Metadata<'static>, &str) -> bool), 46 | ); 47 | 48 | impl Layer for ConstraintLayer 49 | where 50 | S: Subscriber + for<'span> LookupSpan<'span>, 51 | { 52 | fn enabled(&self, metadata: &Metadata<'_>, _ctx: layer::Context<'_, S>) -> bool { 53 | match self.mode { 54 | TracingMode::OnlyConstraints => metadata.target() == "r1cs", 55 | TracingMode::NoConstraints => metadata.target() != "r1cs", 56 | TracingMode::All => true, 57 | } 58 | } 59 | 60 | /// Notifies this layer that a new span was constructed with the given 61 | /// `Attributes` and `Id`. 62 | fn new_span(&self, _attrs: &span::Attributes<'_>, _id: &span::Id, _ctx: layer::Context<'_, S>) { 63 | } 64 | 65 | #[allow(unsafe_code, trivial_casts)] 66 | unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> { 67 | match id { 68 | id if id == TypeId::of::() => Some(self as *const _ as *const ()), 69 | id if id == TypeId::of::() => { 70 | Some(&self.get_context as *const _ as *const ()) 71 | }, 72 | _ => None, 73 | } 74 | } 75 | } 76 | 77 | impl ConstraintLayer 78 | where 79 | S: Subscriber + for<'span> LookupSpan<'span>, 80 | { 81 | /// Returns a new `ConstraintLayer`. 82 | /// 83 | /// If `mode == TracingMode::OnlyConstraints`, the resulting layer will 84 | /// filter out any spans whose `target != "r1cs"`. 85 | /// 86 | /// If `mode == TracingMode::NoConstraints`, the resulting layer will 87 | /// filter out any spans whose `target == "r1cs"`. 88 | /// 89 | /// Finally, if `mode == TracingMode::All`, the resulting layer will 90 | /// not filter out any spans. 91 | pub fn new(mode: TracingMode) -> Self { 92 | Self { 93 | mode, 94 | get_context: WithContext(Self::get_context), 95 | _subscriber: PhantomData, 96 | } 97 | } 98 | 99 | fn get_context( 100 | dispatch: &Dispatch, 101 | id: &span::Id, 102 | f: &mut dyn FnMut(&'static Metadata<'static>, &str) -> bool, 103 | ) { 104 | let subscriber = dispatch 105 | .downcast_ref::() 106 | .expect("subscriber should downcast to expected type; this is a bug!"); 107 | let span = subscriber 108 | .span(id) 109 | .expect("registry should have a span for the current ID"); 110 | for span in span.scope() { 111 | let cont = f(span.metadata(), ""); 112 | if !cont { 113 | break; 114 | } 115 | } 116 | } 117 | } 118 | 119 | impl WithContext { 120 | pub(crate) fn with_context<'a>( 121 | &self, 122 | dispatch: &'a Dispatch, 123 | id: &span::Id, 124 | mut f: impl FnMut(&'static Metadata<'static>, &str) -> bool, 125 | ) { 126 | (self.0)(dispatch, id, &mut f) 127 | } 128 | } 129 | 130 | impl Default for ConstraintLayer 131 | where 132 | S: Subscriber + for<'span> LookupSpan<'span>, 133 | { 134 | fn default() -> Self { 135 | Self::new(TracingMode::All) 136 | } 137 | } 138 | 139 | impl fmt::Debug for ConstraintLayer { 140 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 141 | f.debug_struct("ConstraintLayer") 142 | .field("subscriber", &format_args!("{}", type_name::())) 143 | .finish() 144 | } 145 | } 146 | 147 | macro_rules! try_bool { 148 | ($e:expr, $dest:ident) => {{ 149 | let ret = $e.unwrap_or_else(|e| $dest = Err(e)); 150 | 151 | if $dest.is_err() { 152 | return false; 153 | } 154 | 155 | ret 156 | }}; 157 | } 158 | 159 | /// A captured trace of [`tracing`] spans that have `target = "r1cs"`. 160 | /// 161 | /// This type can be thought of as a relative of 162 | /// [`std::backtrace::Backtrace`][`Backtrace`]. 163 | /// However, rather than capturing the current call stack when it is 164 | /// constructed, a `ConstraintTrace` instead captures the current [span] and its 165 | /// [parents]. It allows inspection of the constraints that are left unsatisfied 166 | /// by a particular witness assignment to an R1CS instance. 167 | /// 168 | /// # Formatting 169 | /// 170 | /// The `ConstraintTrace` type implements `fmt::Display`, formatting the span 171 | /// trace similarly to how Rust formats panics. For example: 172 | /// 173 | /// ```text 174 | /// 0: r1cs-std::bits::something 175 | /// at r1cs-std/src/bits/test.rs:42 176 | /// 1: r1cs-std::bits::another_thing 177 | /// at r1cs-std/src/bits/test.rs:15 178 | /// ``` 179 | /// 180 | /// [`tracing`]: https://docs.rs/tracing 181 | /// [`Backtrace`]: https://doc.rust-lang.org/std/backtrace/struct.Backtrace.html 182 | /// [span]: https://docs.rs/tracing/latest/tracing/span/index.html 183 | /// [parents]: https://docs.rs/tracing/latest/tracing/span/index.html#span-relationships 184 | #[derive(Clone, Debug)] 185 | pub struct ConstraintTrace { 186 | span: span::Span, 187 | } 188 | 189 | // === impl ConstraintTrace === 190 | 191 | impl ConstraintTrace { 192 | /// Capture the current span trace. 193 | /// 194 | /// # Examples 195 | /// ```rust 196 | /// use ark_relations::r1cs::ConstraintTrace; 197 | /// 198 | /// pub struct MyError { 199 | /// trace: Option, 200 | /// // ... 201 | /// } 202 | /// 203 | /// # fn some_error_condition() -> bool { true } 204 | /// 205 | /// pub fn my_function(arg: &str) -> Result<(), MyError> { 206 | /// let _span = tracing::info_span!(target: "r1cs", "In my_function"); 207 | /// let _guard = _span.enter(); 208 | /// if some_error_condition() { 209 | /// return Err(MyError { 210 | /// trace: ConstraintTrace::capture(), 211 | /// // ... 212 | /// }); 213 | /// } 214 | /// 215 | /// // ... 216 | /// # Ok(()) 217 | /// } 218 | /// ``` 219 | pub fn capture() -> Option { 220 | let span = span::Span::current(); 221 | 222 | if span.is_none() { 223 | None 224 | } else { 225 | let trace = Self { span }; 226 | Some(trace) 227 | } 228 | } 229 | 230 | /// Apply a function to all captured spans in the trace until it returns 231 | /// `false`. 232 | /// 233 | /// This will call the provided function with a reference to the 234 | /// [`Metadata`] and a formatted representation of the [fields] of each span 235 | /// captured in the trace, starting with the span that was current when the 236 | /// trace was captured. The function may return `true` or `false` to 237 | /// indicate whether to continue iterating over spans; if it returns 238 | /// `false`, no additional spans will be visited. 239 | /// 240 | /// [fields]: https://docs.rs/tracing/latest/tracing/field/index.html 241 | /// [`Metadata`]: https://docs.rs/tracing/latest/tracing/struct.Metadata.html 242 | fn with_spans(&self, f: impl FnMut(&'static Metadata<'static>, &str) -> bool) { 243 | self.span.with_subscriber(|(id, s)| { 244 | if let Some(getcx) = s.downcast_ref::() { 245 | getcx.with_context(s, id, f); 246 | } 247 | }); 248 | } 249 | 250 | /// Compute a `Vec` of `TraceStep`s, one for each `Span` on the path from 251 | /// the root `Span`. 252 | /// 253 | /// The output starts from the root of the span tree. 254 | pub fn path(&self) -> Vec { 255 | let mut path = Vec::new(); 256 | self.with_spans(|metadata, _| { 257 | if metadata.target() == "r1cs" { 258 | let n = metadata.name(); 259 | let step = metadata 260 | .module_path() 261 | .map(|m| (n, m)) 262 | .and_then(|(n, m)| metadata.file().map(|f| (n, m, f))) 263 | .and_then(|(n, m, f)| metadata.line().map(|l| (n, m, f, l))); 264 | if let Some((name, module_path, file, line)) = step { 265 | let step = TraceStep { 266 | name, 267 | module_path, 268 | file, 269 | line, 270 | }; 271 | path.push(step); 272 | } else { 273 | return false; 274 | } 275 | } 276 | true 277 | }); 278 | path.reverse(); // root first 279 | path 280 | } 281 | } 282 | 283 | impl fmt::Display for ConstraintTrace { 284 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 285 | let mut err = Ok(()); 286 | let mut span = 0; 287 | 288 | self.with_spans(|metadata, _| { 289 | if metadata.target() != "r1cs" { 290 | return true; 291 | } 292 | if span > 0 { 293 | try_bool!(write!(f, "\n",), err); 294 | } 295 | 296 | try_bool!( 297 | write!( 298 | f, 299 | "{:>4}: {}::{}", 300 | span, 301 | metadata.module_path().unwrap(), 302 | metadata.name() 303 | ), 304 | err 305 | ); 306 | 307 | if let Some((file, line)) = metadata 308 | .file() 309 | .and_then(|file| metadata.line().map(|line| (file, line))) 310 | { 311 | try_bool!(write!(f, "\n at {}:{}", file, line), err); 312 | } 313 | 314 | span += 1; 315 | true 316 | }); 317 | 318 | err 319 | } 320 | } 321 | /// A step in the trace of a constraint generation step. 322 | #[derive(Debug, Clone, Copy)] 323 | pub struct TraceStep { 324 | /// Name of the constraint generating span. 325 | pub name: &'static str, 326 | /// Name of the module containing the constraint generating span. 327 | pub module_path: &'static str, 328 | /// Name of the file containing the constraint generating span. 329 | pub file: &'static str, 330 | /// Line number of the constraint generating span. 331 | pub line: u32, 332 | } 333 | -------------------------------------------------------------------------------- /relations/src/r1cs/impl_lc.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::suspicious_arithmetic_impl)] 2 | 3 | use crate::r1cs::{LinearCombination, Variable}; 4 | use ark_ff::Field; 5 | use ark_std::{ 6 | ops::{Add, AddAssign, Deref, DerefMut, Mul, MulAssign, Neg, Sub}, 7 | vec, 8 | vec::Vec, 9 | }; 10 | 11 | /// Generate a `LinearCombination` from arithmetic expressions involving 12 | /// `Variable`s. 13 | #[macro_export] 14 | macro_rules! lc { 15 | () => { 16 | $crate::r1cs::LinearCombination::zero() 17 | }; 18 | } 19 | 20 | impl LinearCombination { 21 | /// Create a new empty linear combination. 22 | pub fn new() -> Self { 23 | Default::default() 24 | } 25 | 26 | /// Create a new empty linear combination. 27 | pub fn zero() -> Self { 28 | Self::new() 29 | } 30 | 31 | /// Deduplicate entries in `self`. 32 | pub fn compactify(&mut self) { 33 | self.0.sort_by_key(|e| e.1); 34 | let mut current_var = None; 35 | let mut current_var_first_index = 0; 36 | for i in 0..self.0.len() { 37 | let (f, v) = self.0[i]; 38 | if Some(v) == current_var { 39 | self.0[current_var_first_index].0 += &f; 40 | } else { 41 | current_var = Some(v); 42 | current_var_first_index = i; 43 | } 44 | } 45 | self.0.dedup_by_key(|e| e.1); 46 | } 47 | } 48 | 49 | impl<'a, F: Field> Deref for LinearCombination { 50 | type Target = Vec<(F, Variable)>; 51 | 52 | #[inline] 53 | fn deref(&self) -> &Vec<(F, Variable)> { 54 | &self.0 55 | } 56 | } 57 | 58 | impl DerefMut for LinearCombination { 59 | #[inline] 60 | fn deref_mut(&mut self) -> &mut Self::Target { 61 | &mut self.0 62 | } 63 | } 64 | 65 | impl From<(F, Variable)> for LinearCombination { 66 | #[inline] 67 | fn from(input: (F, Variable)) -> Self { 68 | LinearCombination(vec![input]) 69 | } 70 | } 71 | 72 | impl From for LinearCombination { 73 | #[inline] 74 | fn from(var: Variable) -> Self { 75 | LinearCombination(vec![(F::one(), var)]) 76 | } 77 | } 78 | 79 | impl LinearCombination { 80 | /// Negate the coefficients of all variables in `self`. 81 | #[inline] 82 | pub fn negate_in_place(&mut self) { 83 | self.0.iter_mut().for_each(|(coeff, _)| *coeff = -(*coeff)); 84 | } 85 | 86 | /// Get the location of a variable in `self`. 87 | #[inline] 88 | pub fn get_var_loc(&self, search_var: &Variable) -> Result { 89 | if self.0.len() < 6 { 90 | let mut found_index = 0; 91 | for (i, (_, var)) in self.iter().enumerate() { 92 | if var >= search_var { 93 | found_index = i; 94 | break; 95 | } else { 96 | found_index += 1; 97 | } 98 | } 99 | Err(found_index) 100 | } else { 101 | self.0 102 | .binary_search_by_key(search_var, |&(_, cur_var)| cur_var) 103 | } 104 | } 105 | } 106 | 107 | impl Add<(F, Variable)> for LinearCombination { 108 | type Output = Self; 109 | 110 | #[inline] 111 | fn add(mut self, coeff_var: (F, Variable)) -> Self { 112 | self += coeff_var; 113 | self 114 | } 115 | } 116 | 117 | impl AddAssign<(F, Variable)> for LinearCombination { 118 | #[inline] 119 | fn add_assign(&mut self, (coeff, var): (F, Variable)) { 120 | match self.get_var_loc(&var) { 121 | Ok(found) => self.0[found].0 += &coeff, 122 | Err(not_found) => self.0.insert(not_found, (coeff, var)), 123 | } 124 | } 125 | } 126 | 127 | impl Sub<(F, Variable)> for LinearCombination { 128 | type Output = Self; 129 | 130 | #[inline] 131 | fn sub(self, (coeff, var): (F, Variable)) -> Self { 132 | self + (-coeff, var) 133 | } 134 | } 135 | 136 | impl Neg for LinearCombination { 137 | type Output = Self; 138 | 139 | #[inline] 140 | fn neg(mut self) -> Self { 141 | self.negate_in_place(); 142 | self 143 | } 144 | } 145 | 146 | impl Mul for LinearCombination { 147 | type Output = Self; 148 | 149 | #[inline] 150 | fn mul(mut self, scalar: F) -> Self { 151 | self *= scalar; 152 | self 153 | } 154 | } 155 | 156 | impl<'a, F: Field> Mul for &'a LinearCombination { 157 | type Output = LinearCombination; 158 | 159 | #[inline] 160 | fn mul(self, scalar: F) -> LinearCombination { 161 | let mut cur = self.clone(); 162 | cur *= scalar; 163 | cur 164 | } 165 | } 166 | 167 | impl MulAssign for LinearCombination { 168 | #[inline] 169 | fn mul_assign(&mut self, scalar: F) { 170 | self.0.iter_mut().for_each(|(coeff, _)| *coeff *= &scalar); 171 | } 172 | } 173 | 174 | impl Add for LinearCombination { 175 | type Output = Self; 176 | 177 | #[inline] 178 | fn add(self, other: Variable) -> LinearCombination { 179 | self + (F::one(), other) 180 | } 181 | } 182 | 183 | impl<'a, F: Field> Add<&'a Variable> for LinearCombination { 184 | type Output = Self; 185 | 186 | #[inline] 187 | fn add(self, other: &'a Variable) -> LinearCombination { 188 | self + *other 189 | } 190 | } 191 | 192 | impl<'a, F: Field> Sub<&'a Variable> for LinearCombination { 193 | type Output = Self; 194 | 195 | #[inline] 196 | fn sub(self, other: &'a Variable) -> LinearCombination { 197 | self - *other 198 | } 199 | } 200 | 201 | impl Sub for LinearCombination { 202 | type Output = LinearCombination; 203 | 204 | #[inline] 205 | fn sub(self, other: Variable) -> LinearCombination { 206 | self - (F::one(), other) 207 | } 208 | } 209 | 210 | fn op_impl( 211 | cur: &LinearCombination, 212 | other: &LinearCombination, 213 | push_fn: F1, 214 | combine_fn: F2, 215 | ) -> LinearCombination 216 | where 217 | F1: Fn(F) -> F, 218 | F2: Fn(F, F) -> F, 219 | { 220 | let mut new_vec = Vec::new(); 221 | let mut i = 0; 222 | let mut j = 0; 223 | while i < cur.len() && j < other.len() { 224 | let self_cur = &cur[i]; 225 | let other_cur = &other[j]; 226 | use core::cmp::Ordering; 227 | match self_cur.1.cmp(&other_cur.1) { 228 | Ordering::Greater => { 229 | new_vec.push((push_fn(other[j].0), other[j].1)); 230 | j += 1; 231 | }, 232 | Ordering::Less => { 233 | new_vec.push(*self_cur); 234 | i += 1; 235 | }, 236 | Ordering::Equal => { 237 | new_vec.push((combine_fn(self_cur.0, other_cur.0), self_cur.1)); 238 | i += 1; 239 | j += 1; 240 | }, 241 | }; 242 | } 243 | new_vec.extend_from_slice(&cur[i..]); 244 | while j < other.0.len() { 245 | new_vec.push((push_fn(other[j].0), other[j].1)); 246 | j += 1; 247 | } 248 | LinearCombination(new_vec) 249 | } 250 | 251 | impl Add<&LinearCombination> for &LinearCombination { 252 | type Output = LinearCombination; 253 | 254 | fn add(self, other: &LinearCombination) -> LinearCombination { 255 | if other.0.is_empty() { 256 | return self.clone(); 257 | } else if self.0.is_empty() { 258 | return other.clone(); 259 | } 260 | op_impl( 261 | self, 262 | other, 263 | |coeff| coeff, 264 | |cur_coeff, other_coeff| cur_coeff + other_coeff, 265 | ) 266 | } 267 | } 268 | 269 | impl Add> for &LinearCombination { 270 | type Output = LinearCombination; 271 | 272 | fn add(self, other: LinearCombination) -> LinearCombination { 273 | if self.0.is_empty() { 274 | return other; 275 | } else if other.0.is_empty() { 276 | return self.clone(); 277 | } 278 | op_impl( 279 | self, 280 | &other, 281 | |coeff| coeff, 282 | |cur_coeff, other_coeff| cur_coeff + other_coeff, 283 | ) 284 | } 285 | } 286 | 287 | impl<'a, F: Field> Add<&'a LinearCombination> for LinearCombination { 288 | type Output = LinearCombination; 289 | 290 | fn add(self, other: &'a LinearCombination) -> LinearCombination { 291 | if other.0.is_empty() { 292 | return self; 293 | } else if self.0.is_empty() { 294 | return other.clone(); 295 | } 296 | op_impl( 297 | &self, 298 | other, 299 | |coeff| coeff, 300 | |cur_coeff, other_coeff| cur_coeff + other_coeff, 301 | ) 302 | } 303 | } 304 | 305 | impl Add> for LinearCombination { 306 | type Output = Self; 307 | 308 | fn add(self, other: Self) -> Self { 309 | if other.0.is_empty() { 310 | return self; 311 | } else if self.0.is_empty() { 312 | return other; 313 | } 314 | op_impl( 315 | &self, 316 | &other, 317 | |coeff| coeff, 318 | |cur_coeff, other_coeff| cur_coeff + other_coeff, 319 | ) 320 | } 321 | } 322 | 323 | impl Sub<&LinearCombination> for &LinearCombination { 324 | type Output = LinearCombination; 325 | 326 | fn sub(self, other: &LinearCombination) -> LinearCombination { 327 | if other.0.is_empty() { 328 | let cur = self.clone(); 329 | return cur; 330 | } else if self.0.is_empty() { 331 | let mut other = other.clone(); 332 | other.negate_in_place(); 333 | return other; 334 | } 335 | 336 | op_impl( 337 | self, 338 | other, 339 | |coeff| -coeff, 340 | |cur_coeff, other_coeff| cur_coeff - other_coeff, 341 | ) 342 | } 343 | } 344 | 345 | impl<'a, F: Field> Sub<&'a LinearCombination> for LinearCombination { 346 | type Output = LinearCombination; 347 | 348 | fn sub(self, other: &'a LinearCombination) -> LinearCombination { 349 | if other.0.is_empty() { 350 | return self; 351 | } else if self.0.is_empty() { 352 | let mut other = other.clone(); 353 | other.negate_in_place(); 354 | return other; 355 | } 356 | op_impl( 357 | &self, 358 | other, 359 | |coeff| -coeff, 360 | |cur_coeff, other_coeff| cur_coeff - other_coeff, 361 | ) 362 | } 363 | } 364 | 365 | impl Sub> for &LinearCombination { 366 | type Output = LinearCombination; 367 | 368 | fn sub(self, mut other: LinearCombination) -> LinearCombination { 369 | if self.0.is_empty() { 370 | other.negate_in_place(); 371 | return other; 372 | } else if other.0.is_empty() { 373 | return self.clone(); 374 | } 375 | 376 | op_impl( 377 | self, 378 | &other, 379 | |coeff| -coeff, 380 | |cur_coeff, other_coeff| cur_coeff - other_coeff, 381 | ) 382 | } 383 | } 384 | 385 | impl Sub> for LinearCombination { 386 | type Output = LinearCombination; 387 | 388 | fn sub(self, mut other: LinearCombination) -> LinearCombination { 389 | if other.0.is_empty() { 390 | return self; 391 | } else if self.0.is_empty() { 392 | other.negate_in_place(); 393 | return other; 394 | } 395 | op_impl( 396 | &self, 397 | &other, 398 | |coeff| -coeff, 399 | |cur_coeff, other_coeff| cur_coeff - other_coeff, 400 | ) 401 | } 402 | } 403 | 404 | impl Add<(F, &LinearCombination)> for &LinearCombination { 405 | type Output = LinearCombination; 406 | 407 | fn add(self, (mul_coeff, other): (F, &LinearCombination)) -> LinearCombination { 408 | if other.0.is_empty() { 409 | return self.clone(); 410 | } else if self.0.is_empty() { 411 | let mut other = other.clone(); 412 | other.mul_assign(mul_coeff); 413 | return other; 414 | } 415 | op_impl( 416 | self, 417 | other, 418 | |coeff| mul_coeff * coeff, 419 | |cur_coeff, other_coeff| cur_coeff + mul_coeff * other_coeff, 420 | ) 421 | } 422 | } 423 | 424 | impl<'a, F: Field> Add<(F, &'a LinearCombination)> for LinearCombination { 425 | type Output = LinearCombination; 426 | 427 | fn add(self, (mul_coeff, other): (F, &'a LinearCombination)) -> LinearCombination { 428 | if other.0.is_empty() { 429 | return self; 430 | } else if self.0.is_empty() { 431 | let mut other = other.clone(); 432 | other.mul_assign(mul_coeff); 433 | return other; 434 | } 435 | op_impl( 436 | &self, 437 | other, 438 | |coeff| mul_coeff * coeff, 439 | |cur_coeff, other_coeff| cur_coeff + mul_coeff * other_coeff, 440 | ) 441 | } 442 | } 443 | 444 | impl Add<(F, LinearCombination)> for &LinearCombination { 445 | type Output = LinearCombination; 446 | 447 | fn add(self, (mul_coeff, mut other): (F, LinearCombination)) -> LinearCombination { 448 | if other.0.is_empty() { 449 | return self.clone(); 450 | } else if self.0.is_empty() { 451 | other.mul_assign(mul_coeff); 452 | return other; 453 | } 454 | op_impl( 455 | self, 456 | &other, 457 | |coeff| mul_coeff * coeff, 458 | |cur_coeff, other_coeff| cur_coeff + mul_coeff * other_coeff, 459 | ) 460 | } 461 | } 462 | 463 | impl Add<(F, Self)> for LinearCombination { 464 | type Output = Self; 465 | 466 | fn add(self, (mul_coeff, other): (F, Self)) -> Self { 467 | if other.0.is_empty() { 468 | return self; 469 | } else if self.0.is_empty() { 470 | let mut other = other; 471 | other.mul_assign(mul_coeff); 472 | return other; 473 | } 474 | op_impl( 475 | &self, 476 | &other, 477 | |coeff| mul_coeff * coeff, 478 | |cur_coeff, other_coeff| cur_coeff + mul_coeff * other_coeff, 479 | ) 480 | } 481 | } 482 | 483 | impl Sub<(F, &LinearCombination)> for &LinearCombination { 484 | type Output = LinearCombination; 485 | 486 | fn sub(self, (coeff, other): (F, &LinearCombination)) -> LinearCombination { 487 | self + (-coeff, other) 488 | } 489 | } 490 | 491 | impl<'a, F: Field> Sub<(F, &'a LinearCombination)> for LinearCombination { 492 | type Output = LinearCombination; 493 | 494 | fn sub(self, (coeff, other): (F, &'a LinearCombination)) -> LinearCombination { 495 | self + (-coeff, other) 496 | } 497 | } 498 | 499 | impl Sub<(F, LinearCombination)> for &LinearCombination { 500 | type Output = LinearCombination; 501 | 502 | fn sub(self, (coeff, other): (F, LinearCombination)) -> LinearCombination { 503 | self + (-coeff, other) 504 | } 505 | } 506 | 507 | impl<'a, F: Field> Sub<(F, LinearCombination)> for LinearCombination { 508 | type Output = LinearCombination; 509 | 510 | fn sub(self, (coeff, other): (F, LinearCombination)) -> LinearCombination { 511 | self + (-coeff, other) 512 | } 513 | } 514 | -------------------------------------------------------------------------------- /relations/src/r1cs/constraint_system.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "std")] 2 | use crate::r1cs::ConstraintTrace; 3 | use crate::r1cs::{LcIndex, LinearCombination, Matrix, SynthesisError, Variable}; 4 | use ark_ff::Field; 5 | use ark_std::{ 6 | any::{Any, TypeId}, 7 | boxed::Box, 8 | cell::{Ref, RefCell, RefMut}, 9 | collections::BTreeMap, 10 | format, 11 | rc::Rc, 12 | string::String, 13 | vec, 14 | vec::Vec, 15 | }; 16 | 17 | /// Computations are expressed in terms of rank-1 constraint systems (R1CS). 18 | /// The `generate_constraints` method is called to generate constraints for 19 | /// both CRS generation and for proving. 20 | // TODO: Think: should we replace this with just a closure? 21 | pub trait ConstraintSynthesizer { 22 | /// Drives generation of new constraints inside `cs`. 23 | fn generate_constraints(self, cs: ConstraintSystemRef) -> crate::r1cs::Result<()>; 24 | } 25 | 26 | /// An Rank-One `ConstraintSystem`. Enforces constraints of the form 27 | /// `⟨a_i, z⟩ ⋅ ⟨b_i, z⟩ = ⟨c_i, z⟩`, where `a_i`, `b_i`, and `c_i` are linear 28 | /// combinations over variables, and `z` is the concrete assignment to these 29 | /// variables. 30 | #[derive(Debug, Clone)] 31 | pub struct ConstraintSystem { 32 | /// The mode in which the constraint system is operating. `self` can either 33 | /// be in setup mode (i.e., `self.mode == SynthesisMode::Setup`) or in 34 | /// proving mode (i.e., `self.mode == SynthesisMode::Prove`). If we are 35 | /// in proving mode, then we have the additional option of whether or 36 | /// not to construct the A, B, and C matrices of the constraint system 37 | /// (see below). 38 | pub mode: SynthesisMode, 39 | /// The number of variables that are "public inputs" to the constraint 40 | /// system. 41 | pub num_instance_variables: usize, 42 | /// The number of variables that are "private inputs" to the constraint 43 | /// system. 44 | pub num_witness_variables: usize, 45 | /// The number of constraints in the constraint system. 46 | pub num_constraints: usize, 47 | /// The number of linear combinations 48 | pub num_linear_combinations: usize, 49 | 50 | /// The parameter we aim to minimize in this constraint system (either the 51 | /// number of constraints or their total weight). 52 | pub optimization_goal: OptimizationGoal, 53 | 54 | /// Assignments to the public input variables. This is empty if `self.mode 55 | /// == SynthesisMode::Setup`. 56 | pub instance_assignment: Vec, 57 | /// Assignments to the private input variables. This is empty if `self.mode 58 | /// == SynthesisMode::Setup`. 59 | pub witness_assignment: Vec, 60 | 61 | /// Map for gadgets to cache computation results. 62 | pub cache_map: Rc>>>, 63 | 64 | lc_map: BTreeMap>, 65 | 66 | #[cfg(feature = "std")] 67 | constraint_traces: Vec>, 68 | 69 | a_constraints: Vec, 70 | b_constraints: Vec, 71 | c_constraints: Vec, 72 | 73 | lc_assignment_cache: Rc>>, 74 | } 75 | 76 | impl Default for ConstraintSystem { 77 | fn default() -> Self { 78 | Self::new() 79 | } 80 | } 81 | 82 | /// Defines the mode of operation of a `ConstraintSystem`. 83 | #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] 84 | pub enum SynthesisMode { 85 | /// Indicate to the `ConstraintSystem` that it should only generate 86 | /// constraint matrices and not populate the variable assignments. 87 | Setup, 88 | /// Indicate to the `ConstraintSystem` that it populate the variable 89 | /// assignments. If additionally `construct_matrices == true`, then generate 90 | /// the matrices as in the `Setup` case. 91 | Prove { 92 | /// If `construct_matrices == true`, then generate 93 | /// the matrices as in the `Setup` case. 94 | construct_matrices: bool, 95 | }, 96 | } 97 | 98 | /// Defines the parameter to optimize for a `ConstraintSystem`. 99 | #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] 100 | pub enum OptimizationGoal { 101 | /// Make no attempt to optimize. 102 | None, 103 | /// Minimize the number of constraints. 104 | Constraints, 105 | /// Minimize the total weight of the constraints (the number of nonzero 106 | /// entries across all constraints). 107 | Weight, 108 | } 109 | 110 | impl ConstraintSystem { 111 | #[inline] 112 | fn make_row(&self, l: &LinearCombination) -> Vec<(F, usize)> { 113 | let num_input = self.num_instance_variables; 114 | l.0.iter() 115 | .filter_map(|(coeff, var)| { 116 | if coeff.is_zero() { 117 | None 118 | } else { 119 | Some(( 120 | *coeff, 121 | var.get_index_unchecked(num_input).expect("no symbolic LCs"), 122 | )) 123 | } 124 | }) 125 | .collect() 126 | } 127 | 128 | /// Construct an empty `ConstraintSystem`. 129 | pub fn new() -> Self { 130 | Self { 131 | num_instance_variables: 1, 132 | num_witness_variables: 0, 133 | num_constraints: 0, 134 | num_linear_combinations: 0, 135 | a_constraints: Vec::new(), 136 | b_constraints: Vec::new(), 137 | c_constraints: Vec::new(), 138 | instance_assignment: vec![F::one()], 139 | witness_assignment: Vec::new(), 140 | cache_map: Rc::new(RefCell::new(BTreeMap::new())), 141 | #[cfg(feature = "std")] 142 | constraint_traces: Vec::new(), 143 | 144 | lc_map: BTreeMap::new(), 145 | lc_assignment_cache: Rc::new(RefCell::new(BTreeMap::new())), 146 | 147 | mode: SynthesisMode::Prove { 148 | construct_matrices: true, 149 | }, 150 | 151 | optimization_goal: OptimizationGoal::Constraints, 152 | } 153 | } 154 | 155 | /// Create a new `ConstraintSystemRef`. 156 | pub fn new_ref() -> ConstraintSystemRef { 157 | ConstraintSystemRef::new(Self::new()) 158 | } 159 | 160 | /// Set `self.mode` to `mode`. 161 | pub fn set_mode(&mut self, mode: SynthesisMode) { 162 | self.mode = mode; 163 | } 164 | 165 | /// Check whether `self.mode == SynthesisMode::Setup`. 166 | pub fn is_in_setup_mode(&self) -> bool { 167 | self.mode == SynthesisMode::Setup 168 | } 169 | 170 | /// Check whether this constraint system aims to optimize weight, 171 | /// number of constraints, or neither. 172 | pub fn optimization_goal(&self) -> OptimizationGoal { 173 | self.optimization_goal 174 | } 175 | 176 | /// Specify whether this constraint system should aim to optimize weight, 177 | /// number of constraints, or neither. 178 | pub fn set_optimization_goal(&mut self, goal: OptimizationGoal) { 179 | // `set_optimization_goal` should only be executed before any constraint or value is created. 180 | assert_eq!(self.num_instance_variables, 1); 181 | assert_eq!(self.num_witness_variables, 0); 182 | assert_eq!(self.num_constraints, 0); 183 | assert_eq!(self.num_linear_combinations, 0); 184 | 185 | self.optimization_goal = goal; 186 | } 187 | 188 | /// Check whether or not `self` will construct matrices. 189 | pub fn should_construct_matrices(&self) -> bool { 190 | match self.mode { 191 | SynthesisMode::Setup => true, 192 | SynthesisMode::Prove { construct_matrices } => construct_matrices, 193 | } 194 | } 195 | 196 | /// Return a variable representing the constant "zero" inside the constraint 197 | /// system. 198 | #[inline] 199 | pub fn zero() -> Variable { 200 | Variable::Zero 201 | } 202 | 203 | /// Return a variable representing the constant "one" inside the constraint 204 | /// system. 205 | #[inline] 206 | pub fn one() -> Variable { 207 | Variable::One 208 | } 209 | 210 | /// Obtain a variable representing a new public instance input. 211 | #[inline] 212 | pub fn new_input_variable(&mut self, f: Func) -> crate::r1cs::Result 213 | where 214 | Func: FnOnce() -> crate::r1cs::Result, 215 | { 216 | let index = self.num_instance_variables; 217 | self.num_instance_variables += 1; 218 | 219 | if !self.is_in_setup_mode() { 220 | self.instance_assignment.push(f()?); 221 | } 222 | Ok(Variable::Instance(index)) 223 | } 224 | 225 | /// Obtain a variable representing a new private witness input. 226 | #[inline] 227 | pub fn new_witness_variable(&mut self, f: Func) -> crate::r1cs::Result 228 | where 229 | Func: FnOnce() -> crate::r1cs::Result, 230 | { 231 | let index = self.num_witness_variables; 232 | self.num_witness_variables += 1; 233 | 234 | if !self.is_in_setup_mode() { 235 | self.witness_assignment.push(f()?); 236 | } 237 | Ok(Variable::Witness(index)) 238 | } 239 | 240 | /// Obtain a variable representing a linear combination. 241 | #[inline] 242 | pub fn new_lc(&mut self, lc: LinearCombination) -> crate::r1cs::Result { 243 | let index = LcIndex(self.num_linear_combinations); 244 | let var = Variable::SymbolicLc(index); 245 | 246 | self.lc_map.insert(index, lc); 247 | 248 | self.num_linear_combinations += 1; 249 | Ok(var) 250 | } 251 | 252 | /// Enforce a R1CS constraint with the name `name`. 253 | #[inline] 254 | pub fn enforce_constraint( 255 | &mut self, 256 | a: LinearCombination, 257 | b: LinearCombination, 258 | c: LinearCombination, 259 | ) -> crate::r1cs::Result<()> { 260 | if self.should_construct_matrices() { 261 | let a_index = self.new_lc(a)?.get_lc_index().unwrap(); 262 | let b_index = self.new_lc(b)?.get_lc_index().unwrap(); 263 | let c_index = self.new_lc(c)?.get_lc_index().unwrap(); 264 | self.a_constraints.push(a_index); 265 | self.b_constraints.push(b_index); 266 | self.c_constraints.push(c_index); 267 | } 268 | self.num_constraints += 1; 269 | #[cfg(feature = "std")] 270 | { 271 | let trace = ConstraintTrace::capture(); 272 | self.constraint_traces.push(trace); 273 | } 274 | Ok(()) 275 | } 276 | 277 | /// Count the number of times each LC is used within other LCs in the 278 | /// constraint system 279 | fn lc_num_times_used(&self, count_sinks: bool) -> Vec { 280 | let mut num_times_used = vec![0; self.lc_map.len()]; 281 | 282 | // Iterate over every lc in constraint system 283 | for (index, lc) in self.lc_map.iter() { 284 | num_times_used[index.0] += count_sinks as usize; 285 | 286 | // Increment the counter for each lc that this lc has a direct dependency on. 287 | for &(_, var) in lc.iter() { 288 | if var.is_lc() { 289 | let lc_index = var.get_lc_index().expect("should be lc"); 290 | num_times_used[lc_index.0] += 1; 291 | } 292 | } 293 | } 294 | num_times_used 295 | } 296 | 297 | /// Transform the map of linear combinations. 298 | /// Specifically, allow the creation of additional witness assignments. 299 | /// 300 | /// This method is used as a subroutine of `inline_all_lcs` and `outline_lcs`. 301 | /// 302 | /// The transformer function is given a references of this constraint system (&self), 303 | /// number of times used, and a mutable reference of the linear combination to be transformed. 304 | /// (&ConstraintSystem, usize, &mut LinearCombination) 305 | /// 306 | /// The transformer function returns the number of new witness variables needed 307 | /// and a vector of new witness assignments (if not in the setup mode). 308 | /// (usize, Option>) 309 | pub fn transform_lc_map( 310 | &mut self, 311 | transformer: &mut dyn FnMut( 312 | &ConstraintSystem, 313 | usize, 314 | &mut LinearCombination, 315 | ) -> (usize, Option>), 316 | ) { 317 | // `transformed_lc_map` stores the transformed linear combinations. 318 | let mut transformed_lc_map = BTreeMap::<_, LinearCombination>::new(); 319 | let mut num_times_used = self.lc_num_times_used(false); 320 | 321 | // This loop goes through all the LCs in the map, starting from 322 | // the early ones. The transformer function is applied to the 323 | // inlined LC, where new witness variables can be created. 324 | for (&index, lc) in &self.lc_map { 325 | let mut transformed_lc = LinearCombination::new(); 326 | 327 | // Inline the LC, unwrapping symbolic LCs that may constitute it, 328 | // and updating them according to transformations in prior iterations. 329 | for &(coeff, var) in lc.iter() { 330 | if var.is_lc() { 331 | let lc_index = var.get_lc_index().expect("should be lc"); 332 | 333 | // If `var` is a `SymbolicLc`, fetch the corresponding 334 | // inlined LC, and substitute it in. 335 | // 336 | // We have the guarantee that `lc_index` must exist in 337 | // `new_lc_map` since a LC can only depend on other 338 | // LCs with lower indices, which we have transformed. 339 | // 340 | let lc = transformed_lc_map 341 | .get(&lc_index) 342 | .expect("should be inlined"); 343 | transformed_lc.extend((lc * coeff).0.into_iter()); 344 | 345 | // Delete linear combinations that are no longer used. 346 | // 347 | // Deletion is safe for both outlining and inlining: 348 | // * Inlining: the LC is substituted directly into all use sites, and so once it 349 | // is fully inlined, it is redundant. 350 | // 351 | // * Outlining: the LC is associated with a new variable `w`, and a new 352 | // constraint of the form `lc_data * 1 = w`, where `lc_data` is the actual 353 | // data in the linear combination. Furthermore, we replace its entry in 354 | // `new_lc_map` with `(1, w)`. Once `w` is fully inlined, then we can delete 355 | // the entry from `new_lc_map` 356 | // 357 | num_times_used[lc_index.0] -= 1; 358 | if num_times_used[lc_index.0] == 0 { 359 | // This lc is not used any more, so remove it. 360 | transformed_lc_map.remove(&lc_index); 361 | } 362 | } else { 363 | // Otherwise, it's a concrete variable and so we 364 | // substitute it in directly. 365 | transformed_lc.push((coeff, var)); 366 | } 367 | } 368 | transformed_lc.compactify(); 369 | 370 | // Call the transformer function. 371 | let (num_new_witness_variables, new_witness_assignments) = 372 | transformer(&self, num_times_used[index.0], &mut transformed_lc); 373 | 374 | // Insert the transformed LC. 375 | transformed_lc_map.insert(index, transformed_lc); 376 | 377 | // Update the witness counter. 378 | self.num_witness_variables += num_new_witness_variables; 379 | 380 | // Supply additional witness assignments if not in the 381 | // setup mode and if new witness variables are created. 382 | if !self.is_in_setup_mode() && num_new_witness_variables > 0 { 383 | assert!(new_witness_assignments.is_some()); 384 | if let Some(new_witness_assignments) = new_witness_assignments { 385 | assert_eq!(new_witness_assignments.len(), num_new_witness_variables); 386 | self.witness_assignment 387 | .extend_from_slice(&new_witness_assignments); 388 | } 389 | } 390 | } 391 | // Replace the LC map. 392 | self.lc_map = transformed_lc_map; 393 | } 394 | 395 | /// Naively inlines symbolic linear combinations into the linear 396 | /// combinations that use them. 397 | /// 398 | /// Useful for standard pairing-based SNARKs where addition gates are cheap. 399 | /// For example, in the SNARKs such as [\[Groth16\]](https://eprint.iacr.org/2016/260) and 400 | /// [\[Groth-Maller17\]](https://eprint.iacr.org/2017/540), addition gates 401 | /// do not contribute to the size of the multi-scalar multiplication, which 402 | /// is the dominating cost. 403 | pub fn inline_all_lcs(&mut self) { 404 | // Only inline when a matrix representing R1CS is needed. 405 | if !self.should_construct_matrices() { 406 | return; 407 | } 408 | 409 | // A dummy closure is used, which means that 410 | // - it does not modify the inlined LC. 411 | // - it does not add new witness variables. 412 | self.transform_lc_map(&mut |_, _, _| (0, None)); 413 | } 414 | 415 | /// If a `SymbolicLc` is used in more than one location and has sufficient 416 | /// length, this method makes a new variable for that `SymbolicLc`, adds 417 | /// a constraint ensuring the equality of the variable and the linear 418 | /// combination, and then uses that variable in every location the 419 | /// `SymbolicLc` is used. 420 | /// 421 | /// Useful for SNARKs like [\[Marlin\]](https://eprint.iacr.org/2019/1047) or 422 | /// [\[Fractal\]](https://eprint.iacr.org/2019/1076), where addition gates 423 | /// are not cheap. 424 | fn outline_lcs(&mut self) { 425 | // Only inline when a matrix representing R1CS is needed. 426 | if !self.should_construct_matrices() { 427 | return; 428 | } 429 | 430 | // Store information about new witness variables created 431 | // for outlining. New constraints will be added after the 432 | // transformation of the LC map. 433 | let mut new_witness_linear_combinations = Vec::new(); 434 | let mut new_witness_indices = Vec::new(); 435 | 436 | // It goes through all the LCs in the map, starting from 437 | // the early ones, and decides whether or not to dedicate a witness 438 | // variable for this LC. 439 | // 440 | // If true, the LC is replaced with 1 * this witness variable. 441 | // Otherwise, the LC is inlined. 442 | // 443 | // Each iteration first updates the LC according to outlinings in prior 444 | // iterations, and then sees if it should be outlined, and if so adds 445 | // the outlining to the map. 446 | // 447 | self.transform_lc_map(&mut |cs, num_times_used, inlined_lc| { 448 | let mut should_dedicate_a_witness_variable = false; 449 | let mut new_witness_index = None; 450 | let mut new_witness_assignment = Vec::new(); 451 | 452 | // Check if it is worthwhile to dedicate a witness variable. 453 | let this_used_times = num_times_used + 1; 454 | let this_len = inlined_lc.len(); 455 | 456 | // Cost with no outlining = `lc_len * number of usages` 457 | // Cost with outlining is one constraint for `(lc_len) * 1 = {new variable}` and 458 | // using that single new variable in each of the prior usages. 459 | // This has total cost `number_of_usages + lc_len + 2` 460 | if this_used_times * this_len > this_used_times + 2 + this_len { 461 | should_dedicate_a_witness_variable = true; 462 | } 463 | 464 | // If it is worthwhile to dedicate a witness variable, 465 | if should_dedicate_a_witness_variable { 466 | // Add a new witness (the value of the linear combination). 467 | // This part follows the same logic of `new_witness_variable`. 468 | let witness_index = cs.num_witness_variables; 469 | new_witness_index = Some(witness_index); 470 | 471 | // Compute the witness assignment. 472 | if !cs.is_in_setup_mode() { 473 | let mut acc = F::zero(); 474 | for (coeff, var) in inlined_lc.iter() { 475 | acc += *coeff * &cs.assigned_value(*var).unwrap(); 476 | } 477 | new_witness_assignment.push(acc); 478 | } 479 | 480 | // Add a new constraint for this new witness. 481 | new_witness_linear_combinations.push(inlined_lc.clone()); 482 | new_witness_indices.push(witness_index); 483 | 484 | // Replace the linear combination with (1 * this new witness). 485 | *inlined_lc = LinearCombination::from(Variable::Witness(witness_index)); 486 | } 487 | // Otherwise, the LC remains unchanged. 488 | 489 | // Return information about new witness variables. 490 | if new_witness_index.is_some() { 491 | (1, Some(new_witness_assignment)) 492 | } else { 493 | (0, None) 494 | } 495 | }); 496 | 497 | // Add the constraints for the newly added witness variables. 498 | for (new_witness_linear_combination, new_witness_variable) in 499 | new_witness_linear_combinations 500 | .iter() 501 | .zip(new_witness_indices.iter()) 502 | { 503 | // Add a new constraint 504 | self.enforce_constraint( 505 | new_witness_linear_combination.clone(), 506 | LinearCombination::from(Self::one()), 507 | LinearCombination::from(Variable::Witness(*new_witness_variable)), 508 | ) 509 | .unwrap(); 510 | } 511 | } 512 | 513 | /// Finalize the constraint system (either by outlining or inlining, 514 | /// if an optimization goal is set). 515 | pub fn finalize(&mut self) { 516 | match self.optimization_goal { 517 | OptimizationGoal::None => self.inline_all_lcs(), 518 | OptimizationGoal::Constraints => self.inline_all_lcs(), 519 | OptimizationGoal::Weight => self.outline_lcs(), 520 | }; 521 | } 522 | 523 | /// This step must be called after constraint generation has completed, and 524 | /// after all symbolic LCs have been inlined into the places that they 525 | /// are used. 526 | pub fn to_matrices(&self) -> Option> { 527 | if let SynthesisMode::Prove { 528 | construct_matrices: false, 529 | } = self.mode 530 | { 531 | None 532 | } else { 533 | let a: Vec<_> = self 534 | .a_constraints 535 | .iter() 536 | .map(|index| self.make_row(self.lc_map.get(index).unwrap())) 537 | .collect(); 538 | let b: Vec<_> = self 539 | .b_constraints 540 | .iter() 541 | .map(|index| self.make_row(self.lc_map.get(index).unwrap())) 542 | .collect(); 543 | let c: Vec<_> = self 544 | .c_constraints 545 | .iter() 546 | .map(|index| self.make_row(self.lc_map.get(index).unwrap())) 547 | .collect(); 548 | 549 | let a_num_non_zero: usize = a.iter().map(|lc| lc.len()).sum(); 550 | let b_num_non_zero: usize = b.iter().map(|lc| lc.len()).sum(); 551 | let c_num_non_zero: usize = c.iter().map(|lc| lc.len()).sum(); 552 | let matrices = ConstraintMatrices { 553 | num_instance_variables: self.num_instance_variables, 554 | num_witness_variables: self.num_witness_variables, 555 | num_constraints: self.num_constraints, 556 | 557 | a_num_non_zero, 558 | b_num_non_zero, 559 | c_num_non_zero, 560 | 561 | a, 562 | b, 563 | c, 564 | }; 565 | Some(matrices) 566 | } 567 | } 568 | 569 | fn eval_lc(&self, lc: LcIndex) -> Option { 570 | let lc = self.lc_map.get(&lc)?; 571 | let mut acc = F::zero(); 572 | for (coeff, var) in lc.iter() { 573 | acc += *coeff * self.assigned_value(*var)?; 574 | } 575 | Some(acc) 576 | } 577 | 578 | /// If `self` is satisfied, outputs `Ok(true)`. 579 | /// If `self` is unsatisfied, outputs `Ok(false)`. 580 | /// If `self.is_in_setup_mode()`, outputs `Err(())`. 581 | pub fn is_satisfied(&self) -> crate::r1cs::Result { 582 | self.which_is_unsatisfied().map(|s| s.is_none()) 583 | } 584 | 585 | /// If `self` is satisfied, outputs `Ok(None)`. 586 | /// If `self` is unsatisfied, outputs `Some(i)`, where `i` is the index of 587 | /// the first unsatisfied constraint. If `self.is_in_setup_mode()`, outputs 588 | /// `Err(())`. 589 | pub fn which_is_unsatisfied(&self) -> crate::r1cs::Result> { 590 | if self.is_in_setup_mode() { 591 | Err(SynthesisError::AssignmentMissing) 592 | } else { 593 | for i in 0..self.num_constraints { 594 | let a = self 595 | .eval_lc(self.a_constraints[i]) 596 | .ok_or(SynthesisError::AssignmentMissing)?; 597 | let b = self 598 | .eval_lc(self.b_constraints[i]) 599 | .ok_or(SynthesisError::AssignmentMissing)?; 600 | let c = self 601 | .eval_lc(self.c_constraints[i]) 602 | .ok_or(SynthesisError::AssignmentMissing)?; 603 | if a * b != c { 604 | let trace; 605 | #[cfg(feature = "std")] 606 | { 607 | trace = self.constraint_traces[i].as_ref().map_or_else( 608 | || { 609 | eprintln!("Constraint trace requires enabling `ConstraintLayer`"); 610 | format!("{}", i) 611 | }, 612 | |t| format!("{}", t), 613 | ); 614 | } 615 | #[cfg(not(feature = "std"))] 616 | { 617 | trace = format!("{}", i); 618 | } 619 | return Ok(Some(trace)); 620 | } 621 | } 622 | Ok(None) 623 | } 624 | } 625 | 626 | /// Obtain the assignment corresponding to the `Variable` `v`. 627 | pub fn assigned_value(&self, v: Variable) -> Option { 628 | match v { 629 | Variable::One => Some(F::one()), 630 | Variable::Zero => Some(F::zero()), 631 | Variable::Witness(idx) => self.witness_assignment.get(idx).copied(), 632 | Variable::Instance(idx) => self.instance_assignment.get(idx).copied(), 633 | Variable::SymbolicLc(idx) => { 634 | let value = self.lc_assignment_cache.borrow().get(&idx).copied(); 635 | if value.is_some() { 636 | value 637 | } else { 638 | let value = self.eval_lc(idx)?; 639 | self.lc_assignment_cache.borrow_mut().insert(idx, value); 640 | Some(value) 641 | } 642 | }, 643 | } 644 | } 645 | } 646 | /// The A, B and C matrices of a Rank-One `ConstraintSystem`. 647 | /// Also contains metadata on the structure of the constraint system 648 | /// and the matrices. 649 | #[derive(Debug, Clone, PartialEq, Eq)] 650 | pub struct ConstraintMatrices { 651 | /// The number of variables that are "public instances" to the constraint 652 | /// system. 653 | pub num_instance_variables: usize, 654 | /// The number of variables that are "private witnesses" to the constraint 655 | /// system. 656 | pub num_witness_variables: usize, 657 | /// The number of constraints in the constraint system. 658 | pub num_constraints: usize, 659 | /// The number of non_zero entries in the A matrix. 660 | pub a_num_non_zero: usize, 661 | /// The number of non_zero entries in the B matrix. 662 | pub b_num_non_zero: usize, 663 | /// The number of non_zero entries in the C matrix. 664 | pub c_num_non_zero: usize, 665 | 666 | /// The A constraint matrix. This is empty when 667 | /// `self.mode == SynthesisMode::Prove { construct_matrices = false }`. 668 | pub a: Matrix, 669 | /// The B constraint matrix. This is empty when 670 | /// `self.mode == SynthesisMode::Prove { construct_matrices = false }`. 671 | pub b: Matrix, 672 | /// The C constraint matrix. This is empty when 673 | /// `self.mode == SynthesisMode::Prove { construct_matrices = false }`. 674 | pub c: Matrix, 675 | } 676 | 677 | /// A shared reference to a constraint system that can be stored in high level 678 | /// variables. 679 | #[derive(Debug, Clone)] 680 | pub enum ConstraintSystemRef { 681 | /// Represents the case where we *don't* need to allocate variables or 682 | /// enforce constraints. Encountered when operating over constant 683 | /// values. 684 | None, 685 | /// Represents the case where we *do* allocate variables or enforce 686 | /// constraints. 687 | CS(Rc>>), 688 | } 689 | 690 | impl PartialEq for ConstraintSystemRef { 691 | fn eq(&self, other: &Self) -> bool { 692 | match (self, other) { 693 | (Self::None, Self::None) => true, 694 | (..) => false, 695 | } 696 | } 697 | } 698 | 699 | impl Eq for ConstraintSystemRef {} 700 | 701 | /// A namespaced `ConstraintSystemRef`. 702 | #[derive(Debug, Clone)] 703 | pub struct Namespace { 704 | inner: ConstraintSystemRef, 705 | id: Option, 706 | } 707 | 708 | impl From> for Namespace { 709 | fn from(other: ConstraintSystemRef) -> Self { 710 | Self { 711 | inner: other, 712 | id: None, 713 | } 714 | } 715 | } 716 | 717 | impl Namespace { 718 | /// Construct a new `Namespace`. 719 | pub fn new(inner: ConstraintSystemRef, id: Option) -> Self { 720 | Self { inner, id } 721 | } 722 | 723 | /// Obtain the inner `ConstraintSystemRef`. 724 | pub fn cs(&self) -> ConstraintSystemRef { 725 | self.inner.clone() 726 | } 727 | 728 | /// Manually leave the namespace. 729 | pub fn leave_namespace(self) { 730 | drop(self) 731 | } 732 | } 733 | 734 | impl Drop for Namespace { 735 | fn drop(&mut self) { 736 | if let Some(id) = self.id.as_ref() { 737 | tracing::dispatcher::get_default(|dispatch| dispatch.exit(id)) 738 | } 739 | let _ = self.inner; 740 | } 741 | } 742 | 743 | impl ConstraintSystemRef { 744 | /// Returns `self` if `!self.is_none()`, otherwise returns `other`. 745 | pub fn or(self, other: Self) -> Self { 746 | match self { 747 | ConstraintSystemRef::None => other, 748 | _ => self, 749 | } 750 | } 751 | 752 | /// Returns `true` is `self == ConstraintSystemRef::None`. 753 | pub fn is_none(&self) -> bool { 754 | matches!(self, ConstraintSystemRef::None) 755 | } 756 | 757 | /// Construct a `ConstraintSystemRef` from a `ConstraintSystem`. 758 | #[inline] 759 | pub fn new(inner: ConstraintSystem) -> Self { 760 | Self::CS(Rc::new(RefCell::new(inner))) 761 | } 762 | 763 | fn inner(&self) -> Option<&Rc>>> { 764 | match self { 765 | Self::CS(a) => Some(a), 766 | Self::None => None, 767 | } 768 | } 769 | 770 | /// Consumes self to return the inner `ConstraintSystem`. Returns 771 | /// `None` if `Self::CS` is `None` or if any other references to 772 | /// `Self::CS` exist. 773 | pub fn into_inner(self) -> Option> { 774 | match self { 775 | Self::CS(a) => Rc::try_unwrap(a).ok().map(|s| s.into_inner()), 776 | Self::None => None, 777 | } 778 | } 779 | 780 | /// Obtain an immutable reference to the underlying `ConstraintSystem`. 781 | /// 782 | /// # Panics 783 | /// This method panics if `self` is already mutably borrowed. 784 | #[inline] 785 | pub fn borrow(&self) -> Option>> { 786 | self.inner().map(|cs| cs.borrow()) 787 | } 788 | 789 | /// Obtain a mutable reference to the underlying `ConstraintSystem`. 790 | /// 791 | /// # Panics 792 | /// This method panics if `self` is already mutably borrowed. 793 | #[inline] 794 | pub fn borrow_mut(&self) -> Option>> { 795 | self.inner().map(|cs| cs.borrow_mut()) 796 | } 797 | 798 | /// Set `self.mode` to `mode`. 799 | pub fn set_mode(&self, mode: SynthesisMode) { 800 | self.inner().map_or((), |cs| cs.borrow_mut().set_mode(mode)) 801 | } 802 | 803 | /// Check whether `self.mode == SynthesisMode::Setup`. 804 | #[inline] 805 | pub fn is_in_setup_mode(&self) -> bool { 806 | self.inner() 807 | .map_or(false, |cs| cs.borrow().is_in_setup_mode()) 808 | } 809 | 810 | /// Returns the number of constraints. 811 | #[inline] 812 | pub fn num_constraints(&self) -> usize { 813 | self.inner().map_or(0, |cs| cs.borrow().num_constraints) 814 | } 815 | 816 | /// Returns the number of instance variables. 817 | #[inline] 818 | pub fn num_instance_variables(&self) -> usize { 819 | self.inner() 820 | .map_or(0, |cs| cs.borrow().num_instance_variables) 821 | } 822 | 823 | /// Returns the number of witness variables. 824 | #[inline] 825 | pub fn num_witness_variables(&self) -> usize { 826 | self.inner() 827 | .map_or(0, |cs| cs.borrow().num_witness_variables) 828 | } 829 | 830 | /// Check whether this constraint system aims to optimize weight, 831 | /// number of constraints, or neither. 832 | #[inline] 833 | pub fn optimization_goal(&self) -> OptimizationGoal { 834 | self.inner().map_or(OptimizationGoal::Constraints, |cs| { 835 | cs.borrow().optimization_goal() 836 | }) 837 | } 838 | 839 | /// Specify whether this constraint system should aim to optimize weight, 840 | /// number of constraints, or neither. 841 | #[inline] 842 | pub fn set_optimization_goal(&self, goal: OptimizationGoal) { 843 | self.inner() 844 | .map_or((), |cs| cs.borrow_mut().set_optimization_goal(goal)) 845 | } 846 | 847 | /// Check whether or not `self` will construct matrices. 848 | #[inline] 849 | pub fn should_construct_matrices(&self) -> bool { 850 | self.inner() 851 | .map_or(false, |cs| cs.borrow().should_construct_matrices()) 852 | } 853 | 854 | /// Obtain a variable representing a new public instance input. 855 | #[inline] 856 | pub fn new_input_variable(&self, f: Func) -> crate::r1cs::Result 857 | where 858 | Func: FnOnce() -> crate::r1cs::Result, 859 | { 860 | self.inner() 861 | .ok_or(SynthesisError::MissingCS) 862 | .and_then(|cs| { 863 | if !self.is_in_setup_mode() { 864 | // This is needed to avoid double-borrows, because `f` 865 | // might itself mutably borrow `cs` (eg: `f = || g.value()`). 866 | let value = f(); 867 | cs.borrow_mut().new_input_variable(|| value) 868 | } else { 869 | cs.borrow_mut().new_input_variable(f) 870 | } 871 | }) 872 | } 873 | 874 | /// Obtain a variable representing a new private witness input. 875 | #[inline] 876 | pub fn new_witness_variable(&self, f: Func) -> crate::r1cs::Result 877 | where 878 | Func: FnOnce() -> crate::r1cs::Result, 879 | { 880 | self.inner() 881 | .ok_or(SynthesisError::MissingCS) 882 | .and_then(|cs| { 883 | if !self.is_in_setup_mode() { 884 | // This is needed to avoid double-borrows, because `f` 885 | // might itself mutably borrow `cs` (eg: `f = || g.value()`). 886 | let value = f(); 887 | cs.borrow_mut().new_witness_variable(|| value) 888 | } else { 889 | cs.borrow_mut().new_witness_variable(f) 890 | } 891 | }) 892 | } 893 | 894 | /// Obtain a variable representing a linear combination. 895 | #[inline] 896 | pub fn new_lc(&self, lc: LinearCombination) -> crate::r1cs::Result { 897 | self.inner() 898 | .ok_or(SynthesisError::MissingCS) 899 | .and_then(|cs| cs.borrow_mut().new_lc(lc)) 900 | } 901 | 902 | /// Enforce a R1CS constraint with the name `name`. 903 | #[inline] 904 | pub fn enforce_constraint( 905 | &self, 906 | a: LinearCombination, 907 | b: LinearCombination, 908 | c: LinearCombination, 909 | ) -> crate::r1cs::Result<()> { 910 | self.inner() 911 | .ok_or(SynthesisError::MissingCS) 912 | .and_then(|cs| cs.borrow_mut().enforce_constraint(a, b, c)) 913 | } 914 | 915 | /// Naively inlines symbolic linear combinations into the linear 916 | /// combinations that use them. 917 | /// 918 | /// Useful for standard pairing-based SNARKs where addition gates are cheap. 919 | /// For example, in the SNARKs such as [\[Groth16\]](https://eprint.iacr.org/2016/260) and 920 | /// [\[Groth-Maller17\]](https://eprint.iacr.org/2017/540), addition gates 921 | /// do not contribute to the size of the multi-scalar multiplication, which 922 | /// is the dominating cost. 923 | pub fn inline_all_lcs(&self) { 924 | if let Some(cs) = self.inner() { 925 | cs.borrow_mut().inline_all_lcs() 926 | } 927 | } 928 | 929 | /// Finalize the constraint system (either by outlining or inlining, 930 | /// if an optimization goal is set). 931 | pub fn finalize(&self) { 932 | if let Some(cs) = self.inner() { 933 | cs.borrow_mut().finalize() 934 | } 935 | } 936 | 937 | /// This step must be called after constraint generation has completed, and 938 | /// after all symbolic LCs have been inlined into the places that they 939 | /// are used. 940 | #[inline] 941 | pub fn to_matrices(&self) -> Option> { 942 | self.inner().and_then(|cs| cs.borrow().to_matrices()) 943 | } 944 | 945 | /// If `self` is satisfied, outputs `Ok(true)`. 946 | /// If `self` is unsatisfied, outputs `Ok(false)`. 947 | /// If `self.is_in_setup_mode()` or if `self == None`, outputs `Err(())`. 948 | pub fn is_satisfied(&self) -> crate::r1cs::Result { 949 | self.inner() 950 | .map_or(Err(SynthesisError::AssignmentMissing), |cs| { 951 | cs.borrow().is_satisfied() 952 | }) 953 | } 954 | 955 | /// If `self` is satisfied, outputs `Ok(None)`. 956 | /// If `self` is unsatisfied, outputs `Some(i)`, where `i` is the index of 957 | /// the first unsatisfied constraint. 958 | /// If `self.is_in_setup_mode()` or `self == None`, outputs `Err(())`. 959 | pub fn which_is_unsatisfied(&self) -> crate::r1cs::Result> { 960 | self.inner() 961 | .map_or(Err(SynthesisError::AssignmentMissing), |cs| { 962 | cs.borrow().which_is_unsatisfied() 963 | }) 964 | } 965 | 966 | /// Obtain the assignment corresponding to the `Variable` `v`. 967 | pub fn assigned_value(&self, v: Variable) -> Option { 968 | self.inner().and_then(|cs| cs.borrow().assigned_value(v)) 969 | } 970 | 971 | /// Get trace information about all constraints in the system 972 | pub fn constraint_names(&self) -> Option> { 973 | #[cfg(feature = "std")] 974 | { 975 | self.inner().and_then(|cs| { 976 | cs.borrow() 977 | .constraint_traces 978 | .iter() 979 | .map(|trace| { 980 | let mut constraint_path = String::new(); 981 | let mut prev_module_path = ""; 982 | let mut prefixes = ark_std::collections::BTreeSet::new(); 983 | for step in trace.as_ref()?.path() { 984 | let module_path = if prev_module_path == step.module_path { 985 | prefixes.insert(step.module_path.to_string()); 986 | String::new() 987 | } else { 988 | let mut parts = step 989 | .module_path 990 | .split("::") 991 | .filter(|&part| part != "r1cs_std" && part != "constraints"); 992 | let mut path_so_far = String::new(); 993 | for part in parts.by_ref() { 994 | if path_so_far.is_empty() { 995 | path_so_far += part; 996 | } else { 997 | path_so_far += &["::", part].join(""); 998 | } 999 | if prefixes.contains(&path_so_far) { 1000 | continue; 1001 | } else { 1002 | prefixes.insert(path_so_far.clone()); 1003 | break; 1004 | } 1005 | } 1006 | parts.collect::>().join("::") + "::" 1007 | }; 1008 | prev_module_path = step.module_path; 1009 | constraint_path += &["/", &module_path, step.name].join(""); 1010 | } 1011 | Some(constraint_path) 1012 | }) 1013 | .collect::>>() 1014 | }) 1015 | } 1016 | #[cfg(not(feature = "std"))] 1017 | { 1018 | None 1019 | } 1020 | } 1021 | } 1022 | 1023 | #[cfg(test)] 1024 | mod tests { 1025 | use crate::r1cs::*; 1026 | use ark_ff::One; 1027 | use ark_test_curves::bls12_381::Fr; 1028 | 1029 | #[test] 1030 | fn matrix_generation() -> crate::r1cs::Result<()> { 1031 | let cs = ConstraintSystem::::new_ref(); 1032 | let two = Fr::one() + Fr::one(); 1033 | let a = cs.new_input_variable(|| Ok(Fr::one()))?; 1034 | let b = cs.new_witness_variable(|| Ok(Fr::one()))?; 1035 | let c = cs.new_witness_variable(|| Ok(two))?; 1036 | cs.enforce_constraint(lc!() + a, lc!() + (two, b), lc!() + c)?; 1037 | let d = cs.new_lc(lc!() + a + b)?; 1038 | cs.enforce_constraint(lc!() + a, lc!() + d, lc!() + d)?; 1039 | let e = cs.new_lc(lc!() + d + d)?; 1040 | cs.enforce_constraint(lc!() + Variable::One, lc!() + e, lc!() + e)?; 1041 | cs.inline_all_lcs(); 1042 | let matrices = cs.to_matrices().unwrap(); 1043 | assert_eq!(matrices.a[0], vec![(Fr::one(), 1)]); 1044 | assert_eq!(matrices.b[0], vec![(two, 2)]); 1045 | assert_eq!(matrices.c[0], vec![(Fr::one(), 3)]); 1046 | 1047 | assert_eq!(matrices.a[1], vec![(Fr::one(), 1)]); 1048 | assert_eq!(matrices.b[1], vec![(Fr::one(), 1), (Fr::one(), 2)]); 1049 | assert_eq!(matrices.c[1], vec![(Fr::one(), 1), (Fr::one(), 2)]); 1050 | 1051 | assert_eq!(matrices.a[2], vec![(Fr::one(), 0)]); 1052 | assert_eq!(matrices.b[2], vec![(two, 1), (two, 2)]); 1053 | assert_eq!(matrices.c[2], vec![(two, 1), (two, 2)]); 1054 | Ok(()) 1055 | } 1056 | 1057 | #[test] 1058 | fn matrix_generation_outlined() -> crate::r1cs::Result<()> { 1059 | let cs = ConstraintSystem::::new_ref(); 1060 | cs.set_optimization_goal(OptimizationGoal::Weight); 1061 | let two = Fr::one() + Fr::one(); 1062 | let a = cs.new_input_variable(|| Ok(Fr::one()))?; 1063 | let b = cs.new_witness_variable(|| Ok(Fr::one()))?; 1064 | let c = cs.new_witness_variable(|| Ok(two))?; 1065 | cs.enforce_constraint(lc!() + a, lc!() + (two, b), lc!() + c)?; 1066 | 1067 | let d = cs.new_lc(lc!() + a + b)?; 1068 | cs.enforce_constraint(lc!() + a, lc!() + d, lc!() + d)?; 1069 | 1070 | let e = cs.new_lc(lc!() + d + d)?; 1071 | cs.enforce_constraint(lc!() + Variable::One, lc!() + e, lc!() + e)?; 1072 | 1073 | cs.finalize(); 1074 | assert!(cs.is_satisfied().unwrap()); 1075 | let matrices = cs.to_matrices().unwrap(); 1076 | assert_eq!(matrices.a[0], vec![(Fr::one(), 1)]); 1077 | assert_eq!(matrices.b[0], vec![(two, 2)]); 1078 | assert_eq!(matrices.c[0], vec![(Fr::one(), 3)]); 1079 | 1080 | assert_eq!(matrices.a[1], vec![(Fr::one(), 1)]); 1081 | // Notice here how the variable allocated for d is outlined 1082 | // compared to the example in previous test case. 1083 | // We are optimising for weight: there are less non-zero elements. 1084 | assert_eq!(matrices.b[1], vec![(Fr::one(), 4)]); 1085 | assert_eq!(matrices.c[1], vec![(Fr::one(), 4)]); 1086 | 1087 | assert_eq!(matrices.a[2], vec![(Fr::one(), 0)]); 1088 | assert_eq!(matrices.b[2], vec![(two, 4)]); 1089 | assert_eq!(matrices.c[2], vec![(two, 4)]); 1090 | Ok(()) 1091 | } 1092 | 1093 | /// Example meant to follow as closely as possible the excellent R1CS 1094 | /// write-up by [Vitalik Buterin](https://vitalik.ca/general/2016/12/10/qap.html) 1095 | /// and demonstrate how to construct such matrices in arkworks. 1096 | #[test] 1097 | fn matrix_generation_example() -> crate::r1cs::Result<()> { 1098 | let cs = ConstraintSystem::::new_ref(); 1099 | // helper definitions 1100 | let three = Fr::from(3u8); 1101 | let five = Fr::from(5u8); 1102 | let nine = Fr::from(9u8); 1103 | // There will be six variables in the system, in the order governed by adding 1104 | // them to the constraint system (Note that the CS is initialised with 1105 | // `Variable::One` in the first position implicitly). 1106 | // Note also that the all public variables will always be placed before all witnesses 1107 | // 1108 | // Variable::One 1109 | // Variable::Instance(35) 1110 | // Variable::Witness(3) ( == x ) 1111 | // Variable::Witness(9) ( == sym_1 ) 1112 | // Variable::Witness(27) ( == y ) 1113 | // Variable::Witness(30) ( == sym_2 ) 1114 | 1115 | // let one = Variable::One; // public input, implicitly defined 1116 | let out = cs.new_input_variable(|| Ok(nine * three + three + five))?; // public input 1117 | let x = cs.new_witness_variable(|| Ok(three))?; // explicit witness 1118 | let sym_1 = cs.new_witness_variable(|| Ok(nine))?; // intermediate witness variable 1119 | let y = cs.new_witness_variable(|| Ok(nine * three))?; // intermediate witness variable 1120 | let sym_2 = cs.new_witness_variable(|| Ok(nine * three + three))?; // intermediate witness variable 1121 | 1122 | cs.enforce_constraint(lc!() + x, lc!() + x, lc!() + sym_1)?; 1123 | cs.enforce_constraint(lc!() + sym_1, lc!() + x, lc!() + y)?; 1124 | cs.enforce_constraint(lc!() + y + x, lc!() + Variable::One, lc!() + sym_2)?; 1125 | cs.enforce_constraint( 1126 | lc!() + sym_2 + (five, Variable::One), 1127 | lc!() + Variable::One, 1128 | lc!() + out, 1129 | )?; 1130 | 1131 | cs.finalize(); 1132 | assert!(cs.is_satisfied().unwrap()); 1133 | let matrices = cs.to_matrices().unwrap(); 1134 | // There are four gates(constraints), each generating a row. 1135 | // Resulting matrices: 1136 | // (Note how 2nd & 3rd columns are swapped compared to the online example. 1137 | // This results from an implementation detail of placing all Variable::Instances(_) first. 1138 | // 1139 | // A 1140 | // [0, 0, 1, 0, 0, 0] 1141 | // [0, 0, 0, 1, 0, 0] 1142 | // [0, 0, 1, 0, 1, 0] 1143 | // [5, 0, 0, 0, 0, 1] 1144 | // B 1145 | // [0, 0, 1, 0, 0, 0] 1146 | // [0, 0, 1, 0, 0, 0] 1147 | // [1, 0, 0, 0, 0, 0] 1148 | // [1, 0, 0, 0, 0, 0] 1149 | // C 1150 | // [0, 0, 0, 1, 0, 0] 1151 | // [0, 0, 0, 0, 1, 0] 1152 | // [0, 0, 0, 0, 0, 1] 1153 | // [0, 1, 0, 0, 0, 0] 1154 | assert_eq!(matrices.a[0], vec![(Fr::one(), 2)]); 1155 | assert_eq!(matrices.b[0], vec![(Fr::one(), 2)]); 1156 | assert_eq!(matrices.c[0], vec![(Fr::one(), 3)]); 1157 | 1158 | assert_eq!(matrices.a[1], vec![(Fr::one(), 3)]); 1159 | assert_eq!(matrices.b[1], vec![(Fr::one(), 2)]); 1160 | assert_eq!(matrices.c[1], vec![(Fr::one(), 4)]); 1161 | 1162 | assert_eq!(matrices.a[2], vec![(Fr::one(), 2), (Fr::one(), 4)]); 1163 | assert_eq!(matrices.b[2], vec![(Fr::one(), 0)]); 1164 | assert_eq!(matrices.c[2], vec![(Fr::one(), 5)]); 1165 | 1166 | assert_eq!(matrices.a[3], vec![(five, 0), (Fr::one(), 5)]); 1167 | assert_eq!(matrices.b[3], vec![(Fr::one(), 0)]); 1168 | assert_eq!(matrices.c[3], vec![(Fr::one(), 1)]); 1169 | Ok(()) 1170 | } 1171 | } 1172 | --------------------------------------------------------------------------------