gnark
gnark copied to clipboard
Fix Or && Xor
Or and Xor return unexpected values
my circuit
package main
import (
"fmt"
"time"
"github.com/consensys/gnark-crypto/ecc"
"github.com/consensys/gnark/backend/groth16"
"github.com/consensys/gnark/frontend"
"github.com/consensys/gnark/frontend/cs/r1cs"
)
type TestCircuit struct {
A frontend.Variable
B frontend.Variable
}
func (t *TestCircuit) Define(api frontend.API) error {
a := api.ToBinary(t.A, 8)
b := api.ToBinary(t.B, 8)
isZero := make([]frontend.Variable, 8)
for i := 0; i < 8; i++ {
isZero[i] = api.And(a[i], b[i])
}
api.Println(isZero...)
// test or
or := make([]frontend.Variable, 8)
or[0] = api.Sub(1, isZero[0])
for i := 1; i < 8; i++ {
or[i] = api.Or(api.Sub(1, isZero[i]), or[i-1])
}
api.Println(or...)
// test xor
xor := make([]frontend.Variable, 8)
xor[0] = api.Sub(1, isZero[0])
for i := 1; i < 8; i++ {
xor[i] = api.Xor(api.Sub(1, isZero[i]), xor[i-1])
}
api.Println(xor...)
return nil
}
func main() {
var circuit TestCircuit
t := time.Now()
_r1cs, err := frontend.Compile(ecc.BN254, r1cs.NewBuilder, &circuit, frontend.IgnoreUnconstrainedInputs())
if err != nil {
panic(err)
}
internal, secret, public := _r1cs.GetNbVariables()
fmt.Printf("public, secret, internal %v, %v, %v\n", public, secret, internal)
t0 := time.Now()
fmt.Printf("Compilation time: %v\n", t0.Sub(t))
pk, vk, _ := groth16.Setup(_r1cs)
t1 := time.Now()
fmt.Printf("Setup time: %v\n", t1.Sub(t0))
witness, err := frontend.NewWitness(&TestCircuit{
A: 7,
B: 21,
}, ecc.BN254)
if err != nil {
panic(err)
}
t2 := time.Now()
fmt.Printf("Witness time: %v\n", t2.Sub(t1))
proof, err := groth16.Prove(_r1cs, pk, witness)
if err != nil {
panic(err)
}
t3 := time.Now()
fmt.Printf("Prove time: %v\n", t3.Sub(t2))
pubwit, _ := witness.Public()
if err := groth16.Verify(proof, vk, pubwit); err != nil {
panic("verification failed")
}
}
and the log
16:56:43 DBG main.go:27 > 1 0 1 0 0 0 0 0
16:56:43 DBG main.go:35 > 0 2 3 1 1 1 1 1
16:56:43 DBG main.go:43 > 0 2 3 -2 3 -2 3 -2
the expected value
17:00:07 DBG main.go:27 > 1 0 1 0 0 0 0 0
17:00:07 DBG main.go:35 > 0 1 1 1 1 1 1 1
17:00:07 DBG main.go:43 > 0 1 1 0 1 0 1 0