Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Rebase dev #95

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ name: Rust
on:
merge_group:
push:
branches: [main]
branches: [main, dev]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
branches: [main]
branches: [main, dev]

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
target
Cargo.lock

# IDE config files
.vscode
.idea
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ members = [

[workspace.dependencies]
blake2s_simd = "1.0.1"
blstrs = "0.7.0"
blstrs = { git="https://github.com/lurk-lab/blstrs.git", branch="dev" }
byteorder = "1"
ff = "0.13.0"
rand_core = "0.6"
Expand Down
30 changes: 30 additions & 0 deletions ThirdPartyNotices.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
THIRD PARTY NOTICES

This repository incorporates material as listed below or described in the code.

------------------------------------------------------------
https://github.com/microsoft/Nova

Licensed under MIT

MIT License

Copyright (c) Microsoft Corporation.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
2 changes: 1 addition & 1 deletion crates/bellpepper-core/src/constraint_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ pub trait ConstraintSystem<Scalar: PrimeField>: Sized + Send {
false
}

/// Extend concatenates thew `other` constraint systems to the receiver, modifying the receiver, whose
/// Extend concatenates the `other` constraint systems to the receiver, modifying the receiver, whose
/// inputs, allocated variables, and constraints will precede those of the `other` constraint system.
/// The primary use case for this is parallel synthesis of circuits which can be decomposed into
/// entirely independent sub-circuits. Each can be synthesized in its own thread, then the
Expand Down
3 changes: 2 additions & 1 deletion crates/bellpepper-core/src/util_cs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::LinearCombination;
use ff::PrimeField;

use crate::LinearCombination;

pub mod test_cs;

pub type Constraint<Scalar> = (
Expand Down
3 changes: 2 additions & 1 deletion crates/bellpepper/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ edition = "2021"
rust-version = "1.66.0"

[dependencies]
bellpepper-core = { version = "0.4", path = "../bellpepper-core" }
bellpepper-core = { version = "0.4" }
byteorder = { workspace = true }
ff = { workspace = true }
itertools = "0.12.0"

[dev-dependencies]
proptest = "1.3.1"
Expand Down
95 changes: 93 additions & 2 deletions crates/bellpepper/src/gadgets/boolean_utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use bellpepper_core::{
boolean::{AllocatedBit, Boolean},
num::Num,
num::{AllocatedNum, Num},
ConstraintSystem, SynthesisError,
};
use ff::PrimeField;
use itertools::Itertools as _;

// Returns a Boolean which is true if any of its arguments are true.
#[macro_export]
Expand Down Expand Up @@ -149,11 +150,86 @@ pub fn and_v<CS: ConstraintSystem<F>, F: PrimeField>(
Ok(and)
}

/// If condition return a otherwise b
pub fn conditionally_select<F: PrimeField, CS: ConstraintSystem<F>>(
mut cs: CS,
a: &AllocatedNum<F>,
b: &AllocatedNum<F>,
condition: &Boolean,
) -> Result<AllocatedNum<F>, SynthesisError> {
let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
if condition
.get_value()
.ok_or(SynthesisError::AssignmentMissing)?
{
a.get_value().ok_or(SynthesisError::AssignmentMissing)
} else {
b.get_value().ok_or(SynthesisError::AssignmentMissing)
}
})?;

// a * condition + b*(1-condition) = c ->
// a * condition - b*condition = c - b
cs.enforce(
|| "conditional select constraint",
|lc| lc + a.get_variable() - b.get_variable(),
|_| condition.lc(CS::one(), F::ONE),
|lc| lc + c.get_variable() - b.get_variable(),
);

Ok(c)
}

/// If condition return a otherwise b
pub fn conditionally_select_slice<F: PrimeField, CS: ConstraintSystem<F>>(
mut cs: CS,
a: &[AllocatedNum<F>],
b: &[AllocatedNum<F>],
condition: &Boolean,
) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
a.iter()
.zip_eq(b.iter())
.enumerate()
.map(|(i, (a, b))| {
conditionally_select(cs.namespace(|| format!("select_{i}")), a, b, condition)
})
.collect::<Result<Vec<AllocatedNum<F>>, SynthesisError>>()
}

#[cfg(test)]
mod tests {
use bellpepper_core::{boolean::Boolean, test_cs::TestConstraintSystem};
use super::*;
use bellpepper_core::{
boolean::{AllocatedBit, Boolean},
num::AllocatedNum,
test_cs::TestConstraintSystem,
};
use blstrs::Scalar as Fr;
use ff::PrimeField;
use proptest::prelude::*;
use rand_xorshift::XorShiftRng;

/// Wrapper struct around a field element that implements additional traits
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FWrap<F>(pub F);

impl<F: PrimeField> Copy for FWrap<F> {}

#[cfg(not(target_arch = "wasm32"))]
/// Trait implementation for generating `FWrap<F>` instances with proptest
impl<F: PrimeField> Arbitrary for FWrap<F> {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;

fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
use rand_core::SeedableRng;

let strategy = any::<[u8; 16]>()
.prop_map(|seed| Self(F::random(XorShiftRng::from_seed(seed))))
.no_shrink();
strategy.boxed()
}
}

