Skip to content

Commit

Permalink
Add an AllocatedNum addition constraint (#39)
Browse files Browse the repository at this point in the history
* Add AllocatedNum addition and test

* Update addition test
  • Loading branch information
varunthakore authored Oct 22, 2023
1 parent 8f8c6e3 commit 029eaad
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions crates/bellpepper-core/src/gadgets/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,38 @@ impl<Scalar: PrimeField> AllocatedNum<Scalar> {
Ok(bits.into_iter().map(Boolean::from).collect())
}

pub fn add<CS>(&self, mut cs: CS, other: &Self) -> Result<Self, SynthesisError>
where
CS: ConstraintSystem<Scalar>,
{
let mut value = None;

let var = cs.alloc(
|| "sum num",
|| {
let mut tmp = self.value.ok_or(SynthesisError::AssignmentMissing)?;
tmp.add_assign(other.value.ok_or(SynthesisError::AssignmentMissing)?);

value = Some(tmp);

Ok(tmp)
},
)?;

// Constrain: (a + b) * 1 = a + b
cs.enforce(
|| "addition constraint",
|lc| lc + self.variable + other.variable,
|lc| lc + CS::one(),
|lc| lc + var,
);

Ok(AllocatedNum {
value,
variable: var,
})
}

pub fn mul<CS>(&self, mut cs: CS, other: &Self) -> Result<Self, SynthesisError>
where
CS: ConstraintSystem<Scalar>,
Expand Down Expand Up @@ -539,6 +571,27 @@ mod test {
assert!(cs.get("num") == Fr::ONE);
}

#[test]
fn test_num_addition() {
let mut cs = TestConstraintSystem::<Fr>::new();

let mut char = Fr::char();
char[0] -= 1u8;
let mod_minus_one = Fr::from_repr(char);
assert!(bool::from(mod_minus_one.is_some()));
let mod_minus_one = mod_minus_one.unwrap();

let a = AllocatedNum::alloc(cs.namespace(|| "a"), || Ok(mod_minus_one)).unwrap();
let b = AllocatedNum::alloc(cs.namespace(|| "b"), || Ok(Fr::ONE)).unwrap();
let c = a.add(&mut cs, &b).unwrap();

assert!(cs.is_satisfied());
assert!(cs.get("sum num") == Fr::ZERO);
assert!(c.value.unwrap() == Fr::ZERO);
cs.set("sum num", Fr::ONE);
assert!(!cs.is_satisfied());
}

#[test]
fn test_num_squaring() {
let mut cs = TestConstraintSystem::<Fr>::new();
Expand Down

0 comments on commit 029eaad

Please sign in to comment.