arnaucube
arnaucube/gnark-plonky2-verifierPublic Self-hosted repository
gnark-plonky2-verifier/goldilocks/base.go
goldilocks/base.goRaw
  1// This package implements efficient Golidlocks arithmetic operations within Gnark. We do not use
  2// the emulated field arithmetic API, because it is too slow for our purposes. Instead, we use
  3// an efficient reduction method that leverages the fact that the modulus is a simple
  4// linear combination of powers of two.
  5package goldilocks
  6
  7// In general, methods whose name do not contain `NoReduce` can be used without any extra mental
  8// overhead. These methods act exactly as you would expect a normal field would operate.
  9//
 10// However, if you want to aggressively optimize the number of constraints in your circuit, it can
 11// be very beneficial to use the no reduction methods and keep track of the maximum number of bits
 12// your computation uses.
 13
 14import (
 15	"fmt"
 16	"math"
 17	"math/big"
 18
 19	"github.com/consensys/gnark-crypto/field/goldilocks"
 20	"github.com/consensys/gnark/constraint/solver"
 21	"github.com/consensys/gnark/frontend"
 22	"github.com/consensys/gnark/std/math/emulated"
 23	"github.com/consensys/gnark/std/rangecheck"
 24)
 25
 26// The multiplicative group generator of the field.
 27var MULTIPLICATIVE_GROUP_GENERATOR goldilocks.Element = goldilocks.NewElement(7)
 28
 29// The two adicity of the field.
 30var TWO_ADICITY uint64 = 32
 31
 32// The power of two generator of the field.
 33var POWER_OF_TWO_GENERATOR goldilocks.Element = goldilocks.NewElement(1753635133440165772)
 34
 35// The modulus of the field.
 36var MODULUS *big.Int = emulated.Goldilocks{}.Modulus()
 37
 38// The threshold maximum number of bits at which we must reduce the element.
 39var REDUCE_NB_BITS_THRESHOLD uint8 = 254 - 64
 40
 41// The number of bits to use for range checks on inner products of field elements.
 42var RANGE_CHECK_NB_BITS int = 140
 43
 44// Registers the hint functions with the solver.
 45func init() {
 46	solver.RegisterHint(MulAddHint)
 47	solver.RegisterHint(ReduceHint)
 48	solver.RegisterHint(InverseHint)
 49	solver.RegisterHint(SplitLimbsHint)
 50}
 51
 52// A type alias used to represent Goldilocks field elements.
 53type GoldilocksVariable struct {
 54	Limb frontend.Variable
 55}
 56
 57// Creates a new Goldilocks field element from an existing variable. Assumes that the element is
 58// already reduced.
 59func NewVariable(x frontend.Variable) GoldilocksVariable {
 60	return GoldilocksVariable{Limb: x}
 61}
 62
 63// The zero element in the Golidlocks field.
 64func Zero() GoldilocksVariable {
 65	return NewVariable(0)
 66}
 67
 68// The one element in the Goldilocks field.
 69func One() GoldilocksVariable {
 70	return NewVariable(1)
 71}
 72
 73// The negative one element in the Goldilocks field.
 74func NegOne() GoldilocksVariable {
 75	return NewVariable(MODULUS.Uint64() - 1)
 76}
 77
 78// The chip used for Goldilocks field operations.
 79type GoldilocksApi struct {
 80	api          frontend.API
 81	rangeChecker frontend.Rangechecker
 82}
 83
 84// Creates a new Goldilocks chip.
 85func NewGoldilocksApi(api frontend.API) *GoldilocksApi {
 86	rangeChecker := rangecheck.New(api)
 87	return &GoldilocksApi{api: api, rangeChecker: rangeChecker}
 88}
 89
 90// Adds two field elements such that x + y = z within the Golidlocks field.
 91func (p *GoldilocksApi) Add(a GoldilocksVariable, b GoldilocksVariable) GoldilocksVariable {
 92	return p.MulAdd(a, NewVariable(1), b)
 93}
 94
 95// Adds two field elements such that x + y = z within the Golidlocks field without reducing.
 96func (p *GoldilocksApi) AddNoReduce(a GoldilocksVariable, b GoldilocksVariable) GoldilocksVariable {
 97	return NewVariable(p.api.Add(a.Limb, b.Limb))
 98}
 99