proptest! {
#[test]
Expand Down Expand Up @@ -191,5 +267,20 @@ mod tests {
assert_eq!(expected_or2, or2.get_value().unwrap());
assert!(cs.is_satisfied());
}

#[test]
fn test_conditional_selection((f1, f2) in any::<(FWrap<Fr>, FWrap<Fr>)>(), b in any::<bool>()) {
let mut cs = TestConstraintSystem::<Fr>::new();
let a1 = AllocatedNum::alloc_infallible(cs.namespace(|| "f1"), || f1.0);
let a2 = AllocatedNum::alloc_infallible(cs.namespace(|| "f2"), || f2.0);
let cond = Boolean::from(AllocatedBit::alloc(
cs.namespace(|| "condition"),
Some(b),
).unwrap());
let c = conditionally_select(&mut cs, &a1, &a2, &cond).unwrap();
assert!(cs.is_satisfied());
let valid_value = if b { f1.0 } else { f2.0 };
assert_eq!(c.get_value(), Some(valid_value));
}
}
}
4 changes: 4 additions & 0 deletions crates/bellpepper/src/util_cs/bench_cs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ impl<Scalar: PrimeField> BenchCS<Scalar> {
self.a
}

pub fn num_auxiliaries(&self) -> usize {
self.aux
}

pub fn num_inputs(&self) -> usize {
self.inputs
}
Expand Down
6 changes: 4 additions & 2 deletions crates/bellpepper/src/util_cs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
pub use bellpepper_core::{Comparable, Constraint};

pub mod bench_cs;
pub mod metric_cs;
pub mod shape_cs;
pub mod test_shape_cs;
pub mod witness_cs;

pub use bellpepper_core::{Comparable, Constraint};
106 changes: 106 additions & 0 deletions crates/bellpepper/src/util_cs/shape_cs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//! Support for generating R1CS shape.

use bellpepper_core::{ConstraintSystem, Index, LinearCombination, SynthesisError, Variable};
use ff::PrimeField;

/// `ShapeCSConstraint` represent a constraint in a `ShapeCS`.
pub type ShapeCSConstraint<Scalar> = (
LinearCombination<Scalar>,
LinearCombination<Scalar>,
LinearCombination<Scalar>,
);

/// `ShapeCS` is a `ConstraintSystem` for creating `R1CSShape`s for a circuit.
#[derive(Debug)]
pub struct ShapeCS<Scalar: PrimeField> {
/// All constraints added to the `ShapeCS`.
pub constraints: Vec<ShapeCSConstraint<Scalar>>,
inputs: usize,
aux: usize,
}

impl<Scalar: PrimeField> ShapeCS<Scalar> {
/// Create a new, default `ShapeCS`,
pub fn new() -> Self {
Self::default()
}

/// Returns the number of constraints defined for this `ShapeCS`.
pub fn num_constraints(&self) -> usize {
self.constraints.len()
}

/// Returns the number of inputs defined for this `ShapeCS`.
pub fn num_inputs(&self) -> usize {
self.inputs
}

/// Returns the number of aux inputs defined for this `ShapeCS`.
pub fn num_aux(&self) -> usize {
self.aux
}
}

impl<Scalar: PrimeField> Default for ShapeCS<Scalar> {
fn default() -> Self {
Self {
constraints: vec![],
inputs: 1,
aux: 0,
}
}
}

impl<Scalar: PrimeField> ConstraintSystem<Scalar> for ShapeCS<Scalar> {
type Root = Self;

fn alloc<F, A, AR>(&mut self, _annotation: A, _f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<Scalar, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>,
{
self.aux += 1;

Ok(Variable::new_unchecked(Index::Aux(self.aux - 1)))
}

fn alloc_input<F, A, AR>(&mut self, _annotation: A, _f: F) -> Result<Variable, SynthesisError>
where
F: FnOnce() -> Result<Scalar, SynthesisError>,
A: FnOnce() -> AR,
AR: Into<String>,
{
self.inputs += 1;

Ok(Variable::new_unchecked(Index::Input(self.inputs - 1)))
}

fn enforce<A, AR, LA, LB, LC>(&mut self, _annotation: A, a: LA, b: LB, c: LC)
where
A: FnOnce() -> AR,
AR: Into<String>,
LA: FnOnce(LinearCombination<Scalar>) -> LinearCombination<Scalar>,
LB: FnOnce(LinearCombination<Scalar>) -> LinearCombination<Scalar>,
LC: FnOnce(LinearCombination<Scalar>) -> LinearCombination<Scalar>,
{
let a = a(LinearCombination::zero());
let b = b(LinearCombination::zero());
let c = c(LinearCombination::zero());

self.constraints.push((a, b, c));
}

fn push_namespace<NR, N>(&mut self, _name_fn: N)
where
NR: Into<String>,
N: FnOnce() -> NR,
{
}

fn pop_namespace(&mut self) {}

fn get_root(&mut self) -> &mut Self::Root {
self
}
}
Loading
Loading