|
| 1 | +package evmprecompiles |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "math/big" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/consensys/gnark-crypto/ecc" |
| 9 | + "github.com/consensys/gnark-crypto/ecc/secp256r1/ecdsa" |
| 10 | + "github.com/consensys/gnark/frontend" |
| 11 | + "github.com/consensys/gnark/std/math/emulated" |
| 12 | + "github.com/consensys/gnark/test" |
| 13 | +) |
| 14 | + |
| 15 | +type p256verifyCircuit struct { |
| 16 | + MsgHash emulated.Element[emulated.P256Fr] |
| 17 | + R emulated.Element[emulated.P256Fr] |
| 18 | + S emulated.Element[emulated.P256Fr] |
| 19 | + Qx, Qy emulated.Element[emulated.P256Fp] |
| 20 | + Expected frontend.Variable |
| 21 | +} |
| 22 | + |
| 23 | +func (c *p256verifyCircuit) Define(api frontend.API) error { |
| 24 | + res := P256Verify(api, c.MsgHash, c.R, c.S, c.Qx, c.Qy) |
| 25 | + api.AssertIsEqual(c.Expected, res) |
| 26 | + return nil |
| 27 | +} |
| 28 | + |
| 29 | +func TestP256VerifyCircuit(t *testing.T) { |
| 30 | + assert := test.NewAssert(t) |
| 31 | + // key generation |
| 32 | + sk, err := ecdsa.GenerateKey(rand.Reader) |
| 33 | + if err != nil { |
| 34 | + t.Fatal("generate", err) |
| 35 | + } |
| 36 | + pk := sk.PublicKey |
| 37 | + // signing |
| 38 | + msg := []byte("test") |
| 39 | + sigBuf, err := sk.Sign(msg, nil) |
| 40 | + if err != nil { |
| 41 | + t.Fatal("sign", err) |
| 42 | + } |
| 43 | + // verification |
| 44 | + verified, err := sk.PublicKey.Verify(sigBuf, msg, nil) |
| 45 | + if err != nil { |
| 46 | + t.Fatal("verify", err) |
| 47 | + } |
| 48 | + // marshalling |
| 49 | + var sig ecdsa.Signature |
| 50 | + sig.SetBytes(sigBuf[:]) |
| 51 | + var r, s big.Int |
| 52 | + r.SetBytes(sig.R[:]) |
| 53 | + s.SetBytes(sig.S[:]) |
| 54 | + hash := ecdsa.HashToInt(msg) |
| 55 | + var expected frontend.Variable |
| 56 | + if verified { |
| 57 | + expected = 1 |
| 58 | + } |
| 59 | + |
| 60 | + circuit := p256verifyCircuit{} |
| 61 | + witness := p256verifyCircuit{ |
| 62 | + MsgHash: emulated.ValueOf[emulated.P256Fr](hash), |
| 63 | + R: emulated.ValueOf[emulated.P256Fr](r), |
| 64 | + S: emulated.ValueOf[emulated.P256Fr](s), |
| 65 | + Qx: emulated.ValueOf[emulated.P256Fp](pk.A.X), |
| 66 | + Qy: emulated.ValueOf[emulated.P256Fp](pk.A.Y), |
| 67 | + Expected: expected, |
| 68 | + } |
| 69 | + err = test.IsSolved(&circuit, &witness, ecc.BN254.ScalarField()) |
| 70 | + assert.NoError(err) |
| 71 | +} |
0 commit comments