├── .gitignore ├── src ├── errors.rs ├── allocated_scalar.rs ├── lib.rs ├── scalar.rs └── range.rs ├── Cargo.toml ├── README.md ├── .github └── workflows │ └── dusk_ci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── tests ├── range_gadgets_tests.rs └── scalar_gadgets_tests.rs └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # These are backup files generated by rustfmt 6 | **/*.rs.bk 7 | 8 | Cargo.lock 9 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | //! Gadget Errors Module. 8 | //! 9 | //! Includes the definitions of all of the possible errors that the gadgets 10 | //! might encounter with toghether with it's display message implementations. 11 | 12 | /// Represents an error during the execution of one of the library gagets. 13 | #[derive(Debug)] 14 | pub enum Error { 15 | /// Error returned when we try to compute the inverse of a number which is 16 | /// non-QR (doesn't have an inverse inside of the field) 17 | NonExistingInverse, 18 | } 19 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "plonk_gadgets" 3 | version = "0.6.0" 4 | authors = ["CPerezz ", "Kevaundray Wedderburn ", "Victor Lopez "] 5 | edition = "2018" 6 | readme = "README.md" 7 | repository = "https://github.com/dusk-network/plonk_gadgets" 8 | keywords = ["cryptography", "plonk", "zk-snarks", "zero-knowledge", "crypto"] 9 | categories =["algorithms", "cryptography", "science"] 10 | description = "A collection of generic gadgets for the PLONK ZK-Proof algorithm" 11 | license = "MPL-2.0" 12 | exclude = [ 13 | ".gitignore", 14 | "Cargo.lock", 15 | ".github/" 16 | ] 17 | 18 | [dependencies] 19 | dusk-bytes = "0.1" 20 | dusk-plonk = {version = "0.8", default-features = false, features = ["alloc"]} 21 | 22 | [dev-dependencies] 23 | rand = "0.8" 24 | 25 | [features] 26 | std = [ 27 | "dusk-plonk/std" 28 | ] 29 | -------------------------------------------------------------------------------- /src/allocated_scalar.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | //! This module contains the implementation of the 8 | //! `AllocatedScalar` helper structure. 9 | use dusk_plonk::{ 10 | bls12_381::BlsScalar, 11 | constraint_system::{StandardComposer, Variable}, 12 | }; 13 | 14 | /// An allocated scalar holds the underlying witness assignment for the Prover 15 | /// and a dummy value for the verifier 16 | /// XXX: This could possibly be added to the PLONK API 17 | #[derive(Copy, Clone, Debug)] 18 | pub struct AllocatedScalar { 19 | /// Variable associated to the `Scalar`. 20 | pub var: Variable, 21 | /// Scalar associated to the `Variable` 22 | pub scalar: BlsScalar, 23 | } 24 | 25 | impl AllocatedScalar { 26 | /// Allocates a BlsScalar into the constraint system as a witness 27 | pub fn allocate(composer: &mut StandardComposer, scalar: BlsScalar) -> AllocatedScalar { 28 | let var = composer.add_input(scalar); 29 | AllocatedScalar { var, scalar } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Plonk Gadgets 2 | ![Build Status](https://github.com/dusk-network/plonk_gadgets/workflows/Continuous%20integration/badge.svg) 3 | [![Repository](https://img.shields.io/badge/github-plonk_gadgets-blueviolet?logo=github)](https://github.com/dusk-network/plonk_gadgets) 4 | [![Documentation](https://img.shields.io/badge/docs-plonk_gadgets-blue?logo=rust)](https://docs.rs/plonk_gadgets/) 5 | 6 | 7 | This library cointains the gadgets that the Dusk-Network protocol needs to build it's ZK-Circuits. 8 | The library **contains generic gadgets** which are used across Dusk's tech stack, all of the other 9 | gadgets used which depend on foreign types are placed on the libraries where this types are defined. 10 | 11 | 12 | ## WARNING 13 | This implementation is not audited. Use under your own responsability. 14 | 15 | ## Content 16 | This library provides: 17 | 18 | - Scalar gadgets: `is_non-zero`, `maybe_equals`, `conditionally_select_one`, `conditionally_select_zero`. 19 | - Range gadgets: `range_check`, `max_bound`. 20 | 21 | 22 | ## Acknowledgements 23 | 24 | - Conditional selection gadgets and `AllocatedScalar` structure have been taken from the ZCash sapling 25 | circuits and translated to the Plonk Constraint System language. 26 | 27 | ## Licensing 28 | 29 | This code is licensed under Mozilla Public License Version 2.0 (MPL-2.0). Please see [LICENSE](https://github.com/dusk-network/plonk_gadgets/blob/master/LICENSE) for further info. 30 | 31 | ## About 32 | 33 | Implementation designed by the [dusk](https://dusk.network) team. 34 | 35 | ## Contributing 36 | - If you want to contribute to this repository/project please, check [CONTRIBUTING.md](https://github.com/dusk-network/plonk_gadgets/blob/master/CONTRIBUTING.md) 37 | - If you want to report a bug or request a new feature addition, please open an issue on this repository. -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | //! # Plonk Gadgets 8 | //! This library cointains the gadgets that the Dusk-Network protocol needs to build it's ZK-Circuits. 9 | //! The library **contains generic gadgets** which are used across Dusk's tech stack, all of the other 10 | //! gadgets used which depend on foreign types are placed on the libraries where this types are defined. 11 | //! 12 | //! 13 | //! ## WARNING 14 | //! This implementation is not audited. Use under your own responsability. 15 | //! 16 | //! ## Content 17 | //! This library provides: 18 | //! 19 | //! - Scalar gadgets: `is_non-zero`, `maybe_equals`, `conditionally_select_one`, `conditionally_select_zero`. 20 | //! - Range gadgets: `range_check`, `max_bound`. 21 | 22 | #![doc( 23 | html_logo_url = "https://lh3.googleusercontent.com/SmwswGxtgIANTbDrCOn5EKcRBnVdHjmYsHYxLq2HZNXWCQ9-fZyaea-bNgdX9eR0XGSqiMFi=w128-h128-e365" 24 | )] 25 | #![doc(html_favicon_url = "https://dusk.network/lib/img/favicon-16x16.png")] 26 | // We need to perform bitshifting sometimes. 27 | #![allow(clippy::suspicious_arithmetic_impl)] 28 | // We have cases where we just have `Variables` which don't have any descriptive name. 29 | #![allow(clippy::many_single_char_names)] 30 | #![deny(missing_debug_implementations)] 31 | #![deny(missing_docs)] 32 | #![deny(unsafe_code)] 33 | #![no_std] 34 | 35 | extern crate alloc; 36 | 37 | pub(crate) mod allocated_scalar; 38 | pub mod errors; 39 | pub mod range; 40 | pub mod scalar; 41 | 42 | pub use crate::errors::Error; 43 | pub use allocated_scalar::AllocatedScalar; 44 | pub use range as RangeGadgets; 45 | pub use scalar as ScalarGadgets; 46 | -------------------------------------------------------------------------------- /.github/workflows/dusk_ci.yml: -------------------------------------------------------------------------------- 1 | on: [pull_request] 2 | 3 | name: Continuous integration 4 | 5 | jobs: 6 | analyze: 7 | name: Dusk Analyzer 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | profile: minimal 14 | toolchain: nightly 15 | override: true 16 | - uses: actions-rs/cargo@v1 17 | with: 18 | command: install 19 | args: --git https://github.com/dusk-network/cargo-dusk-analyzer 20 | - uses: actions-rs/cargo@v1 21 | with: 22 | command: dusk-analyzer 23 | 24 | check: 25 | name: Check 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions-rs/toolchain@v1 30 | with: 31 | profile: minimal 32 | toolchain: nightly 33 | override: true 34 | - uses: actions-rs/cargo@v1 35 | with: 36 | command: check 37 | 38 | test_nightly: 39 | name: Nightly tests 40 | runs-on: ubuntu-latest 41 | steps: 42 | - uses: actions/checkout@v2 43 | - uses: actions-rs/toolchain@v1 44 | with: 45 | profile: minimal 46 | toolchain: nightly 47 | override: true 48 | - uses: actions-rs/cargo@v1 49 | with: 50 | command: test 51 | args: --release 52 | 53 | fmt: 54 | name: Rustfmt 55 | runs-on: ubuntu-latest 56 | steps: 57 | - uses: actions/checkout@v2 58 | - uses: actions-rs/toolchain@v1 59 | with: 60 | profile: minimal 61 | toolchain: nightly-2020-10-25 62 | override: true 63 | - run: rustup component add rustfmt 64 | - uses: actions-rs/cargo@v1 65 | with: 66 | command: fmt 67 | args: --all -- --check 68 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ## [v0.6.0] - 06-07-21 11 | 12 | ### Add 13 | - Add `std` feature to crate [#42](https://github.com/dusk-network/plonk_gadgets/issues/42) 14 | 15 | ### Change 16 | - Change crate to be `no_std` by default [#42](https://github.com/dusk-network/plonk_gadgets/issues/42) 17 | - Update `rand` from `v0.7` to `v0.8` [#42](https://github.com/dusk-network/plonk_gadgets/issues/42) 18 | 19 | ### Remove 20 | - Remove `anyhow` and `thiserror`. [#39](https://github.com/dusk-network/plonk_gadgets/issues/39) 21 | - Remove `rand_core` from dev-deps [#42](https://github.com/dusk-network/plonk_gadgets/issues/42) 22 | 23 | ## [v0.5.0] - 13-01-21 24 | 25 | ### Change 26 | 27 | - Update `dusk-plonk` to `v0.5.0` 28 | 29 | ## [v0.4.3] - 10-11-20 30 | 31 | ### Change 32 | 33 | - Update `BlsScalar` instance backend 34 | 35 | ## [0.4.2] - 02-11-20 36 | 37 | ### Changed 38 | 39 | - Bumped dusk-plonk to v0.3.3 40 | 41 | ## [0.4.1] - 01-11-20 42 | 43 | ### Changed 44 | 45 | - Bumped dusk-plonk to v0.3.2 46 | 47 | ## [0.4.0] - 05-10-20 48 | 49 | ### Changed 50 | 51 | - Updated dusk-plonk to v0.3.1 52 | 53 | ## [0.3.0] - 29-09-20 54 | 55 | ### Changed 56 | 57 | - dusk_plonk version changed to latest (v0.2.11) 58 | 59 | ## [0.2.1] - 28-08-20 60 | 61 | ### Changed 62 | 63 | - dusk_plonk version changed to latest (v0.2.8) 64 | 65 | ## [0.2.0] - 19-08-20 66 | 67 | ### Added 68 | 69 | - `maybe_equal` gadget 70 | - `AllocatedScalar` helper structure. 71 | - Lib & code docs. 72 | 73 | ### Changed 74 | 75 | - Integration tests moved to the `tests` folder. 76 | - Changed the external API the crate exposes. 77 | - Rangeproof-related functions (#17) 78 | 79 | ## [0.1.0] - 17-08-20 80 | 81 | ### Added 82 | 83 | - Range gadgets taken from the `dusk-blindbid` library. 84 | - `Inverse rangeproof` gadget. 85 | 86 | ### Changed 87 | 88 | - Conditional selection gadgets have been upadated. 89 | - Switched to latest `dusk-plonk` version. 90 | 91 | ### Removed 92 | 93 | - Removed all of the ECC-related modules. 94 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to plonk 2 | 3 | All of the code under this repository is licensed under the 4 | Mozilla Public License Version 2.0. 5 | 6 | If you have questions or comments, please feel free to email the 7 | authors listed [here](https://github.com/dusk-network/plonk_gadgets/blob/master/Cargo.toml#L4). 8 | 9 | For feature requests, suggestions, and bug reports, please open an issue on 10 | [our Github](https://github.com/dusk-network/plonk_gadgets). (Or, send us 11 | an email if you're opposed to using Github for whatever reason.) 12 | 13 | Patches are welcomed as pull requests on 14 | [our Github](https://github.com/dusk-network/plonk_gadgets), as well as by 15 | email (preferably sent to all of the authors listed in `Cargo.toml`). 16 | 17 | If you want to work on an issue, please let us know in the comments of it and 18 | we will assign it to you. 19 | 20 | If you're new to this repository and you want to contribute, you can 21 | look for the issues tagged the with `good first issue` label. We try to add this tag 22 | to the issues we belive are easy for newcomers. 23 | 24 | If you need any help regarding an issue feel free to ask the authors in the `Draft pull request` 25 | or the issue (or by email if you prefer it by any reason.) 26 | 27 | # Pull Requests 28 | 29 | - Keep your pull requests as `Draft` until they are ready to be reviewed. 30 | 31 | - Be descriptive in the titles of your PRs and also provide good descriptions about 32 | which things are being added, changed, fixed or removed also addressing the corresponding 33 | issue that it is addressing to. 34 | 35 | - Any pull request that it's not passing our CI tests & builds will not be merged. 36 | This implies incorrect formatting errors, compilation errors, clippy lints, or any 37 | other kind of inconsistency with your code. 38 | 39 | - Do not open PRs that are not linked or related to a previously opened issue. 40 | 41 | - Update the `Unreleased` section of the [CHANGELOG](https://github.com/dusk-network/plonk_gadgets/blob/master/CHANGELOG.md) 42 | if your PR includes anything that it's worth to be noticed in there. Avoid adding things 43 | like doc-nitpicks and similar changes which do not affect directly any added, 44 | fixed, removed or changed feature. 45 | 46 | # Code of Conduct 47 | 48 | We follow the [Rust Code of Conduct](http://www.rust-lang.org/conduct.html): 49 | 50 | * We are committed to providing a friendly, safe and welcoming environment for all, regardless 51 | of level of experience, gender identity and expression, sexual orientation, disability, personal 52 | appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. 53 | 54 | * Please avoid using overtly sexual aliases or other nicknames that might detract from a friendly, 55 | safe and welcoming environment for all. 56 | 57 | * Please be kind and courteous. There’s no need to be mean or rude. 58 | 59 | * Respect that people have differences of opinion and that every design or implementation choice carries 60 | a trade-off and numerous costs. There is seldom a right answer. 61 | 62 | * Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. 63 | 64 | * We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term “harassment” as including the definition in the Citizen Code of Conduct; if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don’t tolerate behavior that excludes people in socially marginalized groups. 65 | 66 | * Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the Rust moderation team immediately. Whether you’re a regular contributor or a newcomer, we care about making this community a safe place for you and we’ve got your back. 67 | 68 | * Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. 69 | 70 | -------------------------------------------------------------------------------- /src/scalar.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | //! Basic `Scalar` oriented gadgets collection. 8 | //! 9 | //! This module actually contains conditional selection implementations as 10 | //! well as equalty-checking gadgets. 11 | use super::AllocatedScalar; 12 | use crate::Error as GadgetsError; 13 | use dusk_plonk::prelude::*; 14 | 15 | /// Conditionally selects the value provided or a zero instead. 16 | /// NOTE that the `select` input has to be previously constrained to 17 | /// be either `one` or `zero`. 18 | /// ## Performs: 19 | /// x' = x if select = 1 20 | /// x' = 0 if select = 0 21 | pub fn conditionally_select_zero( 22 | composer: &mut StandardComposer, 23 | x: Variable, 24 | select: Variable, 25 | ) -> Variable { 26 | composer.mul(BlsScalar::one(), x, select, BlsScalar::zero(), None) 27 | } 28 | 29 | /// Conditionally selects the value provided or a one instead. 30 | /// NOTE that the `select` input has to be previously constrained to 31 | /// be either `one` or `zero`. 32 | /// ## Performs: 33 | /// y' = y if selector = 1 34 | /// y' = 1 if selector = 0 => 35 | /// y' = selector * y + (1 - selector) 36 | pub fn conditionally_select_one( 37 | composer: &mut StandardComposer, 38 | y: Variable, 39 | selector: Variable, 40 | ) -> Variable { 41 | let one = composer.add_witness_to_circuit_description(BlsScalar::one()); 42 | // selector * y 43 | let selector_y = composer.mul(BlsScalar::one(), y, selector, BlsScalar::zero(), None); 44 | // 1 - selector 45 | let one_min_selector = composer.add( 46 | (BlsScalar::one(), one), 47 | (-BlsScalar::one(), selector), 48 | BlsScalar::zero(), 49 | None, 50 | ); 51 | 52 | // selector * y + (1 - selector) 53 | composer.add( 54 | (BlsScalar::one(), selector_y), 55 | (BlsScalar::one(), one_min_selector), 56 | BlsScalar::zero(), 57 | None, 58 | ) 59 | } 60 | 61 | /// Provided a `Variable` and the `Scalar` it is attached to, the function 62 | /// constraints the `Variable` to be != Zero. 63 | pub fn is_non_zero( 64 | composer: &mut StandardComposer, 65 | var: Variable, 66 | value_assigned: BlsScalar, 67 | ) -> Result<(), GadgetsError> { 68 | // Add original scalar which is equal to `var`. 69 | let var_assigned = composer.add_input(value_assigned); 70 | // Constrain `var` to actually be equal to the `var_assigment` provided. 71 | composer.assert_equal(var, var_assigned); 72 | // Compute the inverse of `value_assigned`. 73 | let inverse = value_assigned.invert(); 74 | let inv: Variable; 75 | if inverse.is_some().unwrap_u8() == 1u8 { 76 | // Safe to unwrap here. 77 | inv = composer.add_input(inverse.unwrap()); 78 | } else { 79 | return Err(GadgetsError::NonExistingInverse); 80 | } 81 | 82 | // Var * Inv(Var) = 1 83 | let one = composer.add_witness_to_circuit_description(BlsScalar::one()); 84 | composer.poly_gate( 85 | var, 86 | inv, 87 | one, 88 | BlsScalar::one(), 89 | BlsScalar::zero(), 90 | BlsScalar::zero(), 91 | -BlsScalar::one(), 92 | BlsScalar::zero(), 93 | None, 94 | ); 95 | 96 | Ok(()) 97 | } 98 | 99 | /// Returns 1 if a = b and zero otherwise. 100 | /// 101 | /// # NOTE 102 | /// If you need to check equality constraining it, this function is not intended for it, 103 | /// instead we recommend to use `composer.assert_equals()` or `composer.constraint_to_constant()` 104 | /// functions from `dusk-plonk` crate which will introduce less constraints to your circuit. 105 | pub fn maybe_equal( 106 | composer: &mut StandardComposer, 107 | a: AllocatedScalar, 108 | b: AllocatedScalar, 109 | ) -> Variable { 110 | // u = a - b 111 | let u = { 112 | let q_l_a = (BlsScalar::one(), a.var); 113 | let q_r_b = (-BlsScalar::one(), b.var); 114 | let q_c = BlsScalar::zero(); 115 | 116 | composer.add(q_l_a, q_r_b, q_c, None) 117 | }; 118 | 119 | // compute z = inverse of u. 120 | // This is zero for zero and non-zero otherwise 121 | let u_scalar = a.scalar - b.scalar; 122 | let u_inv_scalar = u_scalar.invert().unwrap_or(BlsScalar::zero()); 123 | let z = composer.add_input(u_inv_scalar); 124 | 125 | // y = 1 - uz 126 | let y = composer.mul(-BlsScalar::one(), z, u, BlsScalar::one(), None); 127 | 128 | // yu = 0 129 | { 130 | let a = y; 131 | let b = u; 132 | let c = u; 133 | let q_m = BlsScalar::one(); 134 | let q_o = BlsScalar::zero(); 135 | let q_c = BlsScalar::zero(); 136 | 137 | composer.mul_gate(a, b, c, q_m, q_o, q_c, None); 138 | } 139 | y 140 | } 141 | -------------------------------------------------------------------------------- /tests/range_gadgets_tests.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | extern crate dusk_plonk; 8 | extern crate plonk_gadgets; 9 | use dusk_plonk::prelude::*; 10 | use plonk_gadgets::AllocatedScalar; 11 | use plonk_gadgets::RangeGadgets::*; 12 | 13 | fn max_bound_gadget( 14 | composer: &mut StandardComposer, 15 | max_range: BlsScalar, 16 | witness: BlsScalar, 17 | result: bool, 18 | ) { 19 | let witness = AllocatedScalar::allocate(composer, witness); 20 | let (res, _) = max_bound(composer, max_range, witness); 21 | 22 | let mut outcome = BlsScalar::zero(); 23 | if result { 24 | outcome = BlsScalar::one() 25 | } 26 | composer.constrain_to_constant(res, outcome, None); 27 | } 28 | 29 | fn range_check_gadget( 30 | composer: &mut StandardComposer, 31 | max_range: BlsScalar, 32 | min_range: BlsScalar, 33 | witness: BlsScalar, 34 | result: bool, 35 | ) { 36 | let witness = AllocatedScalar::allocate(composer, witness); 37 | let res = range_check(composer, min_range, max_range, witness); 38 | 39 | let mut outcome = BlsScalar::zero(); 40 | if result { 41 | outcome = BlsScalar::one() 42 | } 43 | composer.constrain_to_constant(res, outcome, None); 44 | } 45 | 46 | #[test] 47 | fn max_bound_test() -> Result<(), Error> { 48 | // Generate Composer & Public Parameters 49 | let pub_params = PublicParameters::setup(1 << 11, &mut rand::thread_rng())?; 50 | let (ck, vk) = pub_params.trim(1 << 10)?; 51 | 52 | struct TestCase { 53 | max_range: BlsScalar, 54 | witness: BlsScalar, 55 | expected_result: bool, 56 | } 57 | let test_cases = vec![ 58 | TestCase { 59 | max_range: BlsScalar::from(2u64).pow(&[128u64, 0, 0, 0]) - BlsScalar::one(), 60 | witness: BlsScalar::from(2u64).pow(&[127u64, 0, 0, 0]), 61 | expected_result: true, 62 | }, 63 | TestCase { 64 | max_range: BlsScalar::from(200u64), 65 | witness: BlsScalar::from(100u64), 66 | expected_result: true, 67 | }, 68 | TestCase { 69 | max_range: BlsScalar::from(100u64), 70 | witness: BlsScalar::from(200u64), 71 | expected_result: false, 72 | }, 73 | TestCase { 74 | max_range: BlsScalar::from(2u64).pow(&[128u64, 0, 0, 0]) - BlsScalar::one(), 75 | witness: BlsScalar::from(2u64).pow(&[130u64, 0, 0, 0]), 76 | expected_result: false, 77 | }, 78 | ]; 79 | 80 | for case in test_cases.into_iter() { 81 | // Proving 82 | let mut prover = Prover::default(); 83 | 84 | max_bound_gadget( 85 | prover.mut_cs(), 86 | case.max_range, 87 | case.witness, 88 | case.expected_result, 89 | ); 90 | prover.preprocess(&ck)?; 91 | let proof = prover.prove(&ck)?; 92 | 93 | // Verification 94 | let mut verifier = Verifier::default(); 95 | max_bound_gadget( 96 | verifier.mut_cs(), 97 | case.max_range, 98 | case.witness, 99 | case.expected_result, 100 | ); 101 | verifier.preprocess(&ck)?; 102 | assert!(verifier 103 | .verify(&proof, &vk, &vec![BlsScalar::zero()]) 104 | .is_ok()); 105 | } 106 | Ok(()) 107 | } 108 | #[test] 109 | fn range_check_test() -> Result<(), Error> { 110 | // Generate Composer & Public Parameters 111 | let pub_params = PublicParameters::setup(1 << 11, &mut rand::thread_rng())?; 112 | let (ck, vk) = pub_params.trim(1 << 10)?; 113 | 114 | struct TestCase { 115 | max_range: BlsScalar, 116 | min_range: BlsScalar, 117 | witness: BlsScalar, 118 | expected_result: bool, 119 | } 120 | let test_cases = vec![ 121 | TestCase { 122 | min_range: BlsScalar::from(50_000u64), 123 | max_range: BlsScalar::from(250_000u64), 124 | witness: BlsScalar::from(50_001u64), 125 | expected_result: true, 126 | }, 127 | TestCase { 128 | min_range: BlsScalar::from(50_000u64), 129 | max_range: BlsScalar::from(250_000u64), 130 | witness: BlsScalar::from(250_001u64), 131 | expected_result: false, 132 | }, 133 | TestCase { 134 | min_range: BlsScalar::from(50_000u64), 135 | max_range: BlsScalar::from(250_000u64), 136 | witness: BlsScalar::from(250_000u64), 137 | expected_result: false, 138 | }, 139 | TestCase { 140 | min_range: BlsScalar::from(50_000u64), 141 | max_range: BlsScalar::from(250_000u64), 142 | witness: BlsScalar::from(249_000u64), 143 | expected_result: true, 144 | }, 145 | TestCase { 146 | min_range: BlsScalar::from(50_000u64), 147 | max_range: BlsScalar::from(250_000u64), 148 | witness: BlsScalar::from(50_000u64), 149 | expected_result: true, 150 | }, 151 | TestCase { 152 | min_range: BlsScalar::from(50_000u64), 153 | max_range: BlsScalar::from(250_000u64), 154 | witness: BlsScalar::from(49_999u64), 155 | expected_result: false, 156 | }, 157 | TestCase { 158 | min_range: BlsScalar::from(2u64).pow(&[126u64, 0, 0, 0]), 159 | max_range: BlsScalar::from(2u64).pow(&[127u64, 0, 0, 0]) + BlsScalar::one(), 160 | witness: BlsScalar::from(2u64).pow(&[127u64, 0, 0, 0]) - BlsScalar::one(), 161 | expected_result: true, 162 | }, 163 | TestCase { 164 | min_range: BlsScalar::from(50_000u64), 165 | max_range: BlsScalar::from(250_000u64), 166 | witness: BlsScalar::from(18_598u64), 167 | expected_result: false, 168 | }, 169 | ]; 170 | 171 | for case in test_cases.into_iter() { 172 | // Proving 173 | let mut prover = Prover::default(); 174 | 175 | range_check_gadget( 176 | prover.mut_cs(), 177 | case.max_range, 178 | case.min_range, 179 | case.witness, 180 | case.expected_result, 181 | ); 182 | prover.preprocess(&ck)?; 183 | let proof = prover.prove(&ck)?; 184 | 185 | // Verification 186 | let mut verifier = Verifier::default(); 187 | range_check_gadget( 188 | verifier.mut_cs(), 189 | case.max_range, 190 | case.min_range, 191 | case.witness, 192 | case.expected_result, 193 | ); 194 | verifier.preprocess(&ck)?; 195 | assert!(verifier 196 | .verify(&proof, &vk, &vec![BlsScalar::zero()]) 197 | .is_ok()); 198 | } 199 | 200 | Ok(()) 201 | } 202 | -------------------------------------------------------------------------------- /src/range.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | //! Collection of range-checking gadgets. 8 | //! 9 | //! # Note 10 | //! If you just need to do a normal rangeproof with boundaries being powers 11 | //! of two, we recomend to use the function builtin plonk for it: `composer.range_gate()` 12 | //! since it will introduce less constraints to your CS. 13 | 14 | use super::{scalar::maybe_equal, AllocatedScalar}; 15 | use alloc::vec::Vec; 16 | use dusk_bytes::Serializable; 17 | use dusk_plonk::prelude::*; 18 | 19 | /// Returns a 0 or a 1, if the value lies within the specified range 20 | /// We do this by decomposing the scalar and showing that it can be represented in x amount of bits 21 | fn range_proof(composer: &mut StandardComposer, value: AllocatedScalar, num_bits: u64) -> Variable { 22 | let (is_equal, _value_bits) = scalar_decomposition_gadget(composer, num_bits as usize, value); 23 | is_equal 24 | } 25 | 26 | /// Returns a 1 if min_range <= x < max_range and zero otherwise 27 | pub fn range_check( 28 | composer: &mut StandardComposer, 29 | min_range: BlsScalar, 30 | max_range: BlsScalar, 31 | witness: AllocatedScalar, 32 | ) -> Variable { 33 | // Upper bound check 34 | let (y1, num_bits_pow_2) = max_bound(composer, max_range, witness); 35 | 36 | // Lower bound check 37 | let y2 = min_bound(composer, min_range, witness, num_bits_pow_2); 38 | 39 | // Computes y1 * y2 40 | // If both lower and upper bound checks are true, 41 | // then this will return 1 otherwise it returns 0 42 | composer.mul(BlsScalar::one(), y1, y2, BlsScalar::zero(), None) 43 | } 44 | 45 | /// Returns a 0 or a 1, if the witness is greater than or equal to the minimum bound 46 | /// The statement a <= x , implies x - a >= 0 , for all values x,a 47 | /// Instead of proving x - a is positive for all values in the field, it is sufficient to prove 48 | /// it is positive for a specific power of two. 49 | /// This power of two must be large enough to cover the whole range of values x and a can take 50 | /// Therefore it must be the closest power of two, to the upper bound 51 | /// In this case, the upper bound is a witness, hence the Prover and Verifier will need to know in advance 52 | /// The maximum number of bits that the witness could be 53 | fn min_bound( 54 | composer: &mut StandardComposer, 55 | min_range: BlsScalar, 56 | witness: AllocatedScalar, 57 | num_bits: u64, 58 | ) -> Variable { 59 | // Compute x - a in the circuit 60 | let x_min_a_var = { 61 | let q_l_a = (BlsScalar::one(), witness.var); 62 | let q_r_b = (BlsScalar::zero(), witness.var); // XXX: Expose composer.zero() 63 | let q_c = -min_range; 64 | 65 | composer.add(q_l_a, q_r_b, q_c, None) 66 | }; 67 | 68 | // Compute witness assignment value for x - a 69 | let x_min_a_scalar = witness.scalar - min_range; 70 | 71 | let x_min_a = AllocatedScalar { 72 | var: x_min_a_var, 73 | scalar: x_min_a_scalar, 74 | }; 75 | range_proof(composer, x_min_a, num_bits) 76 | } 77 | 78 | /// Returns a 0 or a 1, if the witness is greater than the maximum bound 79 | /// x < b which implies that b - x - 1 >= 0 80 | /// Note that since the maximum bound is public knowledge 81 | /// the num_bits can be computed 82 | pub fn max_bound( 83 | composer: &mut StandardComposer, 84 | max_range: BlsScalar, 85 | witness: AllocatedScalar, 86 | ) -> (Variable, u64) { 87 | let max_range = max_range - BlsScalar::one(); 88 | 89 | // Since the upper bound is public, we can compute the number of bits in the closest power of two 90 | let num_bits_pow_2 = num_bits_closest_power_of_two(max_range); 91 | 92 | // Compute b - x in the circuit 93 | let b_minus_x_var = { 94 | let q_l_a = (-BlsScalar::one(), witness.var); 95 | let q_r_b = (BlsScalar::zero(), witness.var); // XXX: Expose composer.zero() 96 | let q_c = max_range; 97 | 98 | composer.add(q_l_a, q_r_b, q_c, None) 99 | }; 100 | 101 | // Compute witness assignment value for b - x 102 | let b_minus_x_scalar = max_range - witness.scalar; 103 | 104 | let b_prime_plus_x = AllocatedScalar { 105 | var: b_minus_x_var, 106 | scalar: b_minus_x_scalar, 107 | }; 108 | 109 | ( 110 | range_proof(composer, b_prime_plus_x, num_bits_pow_2), 111 | num_bits_pow_2, 112 | ) 113 | } 114 | 115 | /// Decomposes a witness and constraints it to be equal to it's bit representation 116 | /// Returns a 0 or 1 if the witness can be represented in the specified number of bits 117 | /// This effectively makes it a rangeproof. If the witness can be represented in less than x bits, then 118 | /// It must be with the range of [0, 2^x) 119 | fn scalar_decomposition_gadget( 120 | composer: &mut StandardComposer, 121 | num_bits: usize, 122 | witness: AllocatedScalar, 123 | ) -> (Variable, Vec) { 124 | // Decompose the bits 125 | let scalar_bits = scalar_to_bits(&witness.scalar); 126 | 127 | // Add all the bits into the composer 128 | let scalar_bits_var: Vec = scalar_bits 129 | .iter() 130 | .map(|bit| composer.add_input(BlsScalar::from(*bit as u64))) 131 | .collect(); 132 | 133 | // Take the first n bits 134 | let scalar_bits_var = scalar_bits_var[..num_bits].to_vec(); 135 | 136 | // Now ensure that the bits correctly accumulate to the witness given 137 | // XXX: Expose a method called .zero() on composer 138 | let mut accumulator = AllocatedScalar { 139 | var: composer.add_witness_to_circuit_description(BlsScalar::zero()), 140 | scalar: BlsScalar::zero(), 141 | }; 142 | 143 | for (power, bit) in scalar_bits_var.iter().enumerate() { 144 | composer.boolean_gate(*bit); 145 | 146 | let two_pow = BlsScalar::from(2).pow(&[power as u64, 0, 0, 0]); 147 | let q_l_a = (two_pow, *bit); 148 | let q_r_b = (BlsScalar::one(), accumulator.var); 149 | let q_c = BlsScalar::zero(); 150 | 151 | accumulator.var = composer.add(q_l_a, q_r_b, q_c, None); 152 | accumulator.scalar += two_pow * BlsScalar::from(scalar_bits[power] as u64); 153 | } 154 | 155 | let is_equal = maybe_equal(composer, accumulator, witness); 156 | 157 | (is_equal, scalar_bits_var) 158 | } 159 | 160 | // Decompose a `BlsScalar` into its 256-bit representation. 161 | fn scalar_to_bits(scalar: &BlsScalar) -> [u8; 256] { 162 | let mut res = [0u8; 256]; 163 | let bytes = scalar.to_bytes(); 164 | for (byte, bits) in bytes.iter().zip(res.chunks_mut(8)) { 165 | bits.iter_mut() 166 | .enumerate() 167 | .for_each(|(i, bit)| *bit = (byte >> i) & 1) 168 | } 169 | res 170 | } 171 | 172 | // Count the minimum amount of bits necessary to represent a `BlsScalar`. 173 | fn bits_count(mut scalar: BlsScalar) -> u64 { 174 | scalar = scalar.reduce(); 175 | let mut counter = 1u64; 176 | while scalar > BlsScalar::one().reduce() { 177 | scalar.divn(1); 178 | counter += 1; 179 | } 180 | counter 181 | } 182 | 183 | // Returns the number of bits of the closest power of two 184 | // to the scalar and the closest power of two 185 | fn num_bits_closest_power_of_two(scalar: BlsScalar) -> u64 { 186 | let num_bits = bits_count(scalar); 187 | let closest_pow_of_two = BlsScalar::pow_of_2(num_bits); 188 | bits_count(closest_pow_of_two) 189 | } 190 | 191 | #[cfg(test)] 192 | mod tests { 193 | use super::*; 194 | use alloc::vec; 195 | 196 | #[test] 197 | fn counting_scalar_bits() { 198 | assert_eq!(bits_count(BlsScalar::zero()), 1); 199 | assert_eq!(bits_count(BlsScalar::one()), 1); 200 | assert_eq!(bits_count(BlsScalar::from(3u64)), 2); 201 | let two_pow_128 = BlsScalar::from(2u64).pow(&[128u64, 0, 0, 0]); 202 | assert_eq!(bits_count(two_pow_128), 129); 203 | } 204 | 205 | #[test] 206 | fn scalar_decomposition_test() -> Result<(), Error> { 207 | // Generate Composer & Public Parameters 208 | let pub_params = PublicParameters::setup(1 << 11, &mut rand::thread_rng())?; 209 | let (ck, vk) = pub_params.trim(1 << 10)?; 210 | 211 | // Proving 212 | let mut prover = Prover::new(b"testing"); 213 | 214 | let witness = AllocatedScalar::allocate(prover.mut_cs(), -BlsScalar::from(100)); 215 | let (is_eq, _) = scalar_decomposition_gadget(prover.mut_cs(), 8, witness); 216 | prover 217 | .mut_cs() 218 | .constrain_to_constant(is_eq, BlsScalar::zero(), None); 219 | let proof = prover.prove(&ck)?; 220 | 221 | // Verification 222 | let mut verifier = Verifier::new(b"testing"); 223 | 224 | let witness = AllocatedScalar::allocate(verifier.mut_cs(), BlsScalar::from(1)); 225 | let (is_eq, _) = scalar_decomposition_gadget(verifier.mut_cs(), 8, witness); 226 | verifier 227 | .mut_cs() 228 | .constrain_to_constant(is_eq, BlsScalar::zero(), None); 229 | 230 | verifier.preprocess(&ck)?; 231 | 232 | verifier.verify(&proof, &vk, &vec![BlsScalar::zero()]) 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /tests/scalar_gadgets_tests.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | extern crate dusk_plonk; 8 | extern crate plonk_gadgets; 9 | 10 | use dusk_plonk::prelude::*; 11 | use plonk_gadgets::{AllocatedScalar, Error as GadgetError, ScalarGadgets::*}; 12 | 13 | #[test] 14 | fn test_maybe_equal() -> Result<(), Error> { 15 | // Generate Composer & Public Parameters 16 | let pub_params = PublicParameters::setup(1 << 10, &mut rand::thread_rng())?; 17 | let (ck, vk) = pub_params.trim(1 << 9)?; 18 | 19 | let is_equal_gadget = 20 | |composer: &mut StandardComposer, num_1: u64, num_2: u64, result: bool| { 21 | let a = AllocatedScalar::allocate(composer, BlsScalar::from(num_1)); 22 | let b = AllocatedScalar::allocate(composer, BlsScalar::from(num_2)); 23 | 24 | let bit = maybe_equal(composer, a, b); 25 | 26 | let mut outcome = BlsScalar::zero(); 27 | if result { 28 | outcome = BlsScalar::one() 29 | } 30 | composer.constrain_to_constant(bit, outcome, None); 31 | }; 32 | 33 | // Proving 34 | // Should pass as 100 == 100 35 | let mut prover = Prover::new(b"testing"); 36 | is_equal_gadget(prover.mut_cs(), 100, 100, true); 37 | 38 | prover.preprocess(&ck)?; 39 | let proof = prover.prove(&ck)?; 40 | 41 | // Verification 42 | let mut verifier = Verifier::new(b"testing"); 43 | is_equal_gadget(verifier.mut_cs(), 0, 0, true); 44 | 45 | verifier.preprocess(&ck).expect("Preprocessing error"); 46 | assert!(verifier 47 | .verify(&proof, &vk, &vec![BlsScalar::zero()]) 48 | .is_ok()); 49 | 50 | // Proving 51 | // Should fail as 20 != 3330 52 | let mut prover = Prover::new(b"testing"); 53 | is_equal_gadget(prover.mut_cs(), 20, 3330, false); 54 | 55 | prover.preprocess(&ck)?; 56 | let proof = prover.prove(&ck)?; 57 | 58 | // Verification 59 | let mut verifier = Verifier::new(b"testing"); 60 | is_equal_gadget(verifier.mut_cs(), 0, 0, false); 61 | 62 | verifier.preprocess(&ck)?; 63 | assert!(verifier 64 | .verify(&proof, &vk, &vec![BlsScalar::zero()]) 65 | .is_ok()); 66 | 67 | Ok(()) 68 | } 69 | 70 | #[test] 71 | fn test_conditionally_select_0() -> Result<(), Error> { 72 | // The circuit closure runs the conditionally_select_zero fn and constraints the result 73 | // to actually be 0 74 | let circuit = |composer: &mut StandardComposer, value: BlsScalar, selector: BlsScalar| { 75 | let value = composer.add_input(value); 76 | let selector = composer.add_input(selector); 77 | let res = conditionally_select_zero(composer, value, selector); 78 | composer.constrain_to_constant(res, BlsScalar::zero(), None); 79 | }; 80 | 81 | // Generate Composer & Public Parameters 82 | let pub_params = PublicParameters::setup(1 << 8, &mut rand::thread_rng())?; 83 | let (ck, vk) = pub_params.trim(1 << 7)?; 84 | 85 | // Selector set to 0 should select 0 86 | // Proving 87 | let mut prover = Prover::new(b"testing"); 88 | circuit( 89 | prover.mut_cs(), 90 | BlsScalar::random(&mut rand::thread_rng()), 91 | BlsScalar::zero(), 92 | ); 93 | prover.preprocess(&ck)?; 94 | let proof = prover.prove(&ck)?; 95 | 96 | // Verification 97 | let mut verifier = Verifier::new(b"testing"); 98 | circuit( 99 | verifier.mut_cs(), 100 | BlsScalar::random(&mut rand::thread_rng()), 101 | BlsScalar::zero(), 102 | ); 103 | verifier.preprocess(&ck)?; 104 | // This should pass since we sent 0 as selector and the circuit closure is constraining the 105 | // result to be equal to 0. 106 | assert!(verifier.verify(&proof, &vk, &[BlsScalar::zero()]).is_ok()); 107 | 108 | // Selector set to 1 shouldn't assign 0. 109 | // Proving 110 | prover.clear_witness(); 111 | circuit( 112 | prover.mut_cs(), 113 | BlsScalar::random(&mut rand::thread_rng()), 114 | BlsScalar::one(), 115 | ); 116 | let proof = prover.prove(&ck)?; 117 | // This shouldn't pass since we sent 1 as selector and the circuit closure is constraining the 118 | // result to be equal to 0 while the value assigned is indeed the randomly generated one. 119 | assert!(verifier.verify(&proof, &vk, &[BlsScalar::zero()]).is_err()); 120 | 121 | Ok(()) 122 | } 123 | 124 | #[test] 125 | fn test_conditionally_select_1() -> Result<(), Error> { 126 | // The circuit closure runs the conditionally_select_one fn and constraints the result 127 | // to actually to be equal to the provided expected_result. 128 | let circuit = |composer: &mut StandardComposer, 129 | value: BlsScalar, 130 | selector: BlsScalar, 131 | expected_result: BlsScalar| { 132 | let value = composer.add_input(value); 133 | let selector = composer.add_input(selector); 134 | let res = conditionally_select_one(composer, value, selector); 135 | composer.constrain_to_constant(res, BlsScalar::zero(), Some(-expected_result)); 136 | }; 137 | 138 | // Generate Composer & Public Parameters 139 | let pub_params = PublicParameters::setup(1 << 8, &mut rand::thread_rng())?; 140 | let (ck, vk) = pub_params.trim(1 << 7)?; 141 | 142 | // Selector set to 0 should asign 1 143 | // Proving 144 | let mut prover = Prover::new(b"testing"); 145 | circuit( 146 | prover.mut_cs(), 147 | BlsScalar::random(&mut rand::thread_rng()), 148 | BlsScalar::zero(), 149 | BlsScalar::one(), 150 | ); 151 | let mut pi = prover.mut_cs().construct_dense_pi_vec().clone(); 152 | prover.preprocess(&ck)?; 153 | let proof = prover.prove(&ck)?; 154 | 155 | // Verification 156 | let mut verifier = Verifier::new(b"testing"); 157 | circuit( 158 | verifier.mut_cs(), 159 | BlsScalar::random(&mut rand::thread_rng()), 160 | BlsScalar::zero(), 161 | BlsScalar::one(), 162 | ); 163 | verifier.preprocess(&ck)?; 164 | // This should pass since we sent 0 as selector and the circuit should then return 165 | // 1. 166 | assert!(verifier.verify(&proof, &vk, &pi).is_ok()); 167 | 168 | // Selector set to 1 should assign the randomly-generated value. 169 | // Proving 170 | prover.clear_witness(); 171 | let rand = BlsScalar::random(&mut rand::thread_rng()); 172 | circuit(prover.mut_cs(), rand, BlsScalar::one(), rand); 173 | pi = prover.mut_cs().construct_dense_pi_vec().clone(); 174 | let proof = prover.prove(&ck)?; 175 | // This should pass since we sent 1 as selector and the circuit closure should assign the randomly-generated 176 | // value as a result. 177 | verifier.verify(&proof, &vk, &pi) 178 | } 179 | 180 | #[test] 181 | fn test_is_not_zero() -> Result<(), Error> { 182 | // The circuit closure runs the is_not_zero fn and constraints the input to 183 | // not be zero. 184 | let circuit = |composer: &mut StandardComposer, 185 | value: BlsScalar, 186 | value_assigned: BlsScalar| 187 | -> Result<(), GadgetError> { 188 | let value = composer.add_input(value); 189 | is_non_zero(composer, value, value_assigned) 190 | }; 191 | 192 | // Generate Composer & Public Parameters 193 | let pub_params = PublicParameters::setup(1 << 8, &mut rand::thread_rng())?; 194 | let (ck, vk) = pub_params.trim(1 << 7)?; 195 | 196 | // Value & Value assigned set to 0 should err 197 | // Proving 198 | let mut prover = Prover::new(b"testing"); 199 | assert!(circuit(prover.mut_cs(), BlsScalar::zero(), BlsScalar::zero()).is_err()); 200 | prover.clear_witness(); 201 | 202 | // Value and value_assigned with different values should fail on verification. 203 | // Proving 204 | let mut prover = Prover::new(b"testing"); 205 | assert!(circuit( 206 | prover.mut_cs(), 207 | BlsScalar::random(&mut rand::thread_rng()), 208 | BlsScalar::random(&mut rand::thread_rng()), 209 | ) 210 | .is_ok()); 211 | let mut pi = prover.mut_cs().construct_dense_pi_vec().clone(); 212 | prover.preprocess(&ck)?; 213 | let proof = prover.prove(&ck)?; 214 | 215 | // Verification 216 | let mut verifier = Verifier::new(b"testing"); 217 | circuit( 218 | verifier.mut_cs(), 219 | BlsScalar::random(&mut rand::thread_rng()), 220 | BlsScalar::random(&mut rand::thread_rng()), 221 | ) 222 | .map_err(|_| Error::BlsScalarMalformed)?; 223 | verifier.preprocess(&ck)?; 224 | assert!(verifier.verify(&proof, &vk, &pi).is_err()); 225 | 226 | // Value & value assigned set correctly and != 0. This should pass. 227 | // Proving 228 | prover.clear_witness(); 229 | let rand = BlsScalar::random(&mut rand::thread_rng()); 230 | circuit(prover.mut_cs(), rand, rand).map_err(|_| Error::BlsScalarMalformed)?; 231 | pi = prover.mut_cs().construct_dense_pi_vec().clone(); 232 | let proof = prover.prove(&ck)?; 233 | // This should pass since we sent 1 as selector and the circuit closure should assign the randomly-generated 234 | // value as a result. 235 | verifier.verify(&proof, &vk, &pi) 236 | } 237 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------