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
10 "github.com/consensys/gnark/frontend"
11)
12
13type FriOpeningBatch struct {
14 values []QuadraticExtension
15}
16
17type FriOpenings struct {
18 Batches []FriOpeningBatch
19}
20
21func (c *OpeningSet) ToFriOpenings() FriOpenings {
22 values := c.Constants
23 values = append(values, c.PlonkSigmas...)
24 values = append(values, c.Wires...)
25 values = append(values, c.PlonkZs...)
26 values = append(values, c.PartialProducts...)
27 values = append(values, c.QuotientPolys...)
28 zetaBatch := FriOpeningBatch{values: values}
29 zetaNextBatch := FriOpeningBatch{values: c.PlonkZsNext}
30 return FriOpenings{Batches: []FriOpeningBatch{zetaBatch, zetaNextBatch}}
31}
32
33type FriChip struct {
34 api frontend.API
35 field frontend.API
36 qe *QuadraticExtensionAPI
37
38 poseidonChip *poseidon.PoseidonChip
39
40 friParams *FriParams
41 verifierOnlyCircuitData *VerifierOnlyCircuitData
42}
43
44func NewFriChip(api frontend.API, field frontend.API, qe *QuadraticExtensionAPI, poseidonChip *poseidon.PoseidonChip, friParams *FriParams) *FriChip {
45 return &FriChip{
46 api: api,
47 field: field,
48 qe: qe,
49 poseidonChip: poseidonChip,
50 friParams: friParams,
51 }
52}
53
54func (f *FriChip) assertLeadingZeros(powWitness F, friConfig FriConfig) {
55 // Asserts that powWitness'es big-endian bit representation has at least `leading_zeros` leading zeros.
56 // Note that this is assuming that the Goldilocks field is being used. Specfically that the
57 // field is 64 bits long
58 maxPowWitness := uint64(math.Pow(2, float64(64-friConfig.ProofOfWorkBits))) - 1
59 f.field.AssertIsLessOrEqual(powWitness, field.NewFieldElement(maxPowWitness))
60}
61
62func (f *FriChip) fromOpeningsAndAlpha(openings *FriOpenings, alpha QuadraticExtension) []QuadraticExtension {
63 // One reduced opening for all openings evaluated at point Zeta.
64 // Another one for all openings evaluated at point Zeta * Omega (which is only PlonkZsNext polynomial)
65
66 reducedOpenings := make([]QuadraticExtension, 0, 2)
67 for _, batch := range openings.Batches {
68 reducedOpenings = append(reducedOpenings, reduceWithPowers(f.qe, batch.values, alpha))
69 }
70
71 return reducedOpenings
72}
73
74func (f *FriChip) hashOrNoop(data []F) Hash {
75 var elements Hash
76 if len(data) <= 4 {
77 // Pad the data to have a size of 4
78 for i, inputElement := range data {
79 elements[i] = inputElement
80 }
81 for i := len(data); i < 4; i++ {
82 elements[i] = f.qe.ZERO_F
83 }
84
85 return elements
86 } else {
87 hashOutput := f.poseidonChip.HashNToMNoPad(data, 4)
88
89 if len(hashOutput) != len(elements) {
90 panic("The length of hashOutput and elements is different")
91 }
92
93 for i, hashField := range hashOutput {
94 elements[i] = hashField
95 }
96
97 return elements
98 }
99}
100
101func (f *FriChip) verifyMerkleProofToCapWithCapIndex(leafData []F, leafIndexBits []frontend.Variable, capIndexBits []frontend.Variable, merkleCap MerkleCap, proof *MerkleProof) {
102 currentDigest := f.hashOrNoop(leafData)
103 fourZeros := [4]F{f.qe.ZERO_F, f.qe.ZERO_F, f.qe.ZERO_F, f.qe.ZERO_F}
104 for i, sibling := range proof.Siblings {
105 bit := leafIndexBits[i]
106
107 var leftSiblingState poseidon.PoseidonState
108 copy(leftSiblingState[0:4], sibling[0:4])
109 copy(leftSiblingState[4:8], currentDigest[0:4])
110 copy(leftSiblingState[8:12], fourZeros[0:4])
111
112 leftHash := f.poseidonChip.Poseidon(leftSiblingState)
113 var leftHashCompress Hash
114 leftHashCompress[0] = leftHash[0]
115 leftHashCompress[1] = leftHash[1]
116 leftHashCompress[2] = leftHash[2]
117 leftHashCompress[3] = leftHash[3]
118
119 var rightSiblingState poseidon.PoseidonState
120 copy(rightSiblingState[0:4], currentDigest[0:4])
121 copy(rightSiblingState[4:8], sibling[0:4])
122 copy(rightSiblingState[8:12], fourZeros[0:4])
123
124 rightHash := f.poseidonChip.Poseidon(rightSiblingState)
125 var rightHashCompress Hash
126 rightHashCompress[0] = rightHash[0]
127 rightHashCompress[1] = rightHash[1]
128 rightHashCompress[2] = rightHash[2]
129 rightHashCompress[3] = rightHash[3]
130
131 currentDigest = SelectHash(f.field, bit, leftHashCompress, rightHashCompress)
132 }
133
134 // We assume that the cap_height is 4. Create two levels of the Lookup2 circuit
135 if len(capIndexBits) != 4 || len(merkleCap) != 16 {
136 panic("capIndexBits length should be 4 and the merkleCap length should be 16")
137 }
138
139 const NUM_LEAF_LOOKUPS = 4
140 var leafLookups [NUM_LEAF_LOOKUPS]Hash
141 // First create the "leaf" lookup2 circuits
142 // The will use the least significant bits of the capIndexBits array
143 for i := 0; i < NUM_LEAF_LOOKUPS; i++ {
144 leafLookups[i] = Lookup2Hash(
145 f.field, capIndexBits[0], capIndexBits[1],
146 merkleCap[i*NUM_LEAF_LOOKUPS], merkleCap[i*NUM_LEAF_LOOKUPS+1], merkleCap[i*NUM_LEAF_LOOKUPS+2], merkleCap[i*NUM_LEAF_LOOKUPS+3],
147 )
148 }
149
150 // Use the most 2 significant bits of the capIndexBits array for the "root" lookup
151 merkleCapEntry := Lookup2Hash(f.field, capIndexBits[2], capIndexBits[3], leafLookups[0], leafLookups[1], leafLookups[2], leafLookups[3])
152 AssertIsEqualHash(f.field, currentDigest, merkleCapEntry)
153}
154
155func (f *FriChip) verifyInitialProof(xIndexBits []frontend.Variable, proof *FriInitialTreeProof, initialMerkleCaps []MerkleCap, capIndexBits []frontend.Variable) {
156 if len(proof.EvalsProofs) != len(initialMerkleCaps) {
157 panic("length of eval proofs in fri proof should equal length of initial merkle caps")
158 }
159
160 for i := 0; i < len(initialMerkleCaps); i++ {
161 evals := proof.EvalsProofs[i].Elements
162 merkleProof := proof.EvalsProofs[i].MerkleProof
163 cap := initialMerkleCaps[i]
164 f.verifyMerkleProofToCapWithCapIndex(evals, xIndexBits, capIndexBits, cap, &merkleProof)
165 }
166}
167
168// / We decompose FRI query indices into bits without verifying that the decomposition given by
169// / the prover is the canonical one. In particular, if `x_index < 2^field_bits - p`, then the
170// / prover could supply the binary encoding of either `x_index` or `x_index + p`, since they are
171// / congruent mod `p`. However, this only occurs with probability
172// / p_ambiguous = (2^field_bits - p) / p
173// / which is small for the field that we use in practice.
174// /
175// / In particular, the soundness error of one FRI query is roughly the codeword rate, which
176// / is much larger than this ambiguous-element probability given any reasonable parameters.
177// / Thus ambiguous elements contribute a negligible amount to soundness error.
178// /
179// / Here we compare the probabilities as a sanity check, to verify the claim above.
180func (f *FriChip) assertNoncanonicalIndicesOK() {
181 numAmbiguousElems := uint64(math.MaxUint64) - EmulatedFieldModulus().Uint64() + 1
182 queryError := f.friParams.Config.rate()
183 pAmbiguous := float64(numAmbiguousElems) / float64(EmulatedFieldModulus().Uint64())
184
185 // TODO: Check that pAmbiguous value is the same as the one in plonky2 verifier
186 if pAmbiguous >= queryError*1e-5 {
187 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.")
188 }
189}
190
191func (f *FriChip) verifyQueryRound(
192 challenges *FriChallenges,
193 precomputedReducedEval []QuadraticExtension,
194 initialMerkleCaps []MerkleCap,
195 proof *FriProof,
196 xIndex F,
197 n uint64,
198 nLog uint64,
199 roundProof *FriQueryRound,
200) {
201 f.assertNoncanonicalIndicesOK()
202 xIndexBits := f.qe.field.ToBinary(xIndex, int(nLog))
203 capIndexBits := xIndexBits[len(xIndexBits)-int(f.friParams.Config.CapHeight):]
204
205 f.verifyInitialProof(xIndexBits, &roundProof.InitialTreesProof, initialMerkleCaps, capIndexBits)
206}
207
208func (f *FriChip) VerifyFriProof(
209 openings FriOpenings,
210 friChallenges *FriChallenges,
211 initialMerkleCaps []MerkleCap,
212 friProof *FriProof,
213) {
214 // TODO: Check fri config
215 /* if let Some(max_arity_bits) = params.max_arity_bits() {
216 self.check_recursion_config::<C>(max_arity_bits);
217 }
218
219 debug_assert_eq!(
220 params.final_poly_len(),
221 proof.final_poly.len(),
222 "Final polynomial has wrong degree."
223 ); */
224
225 // Check POW
226 f.assertLeadingZeros(friChallenges.FriPowResponse, f.friParams.Config)
227
228 precomputedReducedEvals := f.fromOpeningsAndAlpha(&openings, friChallenges.FriAlpha)
229
230 // Size of the LDE domain.
231 nLog := f.friParams.DegreeBits + f.friParams.Config.RateBits
232 n := uint64(math.Pow(2, float64(nLog)))
233
234 if len(friChallenges.FriQueryIndicies) != len(friProof.QueryRoundProofs) {
235 panic(fmt.Sprintf(
236 "Number of query indices (%d) should equal number of query round proofs (%d)",
237 len(friChallenges.FriQueryIndicies),
238 len(friProof.QueryRoundProofs),
239 ))
240 }
241
242 for idx, xIndex := range friChallenges.FriQueryIndicies {
243 roundProof := friProof.QueryRoundProofs[idx]
244
245 f.verifyQueryRound(
246 friChallenges,
247 precomputedReducedEvals,
248 initialMerkleCaps,
249 friProof,
250 xIndex,
251 n,
252 nLog,
253 &roundProof,
254 )
255 }
256}