Skip to content

Commit

Permalink
refactor: Replaced the weak reference with downstreaming constraint s…
Browse files Browse the repository at this point in the history
…ystem reference
  • Loading branch information
alireza-shirzad committed Nov 28, 2024
1 parent 8d57cce commit 6710556
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 77 deletions.
4 changes: 2 additions & 2 deletions relations/src/gr1cs/constraint_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ impl<F: Field> ConstraintSystem<F> {
Err(SynthesisError::AssignmentMissing)
} else {
for (label, predicate) in self.local_predicates.iter() {
if let Some(unsatisfied_constraint) = predicate.which_constraint_is_unsatisfied() {
if let Some(unsatisfied_constraint) = predicate.which_constraint_is_unsatisfied(self) {
let mut trace: String = "".to_string();

Check failure on line 350 in relations/src/gr1cs/constraint_system.rs

View workflow job for this annotation

GitHub Actions / Test (stable)

value assigned to `trace` is never read

Check failure on line 350 in relations/src/gr1cs/constraint_system.rs

View workflow job for this annotation

GitHub Actions / Test (nightly)

value assigned to `trace` is never read

Check warning on line 350 in relations/src/gr1cs/constraint_system.rs

View workflow job for this annotation

GitHub Actions / Check no_std

value assigned to `trace` is never read
#[cfg(feature = "std")]
{
Expand Down Expand Up @@ -629,7 +629,7 @@ impl<F: Field> ConstraintSystem<F> {
pub fn to_matrices(&self) -> crate::gr1cs::Result<BTreeMap<Label, Vec<Matrix<F>>>> {
let mut matrices = BTreeMap::new();
for (label, predicate) in self.local_predicates.iter() {
matrices.insert(label.clone(), predicate.to_matrices());
matrices.insert(label.clone(), predicate.to_matrices(self));
}
Ok(matrices)
}
Expand Down
35 changes: 1 addition & 34 deletions relations/src/gr1cs/constraint_system_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl<F: Field> ConstraintSystemRef<F> {
) -> crate::gr1cs::Result<()> {
if !self.has_predicate(R1CS_PREDICATE_LABEL) {
let r1cs_constraint_system =
PredicateConstraintSystem::new_r1cs_predicate(self.clone())?;
PredicateConstraintSystem::new_r1cs_predicate()?;
self.register_predicate(R1CS_PREDICATE_LABEL, r1cs_constraint_system)?;
}
self.inner()
Expand Down Expand Up @@ -399,36 +399,3 @@ impl<F: Field> ConstraintSystemRef<F> {
// }
}

/// A shared reference to a constraint system that can be stored in high level
/// variables.
#[derive(Debug, Clone)]
pub enum WeakConstraintSystemRef<F: Field> {
/// Represents the case where we *don't* need to allocate variables or
/// enforce constraints. Encountered when operating over constant
/// values.
None,
/// Represents the case where we *do* allocate variables or enforce
/// constraints.
CS(Weak<RefCell<ConstraintSystem<F>>>),
}

impl<F: Field> WeakConstraintSystemRef<F> {
/// Create a new `WeakConstraintSystemRef` from a
/// `Weak<RefCell<ConstraintSystem<F>>>`
pub fn from(cs: ConstraintSystemRef<F>) -> Self {
match cs.inner() {
None => WeakConstraintSystemRef::None,
Some(cs) => WeakConstraintSystemRef::CS(Rc::downgrade(cs)),
}
}

/// Convert a `WeakConstraintSystemRef` to a `ConstraintSystemRef`
/// If the `WeakConstraintSystemRef` is `None`, it will return `None`
/// Otherwise, it will upgrade the weak reference
pub fn to_constraint_system_ref(&self) -> ConstraintSystemRef<F> {
match self {
WeakConstraintSystemRef::CS(ref cs) => ConstraintSystemRef::CS(cs.upgrade().unwrap()),
WeakConstraintSystemRef::None => ConstraintSystemRef::None,
}
}
}
48 changes: 12 additions & 36 deletions relations/src/gr1cs/local_predicate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
pub mod polynomial_constraint;

use super::{
Constraint, ConstraintSystemRef, LcIndex, LinearCombination, Matrix, WeakConstraintSystemRef,
Constraint, ConstraintSystem, ConstraintSystemRef, LcIndex, LinearCombination, Matrix,

Check failure on line 9 in relations/src/gr1cs/local_predicate/mod.rs

View workflow job for this annotation

GitHub Actions / Test (stable)

unused import: `ConstraintSystemRef`

Check failure on line 9 in relations/src/gr1cs/local_predicate/mod.rs

View workflow job for this annotation

GitHub Actions / Test (nightly)

unused import: `ConstraintSystemRef`

Check warning on line 9 in relations/src/gr1cs/local_predicate/mod.rs

View workflow job for this annotation

GitHub Actions / Check no_std

unused import: `ConstraintSystemRef`
};
use crate::utils::{error::SynthesisError::ArityMismatch, variable::Variable::SymbolicLc};
use ark_ff::Field;
Expand Down Expand Up @@ -51,10 +51,6 @@ impl<F: Field> Predicate<F> for LocalPredicate<F> {
/// A constraint system that enforces a predicate
#[derive(Debug, Clone)]
pub struct PredicateConstraintSystem<F: Field> {
/// A reference to the global constraint system that this predicate is
/// associated with
global_cs: WeakConstraintSystemRef<F>,

/// The list of linear combinations for each arguments of the predicate
/// The length of this list is equal to the arity of the predicate
/// Each element in the list has size equal to the number of constraints
Expand All @@ -69,35 +65,25 @@ pub struct PredicateConstraintSystem<F: Field> {

impl<F: Field> PredicateConstraintSystem<F> {
/// Create a new predicate constraint system with a specific predicate
fn new(
global_cs: WeakConstraintSystemRef<F>,
local_predicate: LocalPredicate<F>,
) -> Self {
fn new(local_predicate: LocalPredicate<F>) -> Self {
Self {
global_cs,
argument_lcs: vec![Vec::new(); local_predicate.arity()],
local_predicate,
num_constraints: 0,
}
}

/// Create new polynomial predicate constraint system
pub fn new_polynomial_predicate(
cs: WeakConstraintSystemRef<F>,
arity: usize,
terms: Vec<(F, Vec<(usize, usize)>)>,
) -> Self {
Self::new(
cs,
LocalPredicate::Polynomial(PolynomialPredicate::new(arity, terms)),
)
pub fn new_polynomial_predicate(arity: usize, terms: Vec<(F, Vec<(usize, usize)>)>) -> Self {
Self::new(LocalPredicate::Polynomial(PolynomialPredicate::new(
arity, terms,
)))
}

/// creates an R1CS predicate which is a special kind of polynomial
/// predicate
pub fn new_r1cs_predicate(cs: ConstraintSystemRef<F>) -> crate::utils::Result<Self> {
pub fn new_r1cs_predicate() -> crate::utils::Result<Self> {
Ok(Self::new_polynomial_predicate(
WeakConstraintSystemRef::from(cs),
3,
vec![
(F::from(1u8), vec![(0, 1), (1, 1)]),
Expand Down Expand Up @@ -158,15 +144,11 @@ impl<F: Field> PredicateConstraintSystem<F> {

/// Check if the constraints enforced by this predicate are satisfied
/// i.e. L(x_1, x_2, ..., x_n) = 0
pub fn which_constraint_is_unsatisfied(&self) -> Option<usize> {
pub fn which_constraint_is_unsatisfied(&self, cs: &ConstraintSystem<F>) -> Option<usize> {
for (i, constraint) in self.iter_constraints().enumerate() {
let variables: Vec<F> = constraint
.iter()
.map(|lc_index| {
self.get_global_cs()
.assigned_value(SymbolicLc(*lc_index))
.unwrap()
})
.map(|lc_index| cs.assigned_value(SymbolicLc(*lc_index)).unwrap())
.collect();
let result = self.local_predicate.evaluate(&variables);
if result {
Expand All @@ -177,21 +159,15 @@ impl<F: Field> PredicateConstraintSystem<F> {
}

/// Create the set of matrices for this predicate constraint system
pub fn to_matrices(&self) -> Vec<Matrix<F>> {
let global_cs = self.get_global_cs();
pub fn to_matrices(&self, cs: &ConstraintSystem<F>) -> Vec<Matrix<F>> {
let mut matrices: Vec<Matrix<F>> = vec![Vec::new(); self.get_arity()];
for constraint in self.iter_constraints() {
for (matrix_ind, lc_index) in constraint.iter().enumerate() {
let lc: LinearCombination<F> = global_cs.get_lc(*lc_index).unwrap();
let row: Vec<(F, usize)> = global_cs.make_row(&lc).unwrap();
let lc: LinearCombination<F> = cs.get_lc(*lc_index).unwrap();
let row: Vec<(F, usize)> = cs.make_row(&lc);
matrices[matrix_ind].push(row);
}
}
matrices
}


pub fn get_global_cs(&self) -> ConstraintSystemRef<F> {
self.global_cs.to_constraint_system_ref()
}
}
2 changes: 1 addition & 1 deletion relations/src/gr1cs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub use ark_ff::{Field, ToConstraintField};
pub use crate::{
gr1cs::{
constraint_system::ConstraintSystem,
constraint_system_ref::{ConstraintSystemRef, WeakConstraintSystemRef},
constraint_system_ref::{ConstraintSystemRef},
local_predicate::polynomial_constraint::R1CS_PREDICATE_LABEL
},
lc,
Expand Down
5 changes: 1 addition & 4 deletions relations/src/gr1cs/tests/circuit1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
use ark_ff::Field;
use ark_std::{collections::BTreeMap, string::ToString, vec::Vec};

use super::{Label, Matrix, WeakConstraintSystemRef};
use super::{Label, Matrix};

#[derive(Debug, Clone)]
pub struct Circuit1<F: Field> {
Expand Down Expand Up @@ -80,7 +80,6 @@ impl<F: Field + core::convert::From<i8>> ConstraintSynthesizer<F> for Circuit1<F
// Local predicate declarations -> Polynomial predicates

let local_predicate_a = PredicateConstraintSystem::new_polynomial_predicate(
WeakConstraintSystemRef::from(cs.clone()),
4,
vec![
(F::from(1u8), vec![(0, 1), (1, 1)]),
Expand All @@ -89,7 +88,6 @@ impl<F: Field + core::convert::From<i8>> ConstraintSynthesizer<F> for Circuit1<F
],
);
let local_predicate_b = PredicateConstraintSystem::new_polynomial_predicate(
WeakConstraintSystemRef::from(cs.clone()),
3,
vec![
(F::from(7u8), vec![(1, 1)]),
Expand All @@ -99,7 +97,6 @@ impl<F: Field + core::convert::From<i8>> ConstraintSynthesizer<F> for Circuit1<F
);

let local_predicate_c = PredicateConstraintSystem::new_polynomial_predicate(
WeakConstraintSystemRef::from(cs.clone()),
3,
vec![
(F::from(1u8), vec![(0, 1), (1, 1)]),
Expand Down

0 comments on commit 6710556

Please sign in to comment.