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, capIndex F, merkleCap MerkleCap, proof *MerkleProof) {
102 currentDigest := f.hashOrNoop(leafData)
103
104 if len(leafIndexBits) != len(proof.Siblings) {
105 panic("len(leafIndexBits) != len(proof.Siblings)")
106 }
107
108 fourZeros := [4]F{f.qe.ZERO_F, f.qe.ZERO_F, f.qe.ZERO_F, f.qe.ZERO_F}
109 for i, bit := range leafIndexBits {
110 sibling := proof.Siblings[i]
111
112 var leftSiblingState poseidon.PoseidonState
113 copy(leftSiblingState[0:4], sibling[0:4])
114 copy(leftSiblingState[4:8], currentDigest[0:4])
115 copy(leftSiblingState[8:12], fourZeros[0:4])
116 leftHash := f.poseidonChip.Poseidon(leftSiblingState)
117 leftHashCompress := leftHash[0:4]
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 rightHash := f.poseidonChip.Poseidon(rightSiblingState)
124 rightHashCompress := rightHash[0:4]
125
126 currentDigest = f.api.Select(bit, leftHashCompress, rightHashCompress).(Hash)
127 }
128}
129
130func (f *FriChip) verifyInitialProof(xIndexBits []frontend.Variable, proof *FriInitialTreeProof, initialMerkleCaps []MerkleCap, capIndex F) {
131 if len(proof.EvalsProofs) != len(initialMerkleCaps) {
132 panic("length of eval proofs in fri proof should equal length of initial merkle caps")
133 }
134
135 for i := 0; i < len(initialMerkleCaps); i++ {
136 evals := proof.EvalsProofs[i].Elements
137 merkleProof := proof.EvalsProofs[i].MerkleProof
138 cap := initialMerkleCaps[i]
139 f.verifyMerkleProofToCapWithCapIndex(evals, xIndexBits, capIndex, cap, &merkleProof)
140 }
141}
142
143// / We decompose FRI query indices into bits without verifying that the decomposition given by
144// / the prover is the canonical one. In particular, if `x_index < 2^field_bits - p`, then the
145// / prover could supply the binary encoding of either `x_index` or `x_index + p`, since they are
146// / congruent mod `p`. However, this only occurs with probability
147// / p_ambiguous = (2^field_bits - p) / p
148// / which is small for the field that we use in practice.
149// /
150// / In particular, the soundness error of one FRI query is roughly the codeword rate, which
151// / is much larger than this ambiguous-element probability given any reasonable parameters.
152// / Thus ambiguous elements contribute a negligible amount to soundness error.
153// /
154// / Here we compare the probabilities as a sanity check, to verify the claim above.
155func (f *FriChip) assertNoncanonicalIndicesOK() {
156 numAmbiguousElems := uint64(math.MaxUint64) - EmulatedFieldModulus().Uint64() + 1
157 queryError := f.friParams.Config.rate()
158 pAmbiguous := float64(numAmbiguousElems) / float64(EmulatedFieldModulus().Uint64())
159
160 // TODO: Check that pAmbiguous value is the same as the one in plonky2 verifier
161 if pAmbiguous >= queryError*1e-5 {
162 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.")
163 }
164}
165
166func (f *FriChip) verifyQueryRound(
167 challenges *FriChallenges,
168 precomputedReducedEval []QuadraticExtension,
169 initialMerkleCaps []MerkleCap,
170 proof *FriProof,
171 xIndex F,
172 n uint64,
173 nLog uint64,
174 roundProof *FriQueryRound,
175) {
176 f.assertNoncanonicalIndicesOK()
177 xIndexBits := f.qe.field.ToBinary(xIndex, int(nLog))
178 capIndex := f.qe.field.FromBinary(xIndexBits[len(xIndexBits)-int(f.friParams.Config.CapHeight):]...).(F)
179
180 f.verifyInitialProof(xIndexBits, &roundProof.InitialTreesProof, initialMerkleCaps, capIndex)
181}
182
183func (f *FriChip) VerifyFriProof(
184 openings FriOpenings,
185 friChallenges *FriChallenges,
186 initialMerkleCaps []MerkleCap,
187 friProof *FriProof,
188) {
189 // TODO: Check fri config
190 /* if let Some(max_arity_bits) = params.max_arity_bits() {
191 self.check_recursion_config::<C>(max_arity_bits);
192 }
193
194 debug_assert_eq!(
195 params.final_poly_len(),
196 proof.final_poly.len(),
197 "Final polynomial has wrong degree."
198 ); */
199
200 // Check POW
201 f.assertLeadingZeros(friChallenges.FriPowResponse, f.friParams.Config)
202
203 precomputedReducedEvals := f.fromOpeningsAndAlpha(&openings, friChallenges.FriAlpha)
204
205 // Size of the LDE domain.
206 nLog := f.friParams.DegreeBits + f.friParams.Config.RateBits
207 n := uint64(math.Pow(2, float64(nLog)))
208
209 if len(friChallenges.FriQueryIndicies) != len(friProof.QueryRoundProofs) {
210 panic(fmt.Sprintf(
211 "Number of query indices (%d) should equal number of query round proofs (%d)",
212 len(friChallenges.FriQueryIndicies),
213 len(friProof.QueryRoundProofs),
214 ))
215 }
216
217 for idx, xIndex := range friChallenges.FriQueryIndicies {
218 roundProof := friProof.QueryRoundProofs[idx]
219
220 f.verifyQueryRound(
221 friChallenges,
222 precomputedReducedEvals,
223 initialMerkleCaps,
224 friProof,
225 xIndex,
226 n,
227 nLog,
228 &roundProof,
229 )
230 }
231}