Skip to content

Commit

Permalink
fix xor
Browse files Browse the repository at this point in the history
  • Loading branch information
davidnevadoc committed Jan 25, 2024
1 parent 6e505a9 commit e1e97f7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
21 changes: 12 additions & 9 deletions maingate/src/instructions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,33 +330,36 @@ pub trait MainGateInstructions<F: PrimeField, const WIDTH: usize>: Chip<F> {
.swap_remove(2))
}

/// Assigns new value equal to `1` if `c1 ^ c0 = 1`,
/// equal to `0` if `c1 ^ c0 = 0`
// `new_assigned_value + 2 * c1 * c2 - c1 - c2 = 0`.
/// Returns c0 ^ c1.
/// Enforcing `result + 2 * c1 * c2 - c1 - c2 = 0`.
fn xor(
&self,
ctx: &mut RegionCtx<'_, F>,
c1: &AssignedCondition<F>,
c2: &AssignedCondition<F>,
) -> Result<AssignedCondition<F>, Error> {
// Find the new witness
let c = c1
let result = c1
.value()
.zip(c2.value())
.map(|(c1, c2)| *c1 + *c2 - (F::ONE + F::ONE) * *c1 * *c2);

Ok(self
// The original constraint: `result + 2 * c1 * c2 - c1 - c2 = 0`.
// requires scaling the multiplication by 2, but in this implementation
// it is easier to scale other terms by 1/2.
let result = self
.apply(
ctx,
[
Term::assigned_to_sub(c1),
Term::assigned_to_sub(c2),
Term::unassigned_to_add(c),
Term::Assigned(c1, -F::TWO_INV),
Term::Assigned(c2, -F::TWO_INV),
Term::Unassigned(result, F::TWO_INV),
],
F::ZERO,
CombinationOptionCommon::OneLinerMul.into(),
)?
.swap_remove(2))
.swap_remove(2);
Ok(result)
}

/// Assigns new value that is logic inverse of the given assigned value.
Expand Down
8 changes: 4 additions & 4 deletions maingate/src/main_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1581,10 +1581,10 @@ mod tests {
main_gate.assert_equal(ctx, &out_xor, io[2])?;
}

// for io in nand_io.iter() {
// let out_nand = main_gate.xor(ctx, io[0], io[1])?;
// main_gate.assert_equal(ctx, &out_nand, io[2])?;
// }
for io in nand_io.iter() {
let out_nand = main_gate.nand(ctx, io[0], io[1])?;
main_gate.assert_equal(ctx, &out_nand, io[2])?;
}

Ok(())
},
Expand Down

0 comments on commit e1e97f7

Please sign in to comment.