arnaucube
arnaucube/gnark-plonky2-verifierPublic Self-hosted repository
gnark-plonky2-verifier/field/goldilocks.go
field/goldilocks.goRaw
 1package field
 2
 3import (
 4	"github.com/consensys/gnark-crypto/ecc"
 5	"github.com/consensys/gnark-crypto/field/goldilocks"
 6	"github.com/consensys/gnark/frontend"
 7	"github.com/consensys/gnark/std/math/emulated"
 8)
 9
10type EmulatedField = emulated.Goldilocks
11type F = emulated.Element[EmulatedField]
12
13var TEST_CURVE = ecc.BN254
14
15func NewFieldElement(x uint64) F {
16	return emulated.NewElement[EmulatedField](x)
17}
18
19func NewFieldElementFromString(x string) F {
20	return emulated.NewElement[EmulatedField](x)
21}
22
23func NewFieldAPI(api frontend.API) frontend.API {
24	field, err := emulated.NewField[EmulatedField](api)
25	if err != nil {
26		panic(err)
27	}
28	return field
29}
30
31var ONE_F = NewFieldElement(1)
32var ZERO_F = NewFieldElement(0)
33var NEG_ONE_F = NewFieldElement(EmulatedField{}.Modulus().Uint64() - 1)
34
35var GOLDILOCKS_MULTIPLICATIVE_GROUP_GENERATOR = goldilocks.NewElement(7)
36var GOLDILOCKS_TWO_ADICITY = uint64(32)
37var GOLDILOCKS_POWER_OF_TWO_GENERATOR = goldilocks.NewElement(1753635133440165772)
38
39func GoldilocksPrimitiveRootOfUnity(nLog uint64) goldilocks.Element {
40	if nLog > GOLDILOCKS_TWO_ADICITY {
41		panic("nLog is greater than GOLDILOCKS_TWO_ADICITY")
42	}
43
44	res := goldilocks.NewElement(GOLDILOCKS_POWER_OF_TWO_GENERATOR.Uint64())
45	for i := 0; i < int(GOLDILOCKS_TWO_ADICITY-nLog); i++ {
46		res.Square(&res)
47	}
48
49	return res
50}
51
52func TwoAdicSubgroup(nLog uint64) []goldilocks.Element {
53	if nLog > GOLDILOCKS_TWO_ADICITY {
54		panic("nLog is greater than GOLDILOCKS_TWO_ADICITY")
55	}
56
57	var res []goldilocks.Element
58	rootOfUnity := GoldilocksPrimitiveRootOfUnity(nLog)
59	res = append(res, goldilocks.NewElement(1))
60
61	for i := 0; i < (1 << nLog); i++ {
62		lastElement := res[len(res)-1]
63		res = append(res, *lastElement.Mul(&lastElement, &rootOfUnity))
64	}
65
66	return res
67}