Skip to content

Commit

Permalink
fix: emulated ToBits (#731)
Browse files Browse the repository at this point in the history
* test: implement failing test case

* fix: unify emulated ToBits between constant and var
  • Loading branch information
ivokub committed Jun 22, 2023
1 parent ffc3d12 commit 0fdc46e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
44 changes: 44 additions & 0 deletions std/math/emulated/element_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,50 @@ func testAssertIsLessEqualThan[T FieldParams](t *testing.T) {
}, testName[T]())
}

type AssertIsLessEqualThanConstantCiruit[T FieldParams] struct {
L Element[T]
R *big.Int
}

func (c *AssertIsLessEqualThanConstantCiruit[T]) Define(api frontend.API) error {
f, err := NewField[T](api)
if err != nil {
return err
}
R := f.NewElement(c.R)
f.AssertIsLessOrEqual(&c.L, R)
return nil
}

func testAssertIsLessEqualThanConstant[T FieldParams](t *testing.T) {
var fp T
assert := test.NewAssert(t)
assert.Run(func(assert *test.Assert) {
var circuit, witness AssertIsLessEqualThanConstantCiruit[T]
R, _ := rand.Int(rand.Reader, fp.Modulus())
L, _ := rand.Int(rand.Reader, R)
circuit.R = R
witness.R = R
witness.L = ValueOf[T](L)
assert.ProverSucceeded(&circuit, &witness, test.WithCurves(testCurve), test.NoSerialization(), test.WithBackends(backend.GROTH16, backend.PLONK))
}, testName[T]())
assert.Run(func(assert *test.Assert) {
var circuit, witness AssertIsLessEqualThanConstantCiruit[T]
R := new(big.Int).Set(fp.Modulus())
L, _ := rand.Int(rand.Reader, R)
circuit.R = R
witness.R = R
witness.L = ValueOf[T](L)
assert.ProverSucceeded(&circuit, &witness, test.WithCurves(testCurve), test.NoSerialization(), test.WithBackends(backend.GROTH16, backend.PLONK))
}, fmt.Sprintf("overflow/%s", testName[T]()))
}

func TestAssertIsLessEqualThanConstant(t *testing.T) {
testAssertIsLessEqualThanConstant[Goldilocks](t)
testAssertIsLessEqualThanConstant[Secp256k1Fp](t)
testAssertIsLessEqualThanConstant[BN254Fp](t)
}

type AddCircuit[T FieldParams] struct {
A, B, C Element[T]
}
Expand Down
1 change: 0 additions & 1 deletion std/math/emulated/field_binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ func (f *Field[T]) ToBits(a *Element[T]) []frontend.Variable {
f.enforceWidthConditional(a)
ba, aConst := f.constantValue(a)
if aConst {
ba.Mod(ba, f.fParams.Modulus())
res := make([]frontend.Variable, f.fParams.BitsPerLimb()*f.fParams.NbLimbs())
for i := range res {
res[i] = ba.Bit(i)
Expand Down

0 comments on commit 0fdc46e

Please sign in to comment.