gnark-plonky2-verifier/plonky2_verifier/fri.go
plonky2_verifier/fri.goRaw
1package plonky2_verifier
2
3import (
4 "fmt"
5 "gnark-ed25519/field"
6 . "gnark-ed25519/field"
7 "gnark-ed25519/poseidon"
8 "math"
9 "math/big"
10 "math/bits"
11
12 "github.com/consensys/gnark-crypto/field/goldilocks"
13 "github.com/consensys/gnark/frontend"
14)
15
16type FriChip struct {
17 api frontend.API
18 fieldAPI frontend.API
19 qeAPI *QuadraticExtensionAPI
20
21 poseidonChip *poseidon.PoseidonChip
22
23 friParams *FriParams
24 verifierOnlyCircuitData *VerifierOnlyCircuitData
25}
26
27func NewFriChip(api frontend.API, fieldAPI frontend.API, qeAPI *QuadraticExtensionAPI, poseidonChip *poseidon.PoseidonChip, friParams *FriParams) *FriChip {
28 return &FriChip{
29 api: api,
30 fieldAPI: fieldAPI,
31 qeAPI: qeAPI,
32 poseidonChip: poseidonChip,
33 friParams: friParams,
34 }
35}
36
37func (f *FriChip) assertLeadingZeros(powWitness F, friConfig FriConfig) {
38 // Asserts that powWitness'es big-endian bit representation has at least `leading_zeros` leading zeros.
39 // Note that this is assuming that the Goldilocks field is being used. Specfically that the
40 // field is 64 bits long
41 maxPowWitness := uint64(math.Pow(2, float64(64-friConfig.ProofOfWorkBits))) - 1
42 f.fieldAPI.AssertIsLessOrEqual(powWitness, field.NewFieldElement(maxPowWitness))
43}
44
45func (f *FriChip) fromOpeningsAndAlpha(openings *FriOpenings, alpha QuadraticExtension) []QuadraticExtension {
46 // One reduced opening for all openings evaluated at point Zeta.
47 // Another one for all openings evaluated at point Zeta * Omega (which is only PlonkZsNext polynomial)
48
49 reducedOpenings := make([]QuadraticExtension, 0, 2)
50 for _, batch := range openings.Batches {
51 reducedOpenings = append(reducedOpenings, f.qeAPI.ReduceWithPowers(batch.values, alpha))
52 }
53
54 return reducedOpenings
55}
56
57func (f *FriChip) hashOrNoop(data []F) Hash {
58 var elements Hash
59 if len(data) <= 4 {
60 // Pad the data to have a size of 4
61 for i, inputElement := range data {
62 elements[i] = inputElement
63 }
64 for i := len(data); i < 4; i++ {
65 elements[i] = field.ZERO_F
66 }
67
68 return elements
69 } else {
70 hashOutput := f.poseidonChip.HashNToMNoPad(data, 4)
71
72 if len(hashOutput) != len(elements) {
73 panic("The length of hashOutput and elements is different")
74 }
75
76 for i, hashField := range hashOutput {
77 elements[i] = hashField
78 }
79
80 return elements
81 }
82}
83
84func (f *FriChip) verifyMerkleProofToCapWithCapIndex(leafData []F, leafIndexBits []frontend.Variable, capIndexBits []frontend.Variable, merkleCap MerkleCap, proof *MerkleProof) {
85 currentDigest := f.hashOrNoop(leafData)
86 fourZeros := [4]F{field.ZERO_F, field.ZERO_F, field.ZERO_F, field.ZERO_F}
87 for i, sibling := range proof.Siblings {
88 bit := leafIndexBits[i]
89
90 var leftSiblingState poseidon.PoseidonState
91 copy(leftSiblingState[0:4], sibling[0:4])
92 copy(leftSiblingState[4:8], currentDigest[0:4])
93 copy(leftSiblingState[8:12], fourZeros[0:4])
94
95 leftHash := f.poseidonChip.Poseidon(leftSiblingState)
96 var leftHashCompress Hash
97 leftHashCompress[0] = leftHash[0]
98 leftHashCompress[1] = leftHash[1]
99 leftHashCompress[2] = leftHash[2]
100 leftHashCompress[3] = leftHash[3]
101
102 var rightSiblingState poseidon.PoseidonState
103 copy(rightSiblingState[0:4], currentDigest[0:4])
104 copy(rightSiblingState[4:8], sibling[0:4])
105 copy(rightSiblingState[8:12], fourZeros[0:4])
106
107 rightHash := f.poseidonChip.Poseidon(rightSiblingState)
108 var rightHashCompress Hash
109 rightHashCompress[0] = rightHash[0]
110 rightHashCompress[1] = rightHash[1]
111 rightHashCompress[2] = rightHash[2]
112 rightHashCompress[3] = rightHash[3]
113
114 currentDigest = SelectHash(f.fieldAPI, bit, leftHashCompress, rightHashCompress)
115 }
116
117 // We assume that the cap_height is 4. Create two levels of the Lookup2 circuit
118 if len(capIndexBits) != 4 || len(merkleCap) != 16 {
119 panic("capIndexBits length should be 4 and the merkleCap length should be 16")
120 }
121
122 const NUM_LEAF_LOOKUPS = 4
123 var leafLookups [NUM_LEAF_LOOKUPS]Hash
124 // First create the "leaf" lookup2 circuits
125 // The will use the least significant bits of the capIndexBits array
126 for i := 0; i < NUM_LEAF_LOOKUPS; i++ {
127 leafLookups[i] = Lookup2Hash(
128 f.fieldAPI, capIndexBits[0], capIndexBits[1],
129 merkleCap[i*NUM_LEAF_LOOKUPS], merkleCap[i*NUM_LEAF_LOOKUPS+1], merkleCap[i*NUM_LEAF_LOOKUPS+2], merkleCap[i*NUM_LEAF_LOOKUPS+3],
130 )
131 }
132
133 // Use the most 2 significant bits of the capIndexBits array for the "root" lookup
134 merkleCapEntry := Lookup2Hash(f.fieldAPI, capIndexBits[2], capIndexBits[3], leafLookups[0], leafLookups[1], leafLookups[2], leafLookups[3])
135 AssertIsEqualHash(f.fieldAPI, currentDigest, merkleCapEntry)
136}
137
138func (f *FriChip) verifyInitialProof(xIndexBits []frontend.Variable, proof *FriInitialTreeProof, initialMerkleCaps []MerkleCap, capIndexBits []frontend.Variable) {
139 if len(proof.EvalsProofs) != len(initialMerkleCaps) {
140 panic("length of eval proofs in fri proof should equal length of initial merkle caps")
141 }
142
143 for i := 0; i < len(initialMerkleCaps); i++ {
144 evals := proof.EvalsProofs[i].Elements
145 merkleProof := proof.EvalsProofs[i].MerkleProof
146 cap := initialMerkleCaps[i]
147 f.verifyMerkleProofToCapWithCapIndex(evals, xIndexBits, capIndexBits, cap, &merkleProof)
148 }
149}
150
151// / We decompose FRI query indices into bits without verifying that the decomposition given by
152// / the prover is the canonical one. In particular, if `x_index < 2^field_bits - p`, then the
153// / prover could supply the binary encoding of either `x_index` or `x_index + p`, since they are
154// / congruent mod `p`. However, this only occurs with probability
155// / p_ambiguous = (2^field_bits - p) / p
156// / which is small for the field that we use in practice.
157// /
158// / In particular, the soundness error of one FRI query is roughly the codeword rate, which
159// / is much larger than this ambiguous-element probability given any reasonable parameters.
160// / Thus ambiguous elements contribute a negligible amount to soundness error.
161// /
162// / Here we compare the probabilities as a sanity check, to verify the claim above.
163func (f *FriChip) assertNoncanonicalIndicesOK() {
164 numAmbiguousElems := uint64(math.MaxUint64) - goldilocks.Modulus().Uint64() + 1
165 queryError := f.friParams.Config.rate()
166 pAmbiguous := float64(numAmbiguousElems) / float64(goldilocks.Modulus().Uint64())
167
168 // TODO: Check that pAmbiguous value is the same as the one in plonky2 verifier
169 if pAmbiguous >= queryError*1e-5 {
170 panic("A non-negligible portion of field elements are in the range that permits non-canonical encodings. Need to do more analysis or enforce canonical encodings.")
171 }
172}
173
174func (f *FriChip) expFromBitsConstBase(
175 base goldilocks.Element,
176 exponentBits []frontend.Variable,
177) F {
178 product := ONE_F
179 for i, bit := range exponentBits {
180 pow := int64(1 << i)
181 // If the bit is on, we multiply product by base^pow.
182 // We can arithmetize this as:
183 // product *= 1 + bit (base^pow - 1)
184 // product = (base^pow - 1) product bit + product
185 basePow := goldilocks.NewElement(0)
186 basePow.Exp(base, big.NewInt(pow))
187
188 basePowElement := NewFieldElement(basePow.Uint64() - 1)
189
190 product = f.fieldAPI.Add(
191 f.fieldAPI.Mul(
192 basePowElement,
193 product,
194 bit,
195 ),
196 product,
197 ).(F)
198 }
199
200 return product
201}
202
203func (f *FriChip) calculateSubgroupX(
204 xIndexBits []frontend.Variable,
205 nLog uint64,
206) F {
207 // Compute x from its index
208 // `subgroup_x` is `subgroup[x_index]`, i.e., the actual field element in the domain.
209 // TODO - Make these as global values
210 g := field.NewFieldElement(field.GOLDILOCKS_MULTIPLICATIVE_GROUP_GENERATOR.Uint64())
211 base := field.GoldilocksPrimitiveRootOfUnity(nLog)
212
213 // Create a reverse list of xIndexBits
214 xIndexBitsRev := make([]frontend.Variable, 0)
215 for i := len(xIndexBits) - 1; i >= 0; i-- {
216 xIndexBitsRev = append(xIndexBitsRev, xIndexBits[i])
217 }
218
219 product := f.expFromBitsConstBase(base, xIndexBitsRev)
220
221 return f.fieldAPI.Mul(g, product).(F)
222}
223
224func (f *FriChip) friCombineInitial(
225 instance FriInstanceInfo,
226 proof FriInitialTreeProof,
227 friAlpha QuadraticExtension,
228 subgroupX_QE QuadraticExtension,
229 precomputedReducedEval []QuadraticExtension,
230) QuadraticExtension {
231 sum := f.qeAPI.ZERO_QE
232
233 if len(instance.Batches) != len(precomputedReducedEval) {
234 panic("len(openings) != len(precomputedReducedEval)")
235 }
236
237 for i := 0; i < len(instance.Batches); i++ {
238 batch := instance.Batches[i]
239 reducedOpenings := precomputedReducedEval[i]
240
241 point := batch.Point
242 evals := make([]QuadraticExtension, 0)
243 for _, polynomial := range batch.Polynomials {
244 evals = append(
245 evals,
246 QuadraticExtension{proof.EvalsProofs[polynomial.OracleIndex].Elements[polynomial.PolynomialInfo], field.ZERO_F},
247 )
248 }
249
250 reducedEvals := f.qeAPI.ReduceWithPowers(evals, friAlpha)
251 numerator := f.qeAPI.SubExtension(reducedEvals, reducedOpenings)
252 denominator := f.qeAPI.SubExtension(subgroupX_QE, point)
253 sum = f.qeAPI.MulExtension(f.qeAPI.ExpU64Extension(friAlpha, uint64(len(evals))), sum)
254 sum = f.qeAPI.AddExtension(
255 f.qeAPI.DivExtension(
256 numerator,
257 denominator,
258 ),
259 sum,
260 )
261 }
262
263 return f.qeAPI.MulExtension(sum, subgroupX_QE)
264}
265
266func (f *FriChip) finalPolyEval(finalPoly PolynomialCoeffs, point QuadraticExtension) QuadraticExtension {
267 ret := f.qeAPI.ZERO_QE
268 for i := len(finalPoly.Coeffs) - 1; i >= 0; i-- {
269 ret = f.qeAPI.AddExtension(
270 f.qeAPI.MulExtension(
271 ret,
272 point,
273 ),
274 finalPoly.Coeffs[i],
275 )
276 }
277 return ret
278}
279
280func (f *FriChip) computeEvaluation(
281 x F,
282 xIndexWithinCosetBits []frontend.Variable,
283 arityBits uint64,
284 evals []QuadraticExtension,
285 beta QuadraticExtension,
286) QuadraticExtension {
287 arity := 1 << arityBits
288 if (len(evals)) != arity {
289 panic("len(evals) ! arity")
290 }
291
292 g := field.GoldilocksPrimitiveRootOfUnity(arityBits)
293 gInv := goldilocks.NewElement(0)
294 gInv.Exp(g, big.NewInt(int64(arity-1)))
295
296 // The evaluation vector needs to be reordered first. Permute the evals array such that each
297 // element's new index is the bit reverse of it's original index.
298 // TODO: Optimization - Since the size of the evals array should be constant (e.g. 2^arityBits),
299 // we can just hard code the permutation.
300 permutedEvals := make([]QuadraticExtension, len(evals))
301 for i := uint(0); i < uint(len(evals)); i++ {
302 bitLen := bits.Len(i)
303 rightPadLen := arityBits - uint64(bitLen)
304 newIndex := bits.Reverse(i) << rightPadLen
305 permutedEvals[newIndex] = evals[i]
306 }
307
308 // Want `g^(arity - rev_x_index_within_coset)` as in the out-of-circuit version. Compute it
309 // as `(g^-1)^rev_x_index_within_coset`.
310 revXIndexWithinCosetBits := make([]frontend.Variable, len(xIndexWithinCosetBits))
311 for i := 0; i < len(xIndexWithinCosetBits); i++ {
312 revXIndexWithinCosetBits[len(xIndexWithinCosetBits)-1-i] = xIndexWithinCosetBits[i]
313 }
314 start := f.expFromBitsConstBase(gInv, revXIndexWithinCosetBits)
315 cosetStart := f.fieldAPI.Mul(start, x).(F)
316
317 xPoints := make([]F, len(evals))
318 yPoints := permutedEvals
319
320 // TODO: Make g_F a constant
321 g_F := NewFieldElement(g.Uint64())
322 xPoints[0] = cosetStart
323 for i := 1; i < len(evals); i++ {
324 xPoints[i] = f.fieldAPI.Mul(xPoints[i-1], g_F).(F)
325 }
326
327 // TODO: This is n^2. Is there a way to do this better?
328 // Compute the barycentric weights
329 barycentricWeights := make([]F, len(xPoints))
330 for i := 0; i < len(xPoints); i++ {
331 barycentricWeights[i] = ONE_F
332 for j := 0; j < len(xPoints); j++ {
333 if i != j {
334 barycentricWeights[i] = f.fieldAPI.Mul(
335 f.fieldAPI.Sub(xPoints[i], xPoints[j]),
336 barycentricWeights[i],
337 ).(F)
338 }
339 }
340 // Take the inverse of the barycentric weights
341 // TODO: Can provide a witness to this value
342 barycentricWeights[i] = f.fieldAPI.Inverse(barycentricWeights[i]).(F)
343 }
344
345}
346
347func (f *FriChip) verifyQueryRound(
348 instance FriInstanceInfo,
349 challenges *FriChallenges,
350 precomputedReducedEval []QuadraticExtension,
351 initialMerkleCaps []MerkleCap,
352 proof *FriProof,
353 xIndex F,
354 n uint64,
355 nLog uint64,
356 roundProof *FriQueryRound,
357) {
358 f.assertNoncanonicalIndicesOK()
359 xIndexBits := f.fieldAPI.ToBinary(xIndex, int(nLog))
360 capIndexBits := xIndexBits[len(xIndexBits)-int(f.friParams.Config.CapHeight):]
361
362 f.verifyInitialProof(xIndexBits, &roundProof.InitialTreesProof, initialMerkleCaps, capIndexBits)
363
364 subgroupX := f.calculateSubgroupX(
365 xIndexBits,
366 nLog,
367 )
368
369 subgroupX_QE := QuadraticExtension{subgroupX, field.ZERO_F}
370
371 oldEval := f.friCombineInitial(
372 instance,
373 roundProof.InitialTreesProof,
374 challenges.FriAlpha,
375 subgroupX_QE,
376 precomputedReducedEval,
377 )
378
379 for i, arityBits := range f.friParams.ReductionArityBits {
380 evals := roundProof.Steps[i].Evals
381
382 cosetIndexBits := xIndexBits[arityBits:]
383 xIndexWithinCosetBits := xIndexBits[:arityBits]
384
385 // Assumes that the arity bits will be 4. That means that the range of
386 // xIndexWithCoset is [0,2^4-1]. This is based on plonky2's circuit recursive
387 // config: https://github.com/mir-protocol/plonky2/blob/main/plonky2/src/plonk/circuit_data.rs#L63
388 // Will use a two levels tree of 4-selector gadgets.
389 if arityBits != 4 {
390 panic("assuming arity bits is 4")
391 }
392
393 const NUM_LEAF_LOOKUPS = 4
394 var leafLookups [NUM_LEAF_LOOKUPS]QuadraticExtension
395 // First create the "leaf" lookup2 circuits
396 // The will use the least significant bits of the xIndexWithCosetBits array
397 for i := 0; i < NUM_LEAF_LOOKUPS; i++ {
398 leafLookups[i] = f.qeAPI.Lookup2(
399 xIndexWithinCosetBits[0], xIndexWithinCosetBits[1],
400 evals[i*NUM_LEAF_LOOKUPS], evals[i*NUM_LEAF_LOOKUPS+1], evals[i*NUM_LEAF_LOOKUPS+2], evals[i*NUM_LEAF_LOOKUPS+3],
401 )
402 }
403
404 // Use the most 2 significant bits of the xIndexWithCosetBits array for the "root" lookup
405 newEval := f.qeAPI.Lookup2(xIndexWithinCosetBits[2], xIndexWithinCosetBits[3], evals[0], evals[1], evals[2], evals[3])
406 f.qeAPI.AssertIsEqual(newEval, oldEval)
407
408 oldEval := f.computeEvaluation(
409 subgroupX,
410 xIndexWithinCosetBits,
411 arityBits,
412 evals,
413 challenges.FriBetas[i],
414 )
415
416 // Convert evals (array of QE) to fields by taking their 0th degree coefficients
417 fieldEvals := make([]F, len(evals))
418 for j := 0; j < len(evals); j++ {
419 fieldEvals[j] = evals[j][0]
420 }
421 f.verifyMerkleProofToCapWithCapIndex(
422 fieldEvals,
423 cosetIndexBits,
424 capIndexBits,
425 proof.CommitPhaseMerkleCaps[i],
426 &roundProof.Steps[i].MerkleProof,
427 )
428
429 // Update the point x to x^arity.
430 for j := uint64(0); j < arityBits; j++ {
431 subgroupX = f.fieldAPI.Mul(subgroupX, subgroupX).(F)
432 }
433
434 xIndexBits = cosetIndexBits
435 }
436
437 finalPolyEval := f.finalPolyEval(proof.FinalPoly, subgroupX_QE)
438
439 f.qeAPI.AssertIsEqual(oldEval, finalPolyEval)
440}
441
442func (f *FriChip) VerifyFriProof(
443 instance FriInstanceInfo,
444 openings FriOpenings,
445 friChallenges *FriChallenges,
446 initialMerkleCaps []MerkleCap,
447 friProof *FriProof,
448) {
449 // TODO: Check fri config
450 /* if let Some(max_arity_bits) = params.max_arity_bits() {
451 self.check_recursion_config::<C>(max_arity_bits);
452 }
453
454 debug_assert_eq!(
455 params.final_poly_len(),
456 proof.final_poly.len(),
457 "Final polynomial has wrong degree."
458 ); */
459
460 // Check POW
461 f.assertLeadingZeros(friChallenges.FriPowResponse, f.friParams.Config)
462
463 precomputedReducedEvals := f.fromOpeningsAndAlpha(&openings, friChallenges.FriAlpha)
464
465 // Size of the LDE domain.
466 nLog := f.friParams.DegreeBits + f.friParams.Config.RateBits
467 n := uint64(math.Pow(2, float64(nLog)))
468
469 if len(friChallenges.FriQueryIndicies) != len(friProof.QueryRoundProofs) {
470 panic(fmt.Sprintf(
471 "Number of query indices (%d) should equal number of query round proofs (%d)",
472 len(friChallenges.FriQueryIndicies),
473 len(friProof.QueryRoundProofs),
474 ))
475 }
476
477 for idx, xIndex := range friChallenges.FriQueryIndicies {
478 roundProof := friProof.QueryRoundProofs[idx]
479
480 f.verifyQueryRound(
481 instance,
482 friChallenges,
483 precomputedReducedEvals,
484 initialMerkleCaps,
485 friProof,
486 xIndex,
487 n,
488 nLog,
489 &roundProof,
490 )
491 }
492}