100// Subtracts two field elements such that x + y = z within the Golidlocks field.
101func (p *GoldilocksApi) Sub(a GoldilocksVariable, b GoldilocksVariable) GoldilocksVariable {
102	return p.MulAdd(b, NewVariable(MODULUS.Uint64()-1), a)
103}
104
105// Subtracts two field elements such that x + y = z within the Golidlocks field without reducing.
106func (p *GoldilocksApi) SubNoReduce(a GoldilocksVariable, b GoldilocksVariable) GoldilocksVariable {
107	return NewVariable(p.api.Add(a.Limb, p.api.Mul(b.Limb, MODULUS.Uint64()-1)))
108}
109
110// Multiplies two field elements such that x * y = z within the Golidlocks field.
111func (p *GoldilocksApi) Mul(a GoldilocksVariable, b GoldilocksVariable) GoldilocksVariable {
112	return p.MulAdd(a, b, Zero())
113}
114
115// Multiplies two field elements such that x * y = z within the Golidlocks field without reducing.
116func (p *GoldilocksApi) MulNoReduce(a GoldilocksVariable, b GoldilocksVariable) GoldilocksVariable {
117	return NewVariable(p.api.Mul(a.Limb, b.Limb))
118}
119
120// Multiplies two field elements and adds a field element such that x * y + z = c within the
121// Golidlocks field.
122func (p *GoldilocksApi) MulAdd(a GoldilocksVariable, b GoldilocksVariable, c GoldilocksVariable) GoldilocksVariable {
123	result, err := p.api.Compiler().NewHint(MulAddHint, 2, a.Limb, b.Limb, c.Limb)
124	if err != nil {
125		panic(err)
126	}
127
128	quotient := NewVariable(result[0])
129	remainder := NewVariable(result[1])
130
131	lhs := p.api.Mul(a.Limb, b.Limb)
132	lhs = p.api.Add(lhs, c.Limb)
133	rhs := p.api.Add(p.api.Mul(quotient.Limb, MODULUS), remainder.Limb)
134	p.api.AssertIsEqual(lhs, rhs)
135
136	p.RangeCheck(quotient)
137	p.RangeCheck(remainder)
138	return remainder
139}
140
141// Multiplies two field elements and adds a field element such that x * y + z = c within the
142// Golidlocks field without reducing.
143func (p *GoldilocksApi) MulAddNoReduce(a GoldilocksVariable, b GoldilocksVariable, c GoldilocksVariable) GoldilocksVariable {
144	return p.AddNoReduce(p.MulNoReduce(a, b), c)
145}
146
147// The hint used to compute MulAdd.
148func MulAddHint(_ *big.Int, inputs []*big.Int, results []*big.Int) error {
149	if len(inputs) != 3 {
150		panic("MulAddHint expects 3 input operands")
151	}
152
153	for _, operand := range inputs {
154		if operand.Cmp(MODULUS) >= 0 {
155			panic(fmt.Sprintf("%s is not in the field", operand.String()))
156		}
157	}
158
159	product := new(big.Int).Mul(inputs[0], inputs[1])
160	sum := new(big.Int).Add(product, inputs[2])
161	quotient := new(big.Int).Div(sum, MODULUS)
162	remainder := new(big.Int).Rem(sum, MODULUS)
163
164	results[0] = quotient
165	results[1] = remainder
166
167	return nil
168}
169
170// Reduces a field element x such that x % MODULUS = y.
171func (p *GoldilocksApi) Reduce(x GoldilocksVariable) GoldilocksVariable {
172	// Witness a `quotient` and `remainder` such that:
173	//
174	// 		MODULUS * quotient + remainder = x
175	//
176	// Must check that offset \in [0, MODULUS) and carry \in [0, 2^RANGE_CHECK_NB_BITS) to ensure
177	// that this computation does not overflow. We use 2^RANGE_CHECK_NB_BITS to reduce the cost of the range check
178	//
179	// In other words, we assume that we at most compute a a dot product with dimension at most RANGE_CHECK_NB_BITS - 128.
180
181	result, err := p.api.Compiler().NewHint(ReduceHint, 2, x.Limb)
182	if err != nil {
183		panic(err)
184	}
185
186	quotient := result[0]
187	p.rangeChecker.Check(quotient, RANGE_CHECK_NB_BITS)
188
189	remainder := NewVariable(result[1])
190	p.RangeCheck(remainder)
191	return remainder
192}
193
194// Reduces a field element x such that x % MODULUS = y.
195func (p *GoldilocksApi) ReduceWithMaxBits(x GoldilocksVariable, maxNbBits uint64) GoldilocksVariable {
196	// Witness a `quotient` and `remainder` such that:
197	//
198	// 		MODULUS * quotient + remainder = x
199	//
200	// Must check that remainder \in [0, MODULUS) and quotient \in [0, 2^maxNbBits) to ensure that this
201	// computation does not overflow.
202
203	result, err := p.api.Compiler().NewHint(ReduceHint, 2, x.Limb)
204	if err != nil {
205		panic(err)
206	}
207
208	quotient := result[0]
209	p.rangeChecker.Check(quotient, int(maxNbBits))
210
211	remainder := NewVariable(result[1])
212	p.RangeCheck(remainder)
213	return remainder
214}
215
216// The hint used to compute Reduce.
217func ReduceHint(_ *big.Int, inputs []*big.Int, results []*big.Int) error {
218	if len(inputs) != 1 {
219		panic("ReduceHint expects 1 input operand")
220	}
221	input := inputs[0]
222	quotient := new(big.Int).Div(input, MODULUS)
223	remainder := new(big.Int).Rem(input, MODULUS)
224	results[0] = quotient
225	results[1] = remainder
226	return nil
227}
228
229// Computes the inverse of a field element x such that x * x^-1 = 1.
230func (p *GoldilocksApi) Inverse(x GoldilocksVariable) GoldilocksVariable {
231	result, err := p.api.Compiler().NewHint(InverseHint, 1, x.Limb)
232	if err != nil {
233		panic(err)
234	}
235
236	inverse := NewVariable(result[0])
237	product := p.Mul(inverse, x)
238	p.api.AssertIsEqual(product.Limb, frontend.Variable(1))
239	return inverse
240}
241
242// The hint used to compute Inverse.
243func InverseHint(_ *big.Int, inputs []*big.Int, results []*big.Int) error {
244	if len(inputs) != 1 {
245		panic("InverseHint expects 1 input operand")
246	}
247
248	input := inputs[0]
249	if input.Cmp(MODULUS) == 0 || input.Cmp(MODULUS) == 1 {
250		panic("Input is not in the field")
251	}
252
253	inputGl := goldilocks.NewElement(input.Uint64())
254	resultGl := goldilocks.NewElement(0)
255	resultGl.Inverse(&inputGl)
256
257	result := big.NewInt(0)
258	results[0] = resultGl.BigInt(result)
259
260	return nil
261}
262
263// Computes a field element raised to some power.
264func (p *GoldilocksApi) Exp(x GoldilocksVariable, k *big.Int) GoldilocksVariable {
265	if k.IsUint64() && k.Uint64() == 0 {
266		return One()
267	}
268
269	e := k
270	if k.Sign() == -1 {
271		panic("Unsupported negative exponent. Need to implement inversion.")
272	}
273
274	z := x
275	for i := e.BitLen() - 2; i >= 0; i-- {
276		z = p.Mul(z, z)
277		if e.Bit(i) == 1 {
278			z = p.Mul(z, x)
279		}
280	}
281
282	return z
283}
284
285// The hint used to split a GoldilocksVariable into 2 32 bit limbs.
286func SplitLimbsHint(_ *big.Int, inputs []*big.Int, results []*big.Int) error {
287	if len(inputs) != 1 {
288		panic("SplitLimbsHint expects 1 input operand")
289	}
290
291	// The Goldilocks field element
292	input := inputs[0]
293
294	if input.Cmp(MODULUS) == 0 || input.Cmp(MODULUS) == 1 {
295		return fmt.Errorf("input is not in the field")
296	}
297
298	two_32 := big.NewInt(int64(math.Pow(2, 32)))
299
300	// The most significant bits
301	results[0] = new(big.Int).Quo(input, two_32)
302	// The least significant bits
303	results[1] = new(big.Int).Rem(input, two_32)
304
305	return nil
306}
307
308// Range checks a field element x to be less than the Golidlocks modulus 2 ^ 64 - 2 ^ 32 + 1.
309func (p *GoldilocksApi) RangeCheck(x GoldilocksVariable) {
310	// The Goldilocks' modulus is 2^64 - 2^32 + 1, which is:
311	//
312	// 		1111111111111111111111111111111100000000000000000000000000000001
313	//
314	// in big endian binary. This function will first verify that x is at most 64 bits wide. Then it
315	// checks that if the bits[0:31] (in big-endian) are all 1, then bits[32:64] are all zero.
316
317	// Use the range checker component to range-check the variable.
318	rangeChecker := rangecheck.New(p.api)
319	rangeChecker.Check(x.Limb, 64)
320
321	result, err := p.api.Compiler().NewHint(SplitLimbsHint, 2, x.Limb)
322	if err != nil {
323		panic(err)
324	}
325
326	// We check that this is a valid decomposition of the Goldilock's element and range-check each limb.
327	mostSigBits := result[0]
328	leastSigBits := result[1]
329	p.api.AssertIsEqual(
330		p.api.Add(
331			p.api.Mul(mostSigBits, uint64(math.Pow(2, 32))),
332			leastSigBits,
333		),
334		x.Limb,
335	)
336	rangeChecker.Check(mostSigBits, 32)
337	rangeChecker.Check(leastSigBits, 32)
338
339	// If the most significant bits are all 1, then we need to check that the least significant bits are all zero
340	// in order for element to be less than the Goldilock's modulus.
341	// Otherwise, we don't need to do any checks, since we already know that the element is less than the Goldilocks modulus.
342	shouldCheck := p.api.IsZero(p.api.Sub(mostSigBits, uint64(math.Pow(2, 32))-1))
343	p.api.AssertIsEqual(
344		p.api.Select(
345			shouldCheck,
346			leastSigBits,
347			frontend.Variable(0),
348		),
349		frontend.Variable(0),
350	)
351}
352
353func (p *GoldilocksApi) AssertIsEqual(x, y GoldilocksVariable) {
354	p.api.AssertIsEqual(x.Limb, y.Limb)
355}
356
357// Computes the n'th primitive root of unity for the Goldilocks field.
358func PrimitiveRootOfUnity(nLog uint64) goldilocks.Element {
359	if nLog > TWO_ADICITY {
360		panic("nLog is greater than TWO_ADICITY")
361	}
362	res := goldilocks.NewElement(POWER_OF_TWO_GENERATOR.Uint64())
363	for i := 0; i < int(TWO_ADICITY-nLog); i++ {
364		res.Square(&res)
365	}
366	return res
367}
368
369func TwoAdicSubgroup(nLog uint64) []goldilocks.Element {
370	if nLog > TWO_ADICITY {
371		panic("nLog is greater than GOLDILOCKS_TWO_ADICITY")
372	}
373
374	var res []goldilocks.Element
375	rootOfUnity := PrimitiveRootOfUnity(nLog)
376	res = append(res, goldilocks.NewElement(1))
377
378	for i := 0; i < (1 << nLog); i++ {
379		lastElement := res[len(res)-1]
380		res = append(res, *lastElement.Mul(&lastElement, &rootOfUnity))
381	}
382
383	return res
384}