arnaucube
arnaucube/gnark-plonky2-verifierPublic Self-hosted repository
gnark-plonky2-verifier/fri/fri.go
fri/fri.goRaw
  1package fri
  2
  3import (
  4	"fmt"
  5	"math"
  6	"math/big"
  7	"math/bits"
  8
  9	"github.com/consensys/gnark-crypto/field/goldilocks"
 10	"github.com/consensys/gnark/frontend"
 11	gl "github.com/succinctlabs/gnark-plonky2-verifier/goldilocks"
 12	"github.com/succinctlabs/gnark-plonky2-verifier/poseidon"
 13	"github.com/succinctlabs/gnark-plonky2-verifier/types"
 14	"github.com/succinctlabs/gnark-plonky2-verifier/variables"
 15)
 16
 17type Chip struct {
 18	api               frontend.API             `gnark:"-"`
 19	gl                gl.Chip                  `gnark:"-"`
 20	poseidonBN254Chip *poseidon.BN254Chip      `gnark:"-"`
 21	commonData        *types.CommonCircuitData `gnark:"-"`
 22	friParams         *types.FriParams         `gnark:"-"`
 23}
 24
 25func NewChip(
 26	api frontend.API,
 27	commonData *types.CommonCircuitData,
 28	friParams *types.FriParams,
 29) *Chip {
 30	poseidonBN254Chip := poseidon.NewBN254Chip(api)
 31	return &Chip{
 32		api:               api,
 33		poseidonBN254Chip: poseidonBN254Chip,
 34		commonData:        commonData,
 35		friParams:         friParams,
 36		gl:                *gl.New(api),
 37	}
 38}
 39
 40func (f *Chip) GetInstance(zeta gl.QuadraticExtensionVariable) InstanceInfo {
 41	zetaBatch := BatchInfo{
 42		Point:       zeta,
 43		Polynomials: friAllPolys(f.commonData),
 44	}
 45
 46	g := gl.PrimitiveRootOfUnity(f.commonData.DegreeBits)
 47	zetaNext := f.gl.MulExtension(
 48		gl.NewVariable(g.Uint64()).ToQuadraticExtension(),
 49		zeta,
 50	)
 51
 52	zetaNextBath := BatchInfo{
 53		Point:       zetaNext,
 54		Polynomials: friZSPolys(f.commonData),
 55	}
 56
 57	return InstanceInfo{
 58		Oracles: friOracles(f.commonData),
 59		Batches: []BatchInfo{zetaBatch, zetaNextBath},
 60	}
 61}
 62
 63func (f *Chip) ToOpenings(c variables.OpeningSet) Openings {
 64	values := c.Constants                         // num_constants + 1
 65	values = append(values, c.PlonkSigmas...)     // num_routed_wires
 66	values = append(values, c.Wires...)           // num_wires
 67	values = append(values, c.PlonkZs...)         // num_challenges
 68	values = append(values, c.PartialProducts...) // num_challenges * num_partial_products
 69	values = append(values, c.QuotientPolys...)   // num_challenges * quotient_degree_factor
 70	zetaBatch := OpeningBatch{Values: values}
 71	zetaNextBatch := OpeningBatch{Values: c.PlonkZsNext}
 72	return Openings{Batches: []OpeningBatch{zetaBatch, zetaNextBatch}}
 73}
 74
 75func (f *Chip) assertLeadingZeros(powWitness gl.Variable, friConfig types.FriConfig) {
 76	// Asserts that powWitness'es big-endian bit representation has at least `leading_zeros` leading zeros.
 77	// Note that this is assuming that the Goldilocks field is being used.  Specfically that the
 78	// field is 64 bits long
 79	maxPowWitness := uint64(math.Pow(2, float64(64-friConfig.ProofOfWorkBits))) - 1
 80	reducedPowWitness := f.gl.Reduce(powWitness)
 81	f.api.AssertIsLessOrEqual(reducedPowWitness.Limb, frontend.Variable(maxPowWitness))
 82}
 83
 84func (f *Chip) fromOpeningsAndAlpha(
 85	openings *Openings,
 86	alpha gl.QuadraticExtensionVariable,
 87) []gl.QuadraticExtensionVariable {
 88	// One reduced opening for all openings evaluated at point Zeta.
 89	// Another one for all openings evaluated at point Zeta * Omega (which is only PlonkZsNext polynomial)
 90
 91	reducedOpenings := make([]gl.QuadraticExtensionVariable, 0, 2)
 92	for _, batch := range openings.Batches {
 93		reducedOpenings = append(reducedOpenings, f.gl.ReduceWithPowers(batch.Values, alpha))
 94	}
 95
 96	return reducedOpenings
 97}
 98
 99func (f *Chip) verifyMerkleProofToCapWithCapIndex(
100	leafData []gl.Variable,
101	leafIndexBits []frontend.Variable,
102	capIndexBits []frontend.Variable,
103	merkleCap variables.FriMerkleCap,
104	proof *variables.FriMerkleProof,
105) {
106	currentDigest := f.poseidonBN254Chip.HashOrNoop(leafData)
107	for i, sibling := range proof.Siblings {
108		bit := leafIndexBits[i]
109
110		var inputs poseidon.BN254State
111		inputs[0] = frontend.Variable(0)
112		inputs[1] = frontend.Variable(0)
113		inputs[2] = f.api.Select(bit, sibling, currentDigest)
114		inputs[3] = f.api.Select(bit, currentDigest, sibling)
115		state := f.poseidonBN254Chip.Poseidon(inputs)
116
117		currentDigest = state[0]
118	}
119
120	// We assume that the cap_height is 4.  Create two levels of the Lookup2 circuit
121	if len(capIndexBits) != 4 || len(merkleCap) != 16 {
122		errorMsg, _ := fmt.Printf(
123			"capIndexBits length should be 4 and the merkleCap length should be 16.  Actual values (capIndexBits: %d, merkleCap: %d)\n",
124			len(capIndexBits),
125			len(merkleCap),
126		)
127		panic(errorMsg)
128	}
129
130	const NUM_LEAF_LOOKUPS = 4
131	var leafLookups [NUM_LEAF_LOOKUPS]poseidon.BN254HashOut
132	// First create the "leaf" lookup2 circuits
133	// The will use the least significant bits of the capIndexBits array
134	for i := 0; i < NUM_LEAF_LOOKUPS; i++ {
135		leafLookups[i] = f.api.Lookup2(
136			capIndexBits[0], capIndexBits[1],
137			merkleCap[i*NUM_LEAF_LOOKUPS], merkleCap[i*NUM_LEAF_LOOKUPS+1], merkleCap[i*NUM_LEAF_LOOKUPS+2], merkleCap[i*NUM_LEAF_LOOKUPS+3],
138		)
139	}
140
141	// Use the most 2 significant bits of the capIndexBits array for the "root" lookup
142	merkleCapEntry := f.api.Lookup2(capIndexBits[2], capIndexBits[3], leafLookups[0], leafLookups[1], leafLookups[2], leafLookups[3])
143	f.api.AssertIsEqual(currentDigest, merkleCapEntry)
144}
145
146func (f *Chip) verifyInitialProof(xIndexBits []frontend.Variable, proof *variables.FriInitialTreeProof, initialMerkleCaps []variables.FriMerkleCap, capIndexBits []frontend.Variable) {
147	if len(proof.EvalsProofs) != len(initialMerkleCaps) {
148		panic("length of eval proofs in fri proof should equal length of initial merkle caps")
149	}
150
151	for i := 0; i < len(initialMerkleCaps); i++ {
152		evals := proof.EvalsProofs[i].Elements
153		merkleProof := proof.EvalsProofs[i].MerkleProof
154		cap := initialMerkleCaps[i]
155		f.verifyMerkleProofToCapWithCapIndex(evals, xIndexBits, capIndexBits, cap, &merkleProof)
156	}
157}
158
159func (f *Chip) expFromBitsConstBase(
160	base goldilocks.Element,
161	exponentBits []frontend.Variable,
162) gl.Variable {
163	product := gl.One()
164	for i, bit := range exponentBits {
165		// If the bit is on, we multiply product by base^pow.
166		// We can arithmetize this as:
167		//     product *= 1 + bit (base^pow - 1)
168		//     product = (base^pow - 1) product bit + product
169		pow := int64(1 << i)
170		basePow := goldilocks.NewElement(0)
171		basePow.Exp(base, big.NewInt(pow))
172		basePowVariable := gl.NewVariable(basePow.Uint64() - 1)
173		product = f.gl.Add(
174			f.gl.Mul(
175				f.gl.Mul(
176					basePowVariable,
177					product,
178				),
179				gl.NewVariable(bit),
180			),
181			product,
182		)
183	}
184	return product
185}
186
187func (f *Chip) calculateSubgroupX(
188	xIndexBits []frontend.Variable,
189	nLog uint64,
190) gl.Variable {
191	// Compute x from its index
192	// `subgroup_x` is `subgroup[x_index]`, i.e., the actual field element in the domain.
193	// OPTIMIZE - Make these as global values
194	g := gl.NewVariable(gl.MULTIPLICATIVE_GROUP_GENERATOR.Uint64())
195	base := gl.PrimitiveRootOfUnity(nLog)
196
197	// Create a reverse list of xIndexBits
198	xIndexBitsRev := make([]frontend.Variable, 0)
199	for i := len(xIndexBits) - 1; i >= 0; i-- {
200		xIndexBitsRev = append(xIndexBitsRev, xIndexBits[i])
201	}
202
203	product := f.expFromBitsConstBase(base, xIndexBitsRev)
204
205	return f.gl.Mul(g, product)
206}
207
208func (f *Chip) friCombineInitial(
209	instance InstanceInfo,
210	proof variables.FriInitialTreeProof,
211	friAlpha gl.QuadraticExtensionVariable,
212	subgroupX_QE gl.QuadraticExtensionVariable,
213	precomputedReducedEval []gl.QuadraticExtensionVariable,
214) gl.QuadraticExtensionVariable {
215	sum := gl.ZeroExtension()
216
217	if len(instance.Batches) != len(precomputedReducedEval) {
218		panic("len(openings) != len(precomputedReducedEval)")
219	}
220
221	for i := 0; i < len(instance.Batches); i++ {
222		batch := instance.Batches[i]
223		reducedOpenings := precomputedReducedEval[i]
224
225		point := batch.Point
226		evals := make([]gl.QuadraticExtensionVariable, 0)
227		for _, polynomial := range batch.Polynomials {
228			evals = append(
229				evals,
230				gl.QuadraticExtensionVariable{
231					proof.EvalsProofs[polynomial.OracleIndex].Elements[polynomial.PolynomialInfo],
232					gl.Zero(),
233				},
234			)
235		}
236
237		reducedEvals := f.gl.ReduceWithPowers(evals, friAlpha)
238		numerator := f.gl.SubExtensionNoReduce(reducedEvals, reducedOpenings)
239		denominator := f.gl.SubExtension(subgroupX_QE, point)
240		sum = f.gl.MulExtension(f.gl.ExpExtension(friAlpha, uint64(len(evals))), sum)
241		inv, hasInv := f.gl.InverseExtension(denominator)
242		f.api.AssertIsEqual(hasInv, frontend.Variable(1))
243		sum = f.gl.MulAddExtension(
244			numerator,
245			inv,
246			sum,
247		)
248	}
249
250	return sum
251}
252
253func (f *Chip) finalPolyEval(finalPoly variables.PolynomialCoeffs, point gl.QuadraticExtensionVariable) gl.QuadraticExtensionVariable {
254	ret := gl.ZeroExtension()
255	for i := len(finalPoly.Coeffs) - 1; i >= 0; i-- {
256		ret = f.gl.MulAddExtension(ret, point, finalPoly.Coeffs[i])
257	}
258	return ret
259}
260
261func (f *Chip) interpolate(
262	x gl.QuadraticExtensionVariable,
263	xPoints []gl.QuadraticExtensionVariable,
264	yPoints []gl.QuadraticExtensionVariable,
265	barycentricWeights []gl.QuadraticExtensionVariable,
266) gl.QuadraticExtensionVariable {
267	if len(xPoints) != len(yPoints) || len(xPoints) != len(barycentricWeights) {
268		panic("length of xPoints, yPoints, and barycentricWeights are inconsistent")
269	}
270
271	lX := gl.OneExtension()
272	for i := 0; i < len(xPoints); i++ {
273		lX = f.gl.SubMulExtension(x, xPoints[i], lX)
274	}
275
276	sum := gl.ZeroExtension()
277
278	lookupFromPoints := frontend.Variable(1)
279	for i := 0; i < len(xPoints); i++ {
280		quotient, hasQuotient := f.gl.DivExtension(
281			barycentricWeights[i],
282			f.gl.SubExtension(
283				x,
284				xPoints[i],
285			),
286		)
287
288		lookupFromPoints = f.api.Mul(hasQuotient, lookupFromPoints)
289
290		sum = f.gl.AddExtension(
291			f.gl.MulExtension(
292				yPoints[i],
293				quotient,
294			),
295			sum,
296		)
297	}
298
299	interpolation := f.gl.MulExtension(lX, sum)
300
301	lookupVal := gl.ZeroExtension()
302	// Now check if x is already within the xPoints
303	for i := 0; i < len(xPoints); i++ {
304		lookupVal = f.gl.Lookup(
305			f.gl.IsZero(f.gl.SubExtension(x, xPoints[i])),
306			lookupVal,
307			yPoints[i],
308		)
309	}
310
311	return f.gl.Lookup(lookupFromPoints, lookupVal, interpolation)
312}
313
314func (f *Chip) computeEvaluation(
315	x gl.Variable,
316	xIndexWithinCosetBits []frontend.Variable,
317	arityBits uint64,
318	evals []gl.QuadraticExtensionVariable,
319	beta gl.QuadraticExtensionVariable,
320) gl.QuadraticExtensionVariable {
321	arity := 1 << arityBits
322	if (len(evals)) != arity {
323		panic("len(evals) ! arity")
324	}
325	if arityBits > 8 {
326		panic("currently assuming that arityBits is <= 8")
327	}
328
329	g := gl.PrimitiveRootOfUnity(arityBits)
330	gInv := goldilocks.NewElement(0)
331	gInv.Exp(g, big.NewInt(int64(arity-1)))
332
333	// The evaluation vector needs to be reordered first.  Permute the evals array such that each
334	// element's new index is the bit reverse of it's original index.
335	// OPTIMIZE - Since the size of the evals array should be constant (e.g. 2^arityBits),
336	//        we can just hard code the permutation.
337	permutedEvals := make([]gl.QuadraticExtensionVariable, len(evals))
338	for i := uint8(0); i < uint8(len(evals)); i++ {
339		newIndex := bits.Reverse8(i) >> arityBits
340		permutedEvals[newIndex] = evals[i]
341	}
342
343	// Want `g^(arity - rev_x_index_within_coset)` as in the out-of-circuit version. Compute it
344	// as `(g^-1)^rev_x_index_within_coset`.
345	revXIndexWithinCosetBits := make([]frontend.Variable, len(xIndexWithinCosetBits))
346	for i := 0; i < len(xIndexWithinCosetBits); i++ {
347		revXIndexWithinCosetBits[len(xIndexWithinCosetBits)-1-i] = xIndexWithinCosetBits[i]
348	}
349	start := f.expFromBitsConstBase(gInv, revXIndexWithinCosetBits)
350	cosetStart := f.gl.Mul(start, x)
351
352	xPoints := make([]gl.QuadraticExtensionVariable, len(evals))
353	yPoints := permutedEvals
354
355	// OPTIMIZE: Make g_F a constant
356	g_F := gl.NewVariable(g.Uint64()).ToQuadraticExtension()
357	xPoints[0] = gl.QuadraticExtensionVariable{cosetStart, gl.Zero()}
358	for i := 1; i < len(evals); i++ {
359		xPoints[i] = f.gl.MulExtension(xPoints[i-1], g_F)
360	}
361
362	// OPTIMIZE:  This is n^2.  Is there a way to do this better?
363	// Compute the barycentric weights
364	barycentricWeights := make([]gl.QuadraticExtensionVariable, len(xPoints))
365	for i := 0; i < len(xPoints); i++ {
366		barycentricWeights[i] = gl.OneExtension()
367		for j := 0; j < len(xPoints); j++ {
368			if i != j {
369				barycentricWeights[i] = f.gl.SubMulExtension(
370					xPoints[i],
371					xPoints[j],
372					barycentricWeights[i],
373				)
374			}
375		}
376		// Take the inverse of the barycentric weights
377		// OPTIMIZE: Can provide a witness to this value
378		inv, hasInv := f.gl.InverseExtension(barycentricWeights[i])
379		f.api.AssertIsEqual(hasInv, frontend.Variable(1))
380		barycentricWeights[i] = inv
381	}
382
383	return f.interpolate(beta, xPoints, yPoints, barycentricWeights)
384}
385
386func (f *Chip) verifyQueryRound(
387	instance InstanceInfo,
388	challenges *variables.FriChallenges,
389	precomputedReducedEval []gl.QuadraticExtensionVariable,
390	initialMerkleCaps []variables.FriMerkleCap,
391	proof *variables.FriProof,
392	xIndex gl.Variable,
393	n uint64,
394	nLog uint64,
395	roundProof *variables.FriQueryRound,
396) {
397	// Note assertNoncanonicalIndicesOK does not add any constraints, it's a sanity check on the config
398	assertNoncanonicalIndicesOK(*f.friParams)
399
400	xIndex = f.gl.Reduce(xIndex)
401	xIndexBits := f.api.ToBinary(xIndex.Limb, 64)[0 : f.friParams.DegreeBits+f.friParams.Config.RateBits]
402	capIndexBits := xIndexBits[len(xIndexBits)-int(f.friParams.Config.CapHeight):]
403
404	f.verifyInitialProof(xIndexBits, &roundProof.InitialTreesProof, initialMerkleCaps, capIndexBits)
405
406	subgroupX := f.calculateSubgroupX(
407		xIndexBits,
408		nLog,
409	)
410
411	subgroupX_QE := subgroupX.ToQuadraticExtension()
412
413	oldEval := f.friCombineInitial(
414		instance,
415		roundProof.InitialTreesProof,
416		challenges.FriAlpha,
417		subgroupX_QE,
418		precomputedReducedEval,
419	)
420
421	for i, arityBits := range f.friParams.ReductionArityBits {
422		evals := roundProof.Steps[i].Evals
423
424		cosetIndexBits := xIndexBits[arityBits:]
425		xIndexWithinCosetBits := xIndexBits[:arityBits]
426
427		// Assumes that the arity bits will be 4.  That means that the range of
428		// xIndexWithCoset is [0,2^4-1].  This is based on plonky2's circuit recursive
429		// config:  https://github.com/mir-protocol/plonky2/blob/main/plonky2/src/plonk/circuit_data.rs#L63
430		// Will use a two levels tree of 4-selector gadgets.
431		if arityBits != 4 {
432			panic("assuming arity bits is 4")
433		}
434
435		const NUM_LEAF_LOOKUPS = 4
436		var leafLookups [NUM_LEAF_LOOKUPS]gl.QuadraticExtensionVariable
437		// First create the "leaf" lookup2 circuits
438		// The will use the least significant bits of the xIndexWithCosetBits array
439		for i := 0; i < NUM_LEAF_LOOKUPS; i++ {
440			leafLookups[i] = f.gl.Lookup2(
441				xIndexWithinCosetBits[0],
442				xIndexWithinCosetBits[1],
443				evals[i*NUM_LEAF_LOOKUPS],
444				evals[i*NUM_LEAF_LOOKUPS+1],
445				evals[i*NUM_LEAF_LOOKUPS+2],
446				evals[i*NUM_LEAF_LOOKUPS+3],
447			)
448		}
449
450		// Use the most 2 significant bits of the xIndexWithCosetBits array for the "root" lookup
451		newEval := f.gl.Lookup2(
452			xIndexWithinCosetBits[2],
453			xIndexWithinCosetBits[3],
454			leafLookups[0],
455			leafLookups[1],
456			leafLookups[2],
457			leafLookups[3],
458		)
459
460		f.gl.AssertIsEqual(newEval[0], oldEval[0])
461		f.gl.AssertIsEqual(newEval[1], oldEval[1])
462
463		oldEval = f.computeEvaluation(
464			subgroupX,
465			xIndexWithinCosetBits,
466			arityBits,
467			evals,
468			challenges.FriBetas[i],
469		)
470
471		// Convert evals (array of QE) to fields by taking their 0th degree coefficients
472		fieldEvals := make([]gl.Variable, 0, 2*len(evals))
473		for j := 0; j < len(evals); j++ {
474			fieldEvals = append(fieldEvals, evals[j][0])
475			fieldEvals = append(fieldEvals, evals[j][1])
476		}
477		f.verifyMerkleProofToCapWithCapIndex(
478			fieldEvals,
479			cosetIndexBits,
480			capIndexBits,
481			proof.CommitPhaseMerkleCaps[i],
482			&roundProof.Steps[i].MerkleProof,
483		)
484
485		// Update the point x to x^arity.
486		for j := uint64(0); j < arityBits; j++ {
487			subgroupX = f.gl.Mul(subgroupX, subgroupX)
488		}
489
490		xIndexBits = cosetIndexBits
491	}
492
493	subgroupX_QE = subgroupX.ToQuadraticExtension()
494	finalPolyEval := f.finalPolyEval(proof.FinalPoly, subgroupX_QE)
495
496	f.gl.AssertIsEqual(oldEval[0], finalPolyEval[0])
497	f.gl.AssertIsEqual(oldEval[1], finalPolyEval[1])
498}
499
500func (f *Chip) VerifyFriProof(
501	instance InstanceInfo,
502	openings Openings,
503	friChallenges *variables.FriChallenges,
504	initialMerkleCaps []variables.FriMerkleCap,
505	friProof *variables.FriProof,
506) {
507	// Not adding any constraints but a sanity check on the proof shape matching the friParams (constant).
508	validateFriProofShape(friProof, instance, f.friParams)
509
510	// Check POW
511	f.assertLeadingZeros(friChallenges.FriPowResponse, f.friParams.Config)
512
513	// Check that parameters are coherent. Not adding any constraints but a sanity check
514	// on the proof shape matching the friParams.
515	if int(f.friParams.Config.NumQueryRounds) != len(friProof.QueryRoundProofs) {
516		panic("Number of query rounds does not match config.")
517	}
518
519	precomputedReducedEvals := f.fromOpeningsAndAlpha(&openings, friChallenges.FriAlpha)
520
521	// Size of the LDE domain.
522	nLog := f.friParams.DegreeBits + f.friParams.Config.RateBits
523	n := uint64(math.Pow(2, float64(nLog)))
524
525	if len(friChallenges.FriQueryIndices) != len(friProof.QueryRoundProofs) {
526		panic(fmt.Sprintf(
527			"Number of query indices (%d) should equal number of query round proofs (%d)",
528			len(friChallenges.FriQueryIndices),
529			len(friProof.QueryRoundProofs),
530		))
531	}
532
533	for idx, xIndex := range friChallenges.FriQueryIndices {
534		roundProof := friProof.QueryRoundProofs[idx]
535
536		f.verifyQueryRound(
537			instance,
538			friChallenges,
539			precomputedReducedEvals,
540			initialMerkleCaps,
541			friProof,
542			xIndex,
543			n,
544			nLog,
545			&roundProof,
546		)
547	}
548}