Skip to content

Commit

Permalink
fix: fix OR computation in case one input is constant and other varia…
Browse files Browse the repository at this point in the history
…ble (#1181)

* test: add regression test

* fix: or for constant input
  • Loading branch information
ivokub authored Jul 11, 2024
1 parent e3f932b commit 111a078
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 16 deletions.
23 changes: 7 additions & 16 deletions frontend/cs/scs/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,9 +351,6 @@ func (builder *builder) Or(a, b frontend.Variable) frontend.Variable {
return 0
}

res := builder.newInternalVariable()
builder.MarkBoolean(res)

// if one input is constant, ensure we put it in b
if aConstant {
a, b = b, a
Expand All @@ -362,20 +359,14 @@ func (builder *builder) Or(a, b frontend.Variable) frontend.Variable {
}

if bConstant {
xa := a.(expr.Term)
// b = b - 1
qL := _b
qL = builder.cs.Sub(qL, builder.tOne)
qL = builder.cs.Mul(qL, xa.Coeff)
// a * (b-1) + res == 0
builder.addPlonkConstraint(sparseR1C{
xa: xa.VID,
xc: res.VID,
qL: qL,
qO: builder.tOne,
})
return res
if builder.cs.IsOne(_b) {
return 1
} else {
return a
}
}
res := builder.newInternalVariable()
builder.MarkBoolean(res)
xa := a.(expr.Term)
xb := b.(expr.Term)
// -a - b + ab + res == 0
Expand Down
33 changes: 33 additions & 0 deletions frontend/cs/scs/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,36 @@ func TestSubSameNoConstraint(t *testing.T) {
t.Fatal("expected 0 constraints")
}
}

type regressionOr struct {
A frontend.Variable
constOr int
constCheck int
}

func (c *regressionOr) Define(api frontend.API) error {
y := api.Or(c.A, c.constOr)
api.AssertIsEqual(y, c.constCheck)
return nil
}

func TestRegressionOr(t *testing.T) {
assert := test.NewAssert(t)
for _, tc := range []struct{ in, o, c int }{
{1, 1, 1}, {0, 1, 1},
{1, 0, 1}, {0, 0, 0},
} {
ccs, err := frontend.Compile(ecc.BN254.ScalarField(), scs.NewBuilder, &regressionOr{constOr: tc.o, constCheck: tc.c})
assert.NoError(err)
w, err := frontend.NewWitness(&regressionOr{
A: tc.in,
}, ecc.BN254.ScalarField())
if err != nil {
t.Error("compile", err)
}
_, err = ccs.Solve(w)
if err != nil {
t.Error("solve", err)
}
}
}

0 comments on commit 111a078

Please sign in to comment.