/
pedersen.go
317 lines (260 loc) · 8.46 KB
/
pedersen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright 2020 Consensys Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by consensys/gnark-crypto DO NOT EDIT
package pedersen
import (
"crypto/rand"
"crypto/sha256"
"fmt"
"github.com/consensys/gnark-crypto/ecc"
curve "github.com/consensys/gnark-crypto/ecc/bls12-381"
"github.com/consensys/gnark-crypto/ecc/bls12-381/fr"
fiatshamir "github.com/consensys/gnark-crypto/fiat-shamir"
"io"
"math/big"
)
// ProvingKey for committing and proofs of knowledge
type ProvingKey struct {
basis []curve.G1Affine
basisExpSigma []curve.G1Affine
}
type VerifyingKey struct {
g curve.G2Affine // TODO @tabaie: does this really have to be randomized?
gRootSigmaNeg curve.G2Affine //gRootSigmaNeg = g^{-1/σ}
}
func randomFrSizedBytes() ([]byte, error) {
res := make([]byte, fr.Bytes)
_, err := rand.Read(res)
return res, err
}
func randomOnG2() (curve.G2Affine, error) { // TODO: Add to G2.go?
if gBytes, err := randomFrSizedBytes(); err != nil {
return curve.G2Affine{}, err
} else {
return curve.HashToG2(gBytes, []byte("random on g2"))
}
}
func Setup(bases ...[]curve.G1Affine) (pk []ProvingKey, vk VerifyingKey, err error) {
if vk.g, err = randomOnG2(); err != nil {
return
}
var modMinusOne big.Int
modMinusOne.Sub(fr.Modulus(), big.NewInt(1))
var sigma *big.Int
if sigma, err = rand.Int(rand.Reader, &modMinusOne); err != nil {
return
}
sigma.Add(sigma, big.NewInt(1))
var sigmaInvNeg big.Int
sigmaInvNeg.ModInverse(sigma, fr.Modulus())
sigmaInvNeg.Sub(fr.Modulus(), &sigmaInvNeg)
vk.gRootSigmaNeg.ScalarMultiplication(&vk.g, &sigmaInvNeg)
pk = make([]ProvingKey, len(bases))
for i := range bases {
pk[i].basisExpSigma = make([]curve.G1Affine, len(bases[i]))
for j := range bases[i] {
pk[i].basisExpSigma[j].ScalarMultiplication(&bases[i][j], sigma)
}
pk[i].basis = bases[i]
}
return
}
func (pk *ProvingKey) ProveKnowledge(values []fr.Element) (pok curve.G1Affine, err error) {
if len(values) != len(pk.basis) {
err = fmt.Errorf("must have as many values as basis elements")
return
}
// TODO @gbotrel this will spawn more than one task, see
// https://github.com/ConsenSys/gnark-crypto/issues/269
config := ecc.MultiExpConfig{
NbTasks: 1, // TODO Experiment
}
_, err = pok.MultiExp(pk.basisExpSigma, values, config)
return
}
func (pk *ProvingKey) Commit(values []fr.Element) (commitment curve.G1Affine, err error) {
if len(values) != len(pk.basis) {
err = fmt.Errorf("must have as many values as basis elements")
return
}
// TODO @gbotrel this will spawn more than one task, see
// https://github.com/ConsenSys/gnark-crypto/issues/269
config := ecc.MultiExpConfig{
NbTasks: 1,
}
_, err = commitment.MultiExp(pk.basis, values, config)
return
}
// BatchProve generates a single proof of knowledge for multiple commitments for faster verification
func BatchProve(pk []ProvingKey, values [][]fr.Element, fiatshamirSeeds ...[]byte) (pok curve.G1Affine, err error) {
if len(pk) != len(values) {
err = fmt.Errorf("must have as many value vectors as bases")
return
}
if len(pk) == 1 { // no need to fold
return pk[0].ProveKnowledge(values[0])
} else if len(pk) == 0 { // nothing to do at all
return
}
offset := 0
for i := range pk {
if len(values[i]) != len(pk[i].basis) {
err = fmt.Errorf("must have as many values as basis elements")
return
}
offset += len(values[i])
}
var r fr.Element
if r, err = getChallenge(fiatshamirSeeds); err != nil {
return
}
// prepare one amalgamated MSM
scaledValues := make([]fr.Element, offset)
basis := make([]curve.G1Affine, offset)
copy(basis, pk[0].basisExpSigma)
copy(scaledValues, values[0])
offset = len(values[0])
rI := r
for i := 1; i < len(pk); i++ {
copy(basis[offset:], pk[i].basisExpSigma)
for j := range pk[i].basis {
scaledValues[offset].Mul(&values[i][j], &rI)
offset++
}
if i+1 < len(pk) {
rI.Mul(&rI, &r)
}
}
// TODO @gbotrel this will spawn more than one task, see
// https://github.com/ConsenSys/gnark-crypto/issues/269
config := ecc.MultiExpConfig{
NbTasks: 1,
}
_, err = pok.MultiExp(basis, scaledValues, config)
return
}
// FoldCommitments amalgamates multiple commitments into one, which can be verifier against a folded proof obtained from BatchProve
func FoldCommitments(commitments []curve.G1Affine, fiatshamirSeeds ...[]byte) (commitment curve.G1Affine, err error) {
if len(commitments) == 1 { // no need to fold
commitment = commitments[0]
return
} else if len(commitments) == 0 { // nothing to do at all
return
}
r := make([]fr.Element, len(commitments))
r[0].SetOne()
if r[1], err = getChallenge(fiatshamirSeeds); err != nil {
return
}
for i := 2; i < len(commitments); i++ {
r[i].Mul(&r[i-1], &r[1])
}
for i := range commitments { // TODO @Tabaie Remove if MSM does subgroup check for you
if !commitments[i].IsInSubGroup() {
err = fmt.Errorf("subgroup check failed")
return
}
}
// TODO @gbotrel this will spawn more than one task, see
// https://github.com/ConsenSys/gnark-crypto/issues/269
config := ecc.MultiExpConfig{
NbTasks: 1,
}
_, err = commitment.MultiExp(commitments, r, config)
return
}
// Verify checks if the proof of knowledge is valid
func (vk *VerifyingKey) Verify(commitment curve.G1Affine, knowledgeProof curve.G1Affine) error {
if !commitment.IsInSubGroup() || !knowledgeProof.IsInSubGroup() {
return fmt.Errorf("subgroup check failed")
}
if isOne, err := curve.PairingCheck([]curve.G1Affine{commitment, knowledgeProof}, []curve.G2Affine{vk.g, vk.gRootSigmaNeg}); err != nil {
return err
} else if !isOne {
return fmt.Errorf("proof rejected")
}
return nil
}
func getChallenge(fiatshamirSeeds [][]byte) (r fr.Element, err error) {
// incorporate user-provided seeds into the transcript
t := fiatshamir.NewTranscript(sha256.New(), "r")
for i := range fiatshamirSeeds {
if err = t.Bind("r", fiatshamirSeeds[i]); err != nil {
return
}
}
// obtain the challenge
var rBytes []byte
if rBytes, err = t.ComputeChallenge("r"); err != nil {
return
}
r.SetBytes(rBytes) // TODO @Tabaie Plonk challenge generation done the same way; replace both with hash to fr?
return
}
// Marshal
func (pk *ProvingKey) writeTo(enc *curve.Encoder) (int64, error) {
if err := enc.Encode(pk.basis); err != nil {
return enc.BytesWritten(), err
}
err := enc.Encode(pk.basisExpSigma)
return enc.BytesWritten(), err
}
func (pk *ProvingKey) WriteTo(w io.Writer) (int64, error) {
return pk.writeTo(curve.NewEncoder(w))
}
func (pk *ProvingKey) WriteRawTo(w io.Writer) (int64, error) {
return pk.writeTo(curve.NewEncoder(w, curve.RawEncoding()))
}
func (pk *ProvingKey) ReadFrom(r io.Reader) (int64, error) {
dec := curve.NewDecoder(r)
if err := dec.Decode(&pk.basis); err != nil {
return dec.BytesRead(), err
}
if err := dec.Decode(&pk.basisExpSigma); err != nil {
return dec.BytesRead(), err
}
if cL, pL := len(pk.basis), len(pk.basisExpSigma); cL != pL {
return dec.BytesRead(), fmt.Errorf("commitment basis size (%d) doesn't match proof basis size (%d)", cL, pL)
}
return dec.BytesRead(), nil
}
func (vk *VerifyingKey) WriteTo(w io.Writer) (int64, error) {
return vk.writeTo(curve.NewEncoder(w))
}
func (vk *VerifyingKey) WriteRawTo(w io.Writer) (int64, error) {
return vk.writeTo(curve.NewEncoder(w, curve.RawEncoding()))
}
func (vk *VerifyingKey) writeTo(enc *curve.Encoder) (int64, error) {
var err error
if err = enc.Encode(&vk.g); err != nil {
return enc.BytesWritten(), err
}
err = enc.Encode(&vk.gRootSigmaNeg)
return enc.BytesWritten(), err
}
func (vk *VerifyingKey) ReadFrom(r io.Reader) (int64, error) {
return vk.readFrom(r)
}
func (vk *VerifyingKey) UnsafeReadFrom(r io.Reader) (int64, error) {
return vk.readFrom(r, curve.NoSubgroupChecks())
}
func (vk *VerifyingKey) readFrom(r io.Reader, decOptions ...func(*curve.Decoder)) (int64, error) {
dec := curve.NewDecoder(r, decOptions...)
var err error
if err = dec.Decode(&vk.g); err != nil {
return dec.BytesRead(), err
}
err = dec.Decode(&vk.gRootSigmaNeg)
return dec.BytesRead(), err
}