Skip to content

Commit cba2e77

Browse files
kevaundrayholiman
authored andcommitted
crypto, tests/fuzzers: add gnark bn254 precompile methods for fuzzing (#30585)
Makes the gnark precompile methods more amenable to fuzzing
1 parent d7434fa commit cba2e77

File tree

5 files changed

+261
-30
lines changed

5 files changed

+261
-30
lines changed

crypto/bn256/gnark/g1.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package bn256
2+
3+
import (
4+
"math/big"
5+
6+
"github.com/consensys/gnark-crypto/ecc/bn254"
7+
)
8+
9+
// G1 is the affine representation of a G1 group element.
10+
//
11+
// Since this code is used for precompiles, using Jacobian
12+
// points are not beneficial because there are no intermediate
13+
// points to allow us to save on inversions.
14+
//
15+
// Note: We also use this struct so that we can conform to the existing API
16+
// that the precompiles want.
17+
type G1 struct {
18+
inner bn254.G1Affine
19+
}
20+
21+
// Add adds `a` and `b` together, storing the result in `g`
22+
func (g *G1) Add(a, b *G1) {
23+
g.inner.Add(&a.inner, &b.inner)
24+
}
25+
26+
// ScalarMult computes the scalar multiplication between `a` and
27+
// `scalar`, storing the result in `g`
28+
func (g *G1) ScalarMult(a *G1, scalar *big.Int) {
29+
g.inner.ScalarMultiplication(&a.inner, scalar)
30+
}
31+
32+
// Unmarshal deserializes `buf` into `g`
33+
//
34+
// Note: whether the deserialization is of a compressed
35+
// or an uncompressed point, is encoded in the bytes.
36+
//
37+
// For our purpose, the point will always be serialized
38+
// as uncompressed, ie 64 bytes.
39+
//
40+
// This method also checks whether the point is on the
41+
// curve and in the prime order subgroup.
42+
func (g *G1) Unmarshal(buf []byte) (int, error) {
43+
return g.inner.SetBytes(buf)
44+
}
45+
46+
// Marshal serializes the point into a byte slice.
47+
//
48+
// Note: The point is serialized as uncompressed.
49+
func (p *G1) Marshal() []byte {
50+
return p.inner.Marshal()
51+
}

crypto/bn256/gnark/g2.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package bn256
2+
3+
import (
4+
"github.com/consensys/gnark-crypto/ecc/bn254"
5+
)
6+
7+
// G2 is the affine representation of a G2 group element.
8+
//
9+
// Since this code is used for precompiles, using Jacobian
10+
// points are not beneficial because there are no intermediate
11+
// points and G2 in particular is only used for the pairing input.
12+
//
13+
// Note: We also use this struct so that we can conform to the existing API
14+
// that the precompiles want.
15+
type G2 struct {
16+
inner bn254.G2Affine
17+
}
18+
19+
// Unmarshal deserializes `buf` into `g`
20+
//
21+
// Note: whether the deserialization is of a compressed
22+
// or an uncompressed point, is encoded in the bytes.
23+
//
24+
// For our purpose, the point will always be serialized
25+
// as uncompressed, ie 128 bytes.
26+
//
27+
// This method also checks whether the point is on the
28+
// curve and in the prime order subgroup.
29+
func (g *G2) Unmarshal(buf []byte) (int, error) {
30+
return g.inner.SetBytes(buf)
31+
}
32+
33+
// Marshal serializes the point into a byte slice.
34+
//
35+
// Note: The point is serialized as uncompressed.
36+
func (g *G2) Marshal() []byte {
37+
return g.inner.Marshal()
38+
}

crypto/bn256/gnark/gt.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package bn256
2+
3+
import (
4+
"fmt"
5+
"math/big"
6+
7+
"github.com/consensys/gnark-crypto/ecc/bn254"
8+
)
9+
10+
// GT is the affine representation of a GT field element.
11+
//
12+
// Note: GT is not explicitly used in mainline code.
13+
// It is needed for fuzzing.
14+
type GT struct {
15+
inner bn254.GT
16+
}
17+
18+
// Pair compute the optimal Ate pairing between a G1 and
19+
// G2 element.
20+
//
21+
// Note: This method is not explicitly used in mainline code.
22+
// It is needed for fuzzing. It should also be noted,
23+
// that the output of this function may not match other
24+
func Pair(a_ *G1, b_ *G2) *GT {
25+
a := a_.inner
26+
b := b_.inner
27+
28+
pairingOutput, err := bn254.Pair([]bn254.G1Affine{a}, []bn254.G2Affine{b})
29+
30+
if err != nil {
31+
// Since this method is only called during fuzzing, it is okay to panic here.
32+
// We do not return an error to match the interface of the other bn256 libraries.
33+
panic(fmt.Sprintf("gnark/bn254 encountered error: %v", err))
34+
}
35+
36+
return &GT{
37+
inner: pairingOutput,
38+
}
39+
}
40+
41+
// Unmarshal deserializes `buf` into `g`
42+
//
43+
// Note: This method is not explicitly used in mainline code.
44+
// It is needed for fuzzing.
45+
func (g *GT) Unmarshal(buf []byte) error {
46+
return g.inner.SetBytes(buf)
47+
}
48+
49+
// Marshal serializes the point into a byte slice.
50+
//
51+
// Note: This method is not explicitly used in mainline code.
52+
// It is needed for fuzzing.
53+
func (g *GT) Marshal() []byte {
54+
bytes := g.inner.Bytes()
55+
return bytes[:]
56+
}
57+
58+
// Exp raises `base` to the power of `exponent`
59+
//
60+
// Note: This method is not explicitly used in mainline code.
61+
// It is needed for fuzzing.
62+
func (g *GT) Exp(base GT, exponent *big.Int) *GT {
63+
g.inner.Exp(base.inner, exponent)
64+
return g
65+
}

crypto/bn256/gnark/pairing.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package bn256
2+
3+
import (
4+
"github.com/consensys/gnark-crypto/ecc/bn254"
5+
)
6+
7+
// Computes the following relation: ∏ᵢ e(Pᵢ, Qᵢ) =? 1
8+
//
9+
// To explain why gnark returns a (bool, error):
10+
//
11+
// - If the function `e` does not return a result then internally
12+
// an error is returned.
13+
// - If `e` returns a result, then error will be nil,
14+
// but if this value is not `1` then the boolean value will be false
15+
//
16+
// We therefore check for an error, and return false if its non-nil and
17+
// then return the value of the boolean if not.
18+
func PairingCheck(a_ []*G1, b_ []*G2) bool {
19+
a := getInnerG1s(a_)
20+
b := getInnerG2s(b_)
21+
22+
// Assume that len(a) == len(b)
23+
//
24+
// The pairing function will return
25+
// false, if this is not the case.
26+
size := len(a)
27+
28+
// Check if input is empty -- gnark will
29+
// return false on an empty input, however
30+
// the ossified behavior is to return true
31+
// on an empty input, so we add this if statement.
32+
if size == 0 {
33+
return true
34+
}
35+
36+
ok, err := bn254.PairingCheck(a, b)
37+
if err != nil {
38+
return false
39+
}
40+
return ok
41+
}
42+
43+
// getInnerG1s gets the inner gnark G1 elements.
44+
//
45+
// These methods are used for two reasons:
46+
//
47+
// - We use a new type `G1`, so we need to convert from
48+
// []*G1 to []*bn254.G1Affine
49+
// - The gnark API accepts slices of values and not slices of
50+
// pointers to values, so we need to return []bn254.G1Affine
51+
// instead of []*bn254.G1Affine.
52+
func getInnerG1s(pointerSlice []*G1) []bn254.G1Affine {
53+
gnarkValues := make([]bn254.G1Affine, 0, len(pointerSlice))
54+
for _, ptr := range pointerSlice {
55+
if ptr != nil {
56+
gnarkValues = append(gnarkValues, ptr.inner)
57+
}
58+
}
59+
return gnarkValues
60+
}
61+
62+
// getInnerG2s gets the inner gnark G2 elements.
63+
//
64+
// The rationale for this method is the same as `getInnerG1s`.
65+
func getInnerG2s(pointerSlice []*G2) []bn254.G2Affine {
66+
gnarkValues := make([]bn254.G2Affine, 0, len(pointerSlice))
67+
for _, ptr := range pointerSlice {
68+
if ptr != nil {
69+
gnarkValues = append(gnarkValues, ptr.inner)
70+
}
71+
}
72+
return gnarkValues
73+
}

tests/fuzzers/bn256/bn256_fuzz.go

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@ import (
2222
"io"
2323
"math/big"
2424

25-
"github.com/consensys/gnark-crypto/ecc/bn254"
2625
cloudflare "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare"
26+
gnark "github.com/ethereum/go-ethereum/crypto/bn256/gnark"
2727
google "github.com/ethereum/go-ethereum/crypto/bn256/google"
2828
)
2929

30-
func getG1Points(input io.Reader) (*cloudflare.G1, *google.G1, *bn254.G1Affine) {
30+
func getG1Points(input io.Reader) (*cloudflare.G1, *google.G1, *gnark.G1) {
3131
_, xc, err := cloudflare.RandomG1(input)
3232
if err != nil {
3333
// insufficient input
@@ -37,14 +37,14 @@ func getG1Points(input io.Reader) (*cloudflare.G1, *google.G1, *bn254.G1Affine)
3737
if _, err := xg.Unmarshal(xc.Marshal()); err != nil {
3838
panic(fmt.Sprintf("Could not marshal cloudflare -> google: %v", err))
3939
}
40-
xs := new(bn254.G1Affine)
41-
if err := xs.Unmarshal(xc.Marshal()); err != nil {
40+
xs := new(gnark.G1)
41+
if _, err := xs.Unmarshal(xc.Marshal()); err != nil {
4242
panic(fmt.Sprintf("Could not marshal cloudflare -> gnark: %v", err))
4343
}
4444
return xc, xg, xs
4545
}
4646

47-
func getG2Points(input io.Reader) (*cloudflare.G2, *google.G2, *bn254.G2Affine) {
47+
func getG2Points(input io.Reader) (*cloudflare.G2, *google.G2, *gnark.G2) {
4848
_, xc, err := cloudflare.RandomG2(input)
4949
if err != nil {
5050
// insufficient input
@@ -54,14 +54,14 @@ func getG2Points(input io.Reader) (*cloudflare.G2, *google.G2, *bn254.G2Affine)
5454
if _, err := xg.Unmarshal(xc.Marshal()); err != nil {
5555
panic(fmt.Sprintf("Could not marshal cloudflare -> google: %v", err))
5656
}
57-
xs := new(bn254.G2Affine)
58-
if err := xs.Unmarshal(xc.Marshal()); err != nil {
57+
xs := new(gnark.G2)
58+
if _, err := xs.Unmarshal(xc.Marshal()); err != nil {
5959
panic(fmt.Sprintf("Could not marshal cloudflare -> gnark: %v", err))
6060
}
6161
return xc, xg, xs
6262
}
6363

64-
// fuzzAdd fuzzez bn256 addition between the Google and Cloudflare libraries.
64+
// fuzzAdd fuzzes bn256 addition between the Google, Cloudflare and Gnark libraries.
6565
func fuzzAdd(data []byte) int {
6666
input := bytes.NewReader(data)
6767
xc, xg, xs := getG1Points(input)
@@ -72,17 +72,16 @@ func fuzzAdd(data []byte) int {
7272
if yc == nil {
7373
return 0
7474
}
75-
// Ensure both libs can parse the second curve point
75+
// Ensure libs can parse the second curve point
7676
// Add the two points and ensure they result in the same output
7777
rc := new(cloudflare.G1)
7878
rc.Add(xc, yc)
7979

8080
rg := new(google.G1)
8181
rg.Add(xg, yg)
8282

83-
tmpX := new(bn254.G1Jac).FromAffine(xs)
84-
tmpY := new(bn254.G1Jac).FromAffine(ys)
85-
rs := new(bn254.G1Affine).FromJacobian(tmpX.AddAssign(tmpY))
83+
rs := new(gnark.G1)
84+
rs.Add(xs, ys)
8685

8786
if !bytes.Equal(rc.Marshal(), rg.Marshal()) {
8887
panic("add mismatch: cloudflare/google")
@@ -94,8 +93,8 @@ func fuzzAdd(data []byte) int {
9493
return 1
9594
}
9695

97-
// fuzzMul fuzzez bn256 scalar multiplication between the Google and Cloudflare
98-
// libraries.
96+
// fuzzMul fuzzes bn256 scalar multiplication between the Google, Cloudflare
97+
// and Gnark libraries.
9998
func fuzzMul(data []byte) int {
10099
input := bytes.NewReader(data)
101100
pc, pg, ps := getG1Points(input)
@@ -122,15 +121,13 @@ func fuzzMul(data []byte) int {
122121
rg := new(google.G1)
123122
rg.ScalarMult(pg, new(big.Int).SetBytes(buf))
124123

125-
rs := new(bn254.G1Jac)
126-
psJac := new(bn254.G1Jac).FromAffine(ps)
127-
rs.ScalarMultiplication(psJac, new(big.Int).SetBytes(buf))
128-
rsAffine := new(bn254.G1Affine).FromJacobian(rs)
124+
rs := new(gnark.G1)
125+
rs.ScalarMult(ps, new(big.Int).SetBytes(buf))
129126

130127
if !bytes.Equal(rc.Marshal(), rg.Marshal()) {
131128
panic("scalar mul mismatch: cloudflare/google")
132129
}
133-
if !bytes.Equal(rc.Marshal(), rsAffine.Marshal()) {
130+
if !bytes.Equal(rc.Marshal(), rs.Marshal()) {
134131
panic("scalar mul mismatch: cloudflare/gnark")
135132
}
136133
return 1
@@ -150,17 +147,26 @@ func fuzzPair(data []byte) int {
150147
// Pair the two points and ensure they result in the same output
151148
clPair := cloudflare.Pair(pc, tc).Marshal()
152149
gPair := google.Pair(pg, tg).Marshal()
150+
sPair := gnark.Pair(ps, ts).Marshal()
151+
153152
if !bytes.Equal(clPair, gPair) {
154153
panic("pairing mismatch: cloudflare/google")
155154
}
156-
cPair, err := bn254.Pair([]bn254.G1Affine{*ps}, []bn254.G2Affine{*ts})
157-
if err != nil {
158-
panic(fmt.Sprintf("gnark/bn254 encountered error: %v", err))
155+
156+
normalizedClPair := normalizeGTToGnark(clPair).Marshal()
157+
if !bytes.Equal(normalizedClPair, sPair) {
158+
panic("pairing mismatch: cloudflare/gnark")
159159
}
160160

161-
// gnark uses a different pairing algorithm which might produce
162-
// different but also correct outputs, we need to scale the output by s
161+
return 1
162+
}
163163

164+
// normalizeGTToGnark scales a Cloudflare/Google GT element by `s`
165+
// so that it can be compared with a gnark GT point.
166+
//
167+
// For the definition of `s` see 3.5 in https://eprint.iacr.org/2015/192.pdf
168+
func normalizeGTToGnark(cloudflareOrGoogleGT []byte) *gnark.GT {
169+
// Compute s = 2*u(6*u^2 + 3*u + 1)
164170
u, _ := new(big.Int).SetString("0x44e992b44a6909f1", 0)
165171
u_exp2 := new(big.Int).Exp(u, big.NewInt(2), nil) // u^2
166172
u_6_exp2 := new(big.Int).Mul(big.NewInt(6), u_exp2) // 6*u^2
@@ -170,14 +176,12 @@ func fuzzPair(data []byte) int {
170176
u_2 := new(big.Int).Mul(big.NewInt(2), u) // 2*u
171177
s := u_2.Mul(u_2, inner) // 2*u(6*u^2 + 3*u + 1)
172178

173-
gRes := new(bn254.GT)
174-
if err := gRes.SetBytes(clPair); err != nil {
179+
// Scale the Cloudflare/Google GT element by `s`
180+
gRes := new(gnark.GT)
181+
if err := gRes.Unmarshal(cloudflareOrGoogleGT); err != nil {
175182
panic(err)
176183
}
177184
gRes = gRes.Exp(*gRes, s)
178-
if !bytes.Equal(cPair.Marshal(), gRes.Marshal()) {
179-
panic("pairing mismatch: cloudflare/gnark")
180-
}
181185

182-
return 1
186+
return gRes
183187
}

0 commit comments

Comments
 (0)