forked from Consensys/gnark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prove.go
1398 lines (1140 loc) · 36.3 KB
/
prove.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 gnark DO NOT EDIT
package plonk
import (
"context"
"errors"
"fmt"
"hash"
"math/big"
"math/bits"
"runtime"
"sync"
"time"
"golang.org/x/sync/errgroup"
"github.com/consensys/gnark-crypto/ecc"
curve "github.com/consensys/gnark-crypto/ecc/bn254"
"github.com/consensys/gnark-crypto/ecc/bn254/fr"
"github.com/consensys/gnark-crypto/ecc/bn254/fr/fft"
"github.com/consensys/gnark-crypto/ecc/bn254/fr/hash_to_field"
"github.com/consensys/gnark-crypto/ecc/bn254/fr/iop"
"github.com/consensys/gnark-crypto/ecc/bn254/kzg"
fiatshamir "github.com/consensys/gnark-crypto/fiat-shamir"
"github.com/consensys/gnark/backend"
"github.com/consensys/gnark/backend/witness"
"github.com/consensys/gnark/constraint"
cs "github.com/consensys/gnark/constraint/bn254"
"github.com/consensys/gnark/constraint/solver"
fcs "github.com/consensys/gnark/frontend/cs"
"github.com/consensys/gnark/internal/utils"
"github.com/consensys/gnark/logger"
)
// TODO in gnark-crypto:
// * remove everything linked to the blinding
// * add SetCoeff method
// * modify GetCoeff -> if the poly is shifted and in canonical form the index is computed differently
const (
id_L int = iota
id_R
id_O
id_Z
id_ZS
id_Ql
id_Qr
id_Qm
id_Qo
id_Qk
id_S1
id_S2
id_S3
id_ID
id_LOne
id_Qci // [ .. , Qc_i, Pi_i, ...]
)
// blinding factors
const (
id_Bl int = iota
id_Br
id_Bo
id_Bz
nb_blinding_polynomials
)
// blinding orders (-1 to deactivate)
const (
order_blinding_L = 1
order_blinding_R = 1
order_blinding_O = 1
order_blinding_Z = 2
)
type Proof struct {
// Commitments to the solution vectors
LRO [3]kzg.Digest
// Commitment to Z, the permutation polynomial
Z kzg.Digest
// Commitments to h1, h2, h3 such that h = h1 + Xh2 + X**2h3 is the quotient polynomial
H [3]kzg.Digest
Bsb22Commitments []kzg.Digest
// Batch opening proof of h1 + zeta*h2 + zeta**2h3, linearizedPolynomial, l, r, o, s1, s2, qCPrime
BatchedProof kzg.BatchOpeningProof
// Opening proof of Z at zeta*mu
ZShiftedOpening kzg.OpeningProof
}
func Prove(spr *cs.SparseR1CS, pk *ProvingKey, fullWitness witness.Witness, opts ...backend.ProverOption) (*Proof, error) {
log := logger.Logger().With().
Str("curve", spr.CurveID().String()).
Int("nbConstraints", spr.GetNbConstraints()).
Str("backend", "plonk").Logger()
// parse the options
opt, err := backend.NewProverConfig(opts...)
if err != nil {
return nil, fmt.Errorf("get prover options: %w", err)
}
start := time.Now()
// init instance
g, ctx := errgroup.WithContext(context.Background())
instance, err := newInstance(ctx, spr, pk, fullWitness, &opt)
if err != nil {
return nil, fmt.Errorf("new instance: %w", err)
}
// solve constraints
g.Go(instance.solveConstraints)
// complete qk
g.Go(instance.completeQk)
// init blinding polynomials
g.Go(instance.initBlindingPolynomials)
// derive gamma, beta (copy constraint)
g.Go(instance.deriveGammaAndBeta)
// compute accumulating ratio for the copy constraint
g.Go(instance.buildRatioCopyConstraint)
// compute h
g.Go(instance.evaluateConstraints)
// open Z (blinded) at ωζ (proof.ZShiftedOpening)
g.Go(instance.openZ)
// fold the commitment to H ([H₀] + ζᵐ⁺²*[H₁] + ζ²⁽ᵐ⁺²⁾[H₂])
g.Go(instance.foldH)
// linearized polynomial
g.Go(instance.computeLinearizedPolynomial)
// Batch opening
g.Go(instance.batchOpening)
if err := g.Wait(); err != nil {
return nil, err
}
log.Debug().Dur("took", time.Since(start)).Msg("prover done")
return instance.proof, nil
}
// represents a Prover instance
type instance struct {
ctx context.Context
pk *ProvingKey
proof *Proof
spr *cs.SparseR1CS
opt *backend.ProverConfig
fs *fiatshamir.Transcript
kzgFoldingHash hash.Hash // for KZG folding
htfFunc hash.Hash // hash to field function
// polynomials
x []*iop.Polynomial // x stores tracks the polynomial we need
bp []*iop.Polynomial // blinding polynomials
h *iop.Polynomial // h is the quotient polynomial
blindedZ []fr.Element // blindedZ is the blinded version of Z
foldedH []fr.Element // foldedH is the folded version of H
foldedHDigest kzg.Digest // foldedHDigest is the kzg commitment of foldedH
linearizedPolynomial []fr.Element
linearizedPolynomialDigest kzg.Digest
fullWitness witness.Witness
// bsb22 commitment stuff
commitmentInfo constraint.PlonkCommitments
commitmentVal []fr.Element
cCommitments []*iop.Polynomial
// challenges
gamma, beta, alpha, zeta fr.Element
// channel to wait for the steps
chLRO,
chQk,
chbp,
chZ,
chH,
chRestoreLRO,
chZOpening,
chLinearizedPolynomial,
chFoldedH,
chGammaBeta chan struct{}
domain0, domain1 *fft.Domain
trace *Trace
}
func newInstance(ctx context.Context, spr *cs.SparseR1CS, pk *ProvingKey, fullWitness witness.Witness, opts *backend.ProverConfig) (*instance, error) {
if opts.HashToFieldFn == nil {
opts.HashToFieldFn = hash_to_field.New([]byte("BSB22-Plonk"))
}
s := instance{
ctx: ctx,
pk: pk,
proof: &Proof{},
spr: spr,
opt: opts,
fullWitness: fullWitness,
bp: make([]*iop.Polynomial, nb_blinding_polynomials),
fs: fiatshamir.NewTranscript(opts.ChallengeHash, "gamma", "beta", "alpha", "zeta"),
kzgFoldingHash: opts.KZGFoldingHash,
htfFunc: opts.HashToFieldFn,
chLRO: make(chan struct{}, 1),
chQk: make(chan struct{}, 1),
chbp: make(chan struct{}, 1),
chGammaBeta: make(chan struct{}, 1),
chZ: make(chan struct{}, 1),
chH: make(chan struct{}, 1),
chZOpening: make(chan struct{}, 1),
chLinearizedPolynomial: make(chan struct{}, 1),
chFoldedH: make(chan struct{}, 1),
chRestoreLRO: make(chan struct{}, 1),
}
s.initBSB22Commitments()
s.setupGKRHints()
s.x = make([]*iop.Polynomial, id_Qci+2*len(s.commitmentInfo))
// init fft domains
nbConstraints := spr.GetNbConstraints()
sizeSystem := uint64(nbConstraints + len(spr.Public)) // len(spr.Public) is for the placeholder constraints
s.domain0 = fft.NewDomain(sizeSystem)
// h, the quotient polynomial is of degree 3(n+1)+2, so it's in a 3(n+2) dim vector space,
// the domain is the next power of 2 superior to 3(n+2). 4*domainNum is enough in all cases
// except when n<6.
if sizeSystem < 6 {
s.domain1 = fft.NewDomain(8*sizeSystem, fft.WithoutPrecompute())
} else {
s.domain1 = fft.NewDomain(4*sizeSystem, fft.WithoutPrecompute())
}
// TODO @gbotrel domain1 is used for only 1 FFT --> precomputing the twiddles
// and storing them in memory is costly given its size. --> do a FFT on the fly
// build trace
s.trace = NewTrace(spr, s.domain0)
return &s, nil
}
func (s *instance) initBlindingPolynomials() error {
s.bp[id_Bl] = getRandomPolynomial(order_blinding_L)
s.bp[id_Br] = getRandomPolynomial(order_blinding_R)
s.bp[id_Bo] = getRandomPolynomial(order_blinding_O)
s.bp[id_Bz] = getRandomPolynomial(order_blinding_Z)
close(s.chbp)
return nil
}
func (s *instance) initBSB22Commitments() {
s.commitmentInfo = s.spr.CommitmentInfo.(constraint.PlonkCommitments)
s.commitmentVal = make([]fr.Element, len(s.commitmentInfo)) // TODO @Tabaie get rid of this
s.cCommitments = make([]*iop.Polynomial, len(s.commitmentInfo))
s.proof.Bsb22Commitments = make([]kzg.Digest, len(s.commitmentInfo))
// override the hint for the commitment constraints
bsb22ID := solver.GetHintID(fcs.Bsb22CommitmentComputePlaceholder)
s.opt.SolverOpts = append(s.opt.SolverOpts, solver.OverrideHint(bsb22ID, s.bsb22Hint))
}
// Computing and verifying Bsb22 multi-commits explained in https://hackmd.io/x8KsadW3RRyX7YTCFJIkHg
func (s *instance) bsb22Hint(_ *big.Int, ins, outs []*big.Int) error {
var err error
commDepth := int(ins[0].Int64())
ins = ins[1:]
res := &s.commitmentVal[commDepth]
commitmentInfo := s.spr.CommitmentInfo.(constraint.PlonkCommitments)[commDepth]
committedValues := make([]fr.Element, s.domain0.Cardinality)
offset := s.spr.GetNbPublicVariables()
for i := range ins {
committedValues[offset+commitmentInfo.Committed[i]].SetBigInt(ins[i])
}
if _, err = committedValues[offset+commitmentInfo.CommitmentIndex].SetRandom(); err != nil { // Commitment injection constraint has qcp = 0. Safe to use for blinding.
return err
}
if _, err = committedValues[offset+s.spr.GetNbConstraints()-1].SetRandom(); err != nil { // Last constraint has qcp = 0. Safe to use for blinding
return err
}
s.cCommitments[commDepth] = iop.NewPolynomial(&committedValues, iop.Form{Basis: iop.Lagrange, Layout: iop.Regular})
if s.proof.Bsb22Commitments[commDepth], err = kzg.Commit(s.cCommitments[commDepth].Coefficients(), s.pk.KzgLagrange); err != nil {
return err
}
s.htfFunc.Write(s.proof.Bsb22Commitments[commDepth].Marshal())
hashBts := s.htfFunc.Sum(nil)
s.htfFunc.Reset()
nbBuf := fr.Bytes
if s.htfFunc.Size() < fr.Bytes {
nbBuf = s.htfFunc.Size()
}
res.SetBytes(hashBts[:nbBuf]) // TODO @Tabaie use CommitmentIndex for this; create a new variable CommitmentConstraintIndex for other uses
res.BigInt(outs[0])
return nil
}
func (s *instance) setupGKRHints() {
if s.spr.GkrInfo.Is() {
var gkrData cs.GkrSolvingData
s.opt.SolverOpts = append(s.opt.SolverOpts,
solver.OverrideHint(s.spr.GkrInfo.SolveHintID, cs.GkrSolveHint(s.spr.GkrInfo, &gkrData)),
solver.OverrideHint(s.spr.GkrInfo.ProveHintID, cs.GkrProveHint(s.spr.GkrInfo.HashName, &gkrData)))
}
}
// solveConstraints computes the evaluation of the polynomials L, R, O
// and sets x[id_L], x[id_R], x[id_O] in canonical form
func (s *instance) solveConstraints() error {
_solution, err := s.spr.Solve(s.fullWitness, s.opt.SolverOpts...)
if err != nil {
return err
}
solution := _solution.(*cs.SparseR1CSSolution)
evaluationLDomainSmall := []fr.Element(solution.L)
evaluationRDomainSmall := []fr.Element(solution.R)
evaluationODomainSmall := []fr.Element(solution.O)
var wg sync.WaitGroup
wg.Add(2)
go func() {
s.x[id_L] = iop.NewPolynomial(&evaluationLDomainSmall, iop.Form{Basis: iop.Lagrange, Layout: iop.Regular})
wg.Done()
}()
go func() {
s.x[id_R] = iop.NewPolynomial(&evaluationRDomainSmall, iop.Form{Basis: iop.Lagrange, Layout: iop.Regular})
wg.Done()
}()
s.x[id_O] = iop.NewPolynomial(&evaluationODomainSmall, iop.Form{Basis: iop.Lagrange, Layout: iop.Regular})
wg.Wait()
// commit to l, r, o and add blinding factors
if err := s.commitToLRO(); err != nil {
return err
}
close(s.chLRO)
return nil
}
func (s *instance) completeQk() error {
qk := s.trace.Qk.Clone()
qkCoeffs := qk.Coefficients()
wWitness, ok := s.fullWitness.Vector().(fr.Vector)
if !ok {
return witness.ErrInvalidWitness
}
copy(qkCoeffs, wWitness[:len(s.spr.Public)])
// wait for solver to be done
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chLRO:
}
for i := range s.commitmentInfo {
qkCoeffs[s.spr.GetNbPublicVariables()+s.commitmentInfo[i].CommitmentIndex] = s.commitmentVal[i]
}
s.x[id_Qk] = qk
close(s.chQk)
return nil
}
func (s *instance) commitToLRO() error {
// wait for blinding polynomials to be initialized or context to be done
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chbp:
}
g := new(errgroup.Group)
g.Go(func() (err error) {
s.proof.LRO[0], err = s.commitToPolyAndBlinding(s.x[id_L], s.bp[id_Bl])
return
})
g.Go(func() (err error) {
s.proof.LRO[1], err = s.commitToPolyAndBlinding(s.x[id_R], s.bp[id_Br])
return
})
g.Go(func() (err error) {
s.proof.LRO[2], err = s.commitToPolyAndBlinding(s.x[id_O], s.bp[id_Bo])
return
})
return g.Wait()
}
// deriveGammaAndBeta (copy constraint)
func (s *instance) deriveGammaAndBeta() error {
wWitness, ok := s.fullWitness.Vector().(fr.Vector)
if !ok {
return witness.ErrInvalidWitness
}
if err := bindPublicData(s.fs, "gamma", s.pk.Vk, wWitness[:len(s.spr.Public)]); err != nil {
return err
}
// wait for LRO to be committed
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chLRO:
}
gamma, err := deriveRandomness(s.fs, "gamma", &s.proof.LRO[0], &s.proof.LRO[1], &s.proof.LRO[2])
if err != nil {
return err
}
bbeta, err := s.fs.ComputeChallenge("beta")
if err != nil {
return err
}
s.gamma = gamma
s.beta.SetBytes(bbeta)
close(s.chGammaBeta)
return nil
}
// commitToPolyAndBlinding computes the KZG commitment of a polynomial p
// in Lagrange form (large degree)
// and add the contribution of a blinding polynomial b (small degree)
// /!\ The polynomial p is supposed to be in Lagrange form.
func (s *instance) commitToPolyAndBlinding(p, b *iop.Polynomial) (commit curve.G1Affine, err error) {
commit, err = kzg.Commit(p.Coefficients(), s.pk.KzgLagrange)
// we add in the blinding contribution
n := int(s.domain0.Cardinality)
cb := commitBlindingFactor(n, b, s.pk.Kzg)
commit.Add(&commit, &cb)
return
}
func (s *instance) deriveAlpha() (err error) {
alphaDeps := make([]*curve.G1Affine, len(s.proof.Bsb22Commitments)+1)
for i := range s.proof.Bsb22Commitments {
alphaDeps[i] = &s.proof.Bsb22Commitments[i]
}
alphaDeps[len(alphaDeps)-1] = &s.proof.Z
s.alpha, err = deriveRandomness(s.fs, "alpha", alphaDeps...)
return err
}
func (s *instance) deriveZeta() (err error) {
s.zeta, err = deriveRandomness(s.fs, "zeta", &s.proof.H[0], &s.proof.H[1], &s.proof.H[2])
return
}
// evaluateConstraints computes H
func (s *instance) evaluateConstraints() (err error) {
s.x[id_Ql] = s.trace.Ql
s.x[id_Qr] = s.trace.Qr
s.x[id_Qm] = s.trace.Qm
s.x[id_Qo] = s.trace.Qo
s.x[id_S1] = s.trace.S1
s.x[id_S2] = s.trace.S2
s.x[id_S3] = s.trace.S3
for i := 0; i < len(s.commitmentInfo); i++ {
s.x[id_Qci+2*i] = s.trace.Qcp[i]
}
n := s.domain0.Cardinality
lone := make([]fr.Element, n)
lone[0].SetOne()
// wait for solver to be done
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chLRO:
}
for i := 0; i < len(s.commitmentInfo); i++ {
s.x[id_Qci+2*i+1] = s.cCommitments[i]
}
// wait for Z to be committed or context done
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chZ:
}
// derive alpha
if err = s.deriveAlpha(); err != nil {
return err
}
// TODO complete waste of memory find another way to do that
identity := make([]fr.Element, n)
identity[1].Set(&s.beta)
s.x[id_ID] = iop.NewPolynomial(&identity, iop.Form{Basis: iop.Canonical, Layout: iop.Regular})
s.x[id_LOne] = iop.NewPolynomial(&lone, iop.Form{Basis: iop.Lagrange, Layout: iop.Regular})
s.x[id_ZS] = s.x[id_Z].ShallowClone().Shift(1)
numerator, err := s.computeNumerator()
if err != nil {
return err
}
s.h, err = divideByXMinusOne(numerator, [2]*fft.Domain{s.domain0, s.domain1})
if err != nil {
return err
}
// commit to h
if err := commitToQuotient(s.h1(), s.h2(), s.h3(), s.proof, s.pk.Kzg); err != nil {
return err
}
if err := s.deriveZeta(); err != nil {
return err
}
// wait for clean up tasks to be done
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chRestoreLRO:
}
close(s.chH)
return nil
}
func (s *instance) buildRatioCopyConstraint() (err error) {
// wait for gamma and beta to be derived (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chGammaBeta:
}
// TODO @gbotrel having iop.BuildRatioCopyConstraint return something
// with capacity = len() + 4 would avoid extra alloc / copy during openZ
s.x[id_Z], err = iop.BuildRatioCopyConstraint(
[]*iop.Polynomial{
s.x[id_L],
s.x[id_R],
s.x[id_O],
},
s.trace.S,
s.beta,
s.gamma,
iop.Form{Basis: iop.Lagrange, Layout: iop.Regular},
s.domain0,
)
if err != nil {
return err
}
// commit to the blinded version of z
s.proof.Z, err = s.commitToPolyAndBlinding(s.x[id_Z], s.bp[id_Bz])
close(s.chZ)
return
}
// open Z (blinded) at ωζ
func (s *instance) openZ() (err error) {
// wait for H to be committed and zeta to be derived (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chH:
}
var zetaShifted fr.Element
zetaShifted.Mul(&s.zeta, &s.pk.Vk.Generator)
s.blindedZ = getBlindedCoefficients(s.x[id_Z], s.bp[id_Bz])
// open z at zeta
s.proof.ZShiftedOpening, err = kzg.Open(s.blindedZ, zetaShifted, s.pk.Kzg)
if err != nil {
return err
}
close(s.chZOpening)
return nil
}
func (s *instance) h1() []fr.Element {
h1 := s.h.Coefficients()[:s.domain0.Cardinality+2]
return h1
}
func (s *instance) h2() []fr.Element {
h2 := s.h.Coefficients()[s.domain0.Cardinality+2 : 2*(s.domain0.Cardinality+2)]
return h2
}
func (s *instance) h3() []fr.Element {
h3 := s.h.Coefficients()[2*(s.domain0.Cardinality+2) : 3*(s.domain0.Cardinality+2)]
return h3
}
// fold the commitment to H ([H₀] + ζᵐ⁺²*[H₁] + ζ²⁽ᵐ⁺²⁾[H₂])
func (s *instance) foldH() error {
// wait for H to be committed and zeta to be derived (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chH:
}
var n big.Int
n.SetUint64(s.domain0.Cardinality + 2)
var zetaPowerNplusTwo fr.Element
zetaPowerNplusTwo.Exp(s.zeta, &n)
zetaPowerNplusTwo.BigInt(&n)
s.foldedHDigest.ScalarMultiplication(&s.proof.H[2], &n)
s.foldedHDigest.Add(&s.foldedHDigest, &s.proof.H[1]) // ζᵐ⁺²*Comm(h3)
s.foldedHDigest.ScalarMultiplication(&s.foldedHDigest, &n) // ζ²⁽ᵐ⁺²⁾*Comm(h3) + ζᵐ⁺²*Comm(h2)
s.foldedHDigest.Add(&s.foldedHDigest, &s.proof.H[0])
// fold H (H₀ + ζᵐ⁺²*H₁ + ζ²⁽ᵐ⁺²⁾H₂))
h1 := s.h1()
h2 := s.h2()
s.foldedH = s.h3()
for i := 0; i < int(s.domain0.Cardinality)+2; i++ {
s.foldedH[i].
Mul(&s.foldedH[i], &zetaPowerNplusTwo).
Add(&s.foldedH[i], &h2[i]).
Mul(&s.foldedH[i], &zetaPowerNplusTwo).
Add(&s.foldedH[i], &h1[i])
}
close(s.chFoldedH)
return nil
}
func (s *instance) computeLinearizedPolynomial() error {
// wait for H to be committed and zeta to be derived (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chH:
}
qcpzeta := make([]fr.Element, len(s.commitmentInfo))
var blzeta, brzeta, bozeta fr.Element
var wg sync.WaitGroup
wg.Add(3 + len(s.commitmentInfo))
for i := 0; i < len(s.commitmentInfo); i++ {
go func(i int) {
qcpzeta[i] = s.trace.Qcp[i].Evaluate(s.zeta)
wg.Done()
}(i)
}
go func() {
blzeta = evaluateBlinded(s.x[id_L], s.bp[id_Bl], s.zeta)
wg.Done()
}()
go func() {
brzeta = evaluateBlinded(s.x[id_R], s.bp[id_Br], s.zeta)
wg.Done()
}()
go func() {
bozeta = evaluateBlinded(s.x[id_O], s.bp[id_Bo], s.zeta)
wg.Done()
}()
// wait for Z to be opened at zeta (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chZOpening:
}
bzuzeta := s.proof.ZShiftedOpening.ClaimedValue
wg.Wait()
s.linearizedPolynomial = s.innerComputeLinearizedPoly(
blzeta,
brzeta,
bozeta,
s.alpha,
s.beta,
s.gamma,
s.zeta,
bzuzeta,
qcpzeta,
s.blindedZ,
coefficients(s.cCommitments),
s.pk,
)
var err error
s.linearizedPolynomialDigest, err = kzg.Commit(s.linearizedPolynomial, s.pk.Kzg, runtime.NumCPU()*2)
if err != nil {
return err
}
close(s.chLinearizedPolynomial)
return nil
}
func (s *instance) batchOpening() error {
// wait for LRO to be committed (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chLRO:
}
// wait for foldedH to be computed (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chFoldedH:
}
// wait for linearizedPolynomial to be computed (or ctx.Done())
select {
case <-s.ctx.Done():
return errContextDone
case <-s.chLinearizedPolynomial:
}
polysQcp := coefficients(s.trace.Qcp)
polysToOpen := make([][]fr.Element, 7+len(polysQcp))
copy(polysToOpen[7:], polysQcp)
polysToOpen[0] = s.foldedH
polysToOpen[1] = s.linearizedPolynomial
polysToOpen[2] = getBlindedCoefficients(s.x[id_L], s.bp[id_Bl])
polysToOpen[3] = getBlindedCoefficients(s.x[id_R], s.bp[id_Br])
polysToOpen[4] = getBlindedCoefficients(s.x[id_O], s.bp[id_Bo])
polysToOpen[5] = s.trace.S1.Coefficients()
polysToOpen[6] = s.trace.S2.Coefficients()
digestsToOpen := make([]curve.G1Affine, len(s.pk.Vk.Qcp)+7)
copy(digestsToOpen[7:], s.pk.Vk.Qcp)
digestsToOpen[0] = s.foldedHDigest
digestsToOpen[1] = s.linearizedPolynomialDigest
digestsToOpen[2] = s.proof.LRO[0]
digestsToOpen[3] = s.proof.LRO[1]
digestsToOpen[4] = s.proof.LRO[2]
digestsToOpen[5] = s.pk.Vk.S[0]
digestsToOpen[6] = s.pk.Vk.S[1]
var err error
s.proof.BatchedProof, err = kzg.BatchOpenSinglePoint(
polysToOpen,
digestsToOpen,
s.zeta,
s.kzgFoldingHash,
s.pk.Kzg,
s.proof.ZShiftedOpening.ClaimedValue.Marshal(),
)
return err
}
// evaluate the full set of constraints, all polynomials in x are back in
// canonical regular form at the end
func (s *instance) computeNumerator() (*iop.Polynomial, error) {
// init vectors that are used multiple times throughout the computation
n := s.domain0.Cardinality
twiddles0 := make([]fr.Element, n)
if n == 1 {
// edge case
twiddles0[0].SetOne()
} else {
twiddles, err := s.domain0.Twiddles()
if err != nil {
return nil, err
}
copy(twiddles0, twiddles[0])
w := twiddles0[1]
for i := len(twiddles[0]); i < len(twiddles0); i++ {
twiddles0[i].Mul(&twiddles0[i-1], &w)
}
}
// wait for chQk to be closed (or ctx.Done())
select {
case <-s.ctx.Done():
return nil, errContextDone
case <-s.chQk:
}
nbBsbGates := (len(s.x) - id_Qci + 1) >> 1
gateConstraint := func(u ...fr.Element) fr.Element {
var ic, tmp fr.Element
ic.Mul(&u[id_Ql], &u[id_L])
tmp.Mul(&u[id_Qr], &u[id_R])
ic.Add(&ic, &tmp)
tmp.Mul(&u[id_Qm], &u[id_L]).Mul(&tmp, &u[id_R])
ic.Add(&ic, &tmp)
tmp.Mul(&u[id_Qo], &u[id_O])
ic.Add(&ic, &tmp).Add(&ic, &u[id_Qk])
for i := 0; i < nbBsbGates; i++ {
tmp.Mul(&u[id_Qci+2*i], &u[id_Qci+2*i+1])
ic.Add(&ic, &tmp)
}
return ic
}
var cs, css fr.Element
cs.Set(&s.domain1.FrMultiplicativeGen)
css.Square(&cs)
orderingConstraint := func(u ...fr.Element) fr.Element {
gamma := s.gamma
var a, b, c, r, l fr.Element
a.Add(&gamma, &u[id_L]).Add(&a, &u[id_ID])
b.Mul(&u[id_ID], &cs).Add(&b, &u[id_R]).Add(&b, &gamma)
c.Mul(&u[id_ID], &css).Add(&c, &u[id_O]).Add(&c, &gamma)
r.Mul(&a, &b).Mul(&r, &c).Mul(&r, &u[id_Z])
a.Add(&u[id_S1], &u[id_L]).Add(&a, &gamma)
b.Add(&u[id_S2], &u[id_R]).Add(&b, &gamma)
c.Add(&u[id_S3], &u[id_O]).Add(&c, &gamma)
l.Mul(&a, &b).Mul(&l, &c).Mul(&l, &u[id_ZS])
l.Sub(&l, &r)
return l
}
ratioLocalConstraint := func(u ...fr.Element) fr.Element {
var res fr.Element
res.SetOne()
res.Sub(&u[id_Z], &res).Mul(&res, &u[id_LOne])
return res
}
rho := int(s.domain1.Cardinality / n)
shifters := make([]fr.Element, rho)
shifters[0].Set(&s.domain1.FrMultiplicativeGen)
for i := 1; i < rho; i++ {
shifters[i].Set(&s.domain1.Generator)
}
// stores the current coset shifter
var coset fr.Element
coset.SetOne()
var tmp, one fr.Element
one.SetOne()
bn := big.NewInt(int64(n))
cosetTable, err := s.domain0.CosetTable()
if err != nil {
return nil, err
}
// init the result polynomial & buffer
cres := make([]fr.Element, s.domain1.Cardinality)
buf := make([]fr.Element, n)
var wgBuf sync.WaitGroup
allConstraints := func(i int, u ...fr.Element) fr.Element {
// scale S1, S2, S3 by β
u[id_S1].Mul(&u[id_S1], &s.beta)
u[id_S2].Mul(&u[id_S2], &s.beta)
u[id_S3].Mul(&u[id_S3], &s.beta)
// blind L, R, O, Z, ZS
var y fr.Element
y = s.bp[id_Bl].Evaluate(twiddles0[i])
u[id_L].Add(&u[id_L], &y)
y = s.bp[id_Br].Evaluate(twiddles0[i])
u[id_R].Add(&u[id_R], &y)
y = s.bp[id_Bo].Evaluate(twiddles0[i])
u[id_O].Add(&u[id_O], &y)
y = s.bp[id_Bz].Evaluate(twiddles0[i])
u[id_Z].Add(&u[id_Z], &y)
// ZS is shifted by 1; need to get correct twiddle
y = s.bp[id_Bz].Evaluate(twiddles0[(i+1)%int(n)])
u[id_ZS].Add(&u[id_ZS], &y)
a := gateConstraint(u...)
b := orderingConstraint(u...)
c := ratioLocalConstraint(u...)
c.Mul(&c, &s.alpha).Add(&c, &b).Mul(&c, &s.alpha).Add(&c, &a)
return c
}
// for the first iteration, the scalingVector is the coset table
scalingVector := cosetTable
scalingVectorRev := make([]fr.Element, len(cosetTable))
copy(scalingVectorRev, cosetTable)
fft.BitReverse(scalingVectorRev)
// pre-computed to compute the bit reverse index
// of the result polynomial
m := uint64(s.domain1.Cardinality)
mm := uint64(64 - bits.TrailingZeros64(m))
for i := 0; i < rho; i++ {
coset.Mul(&coset, &shifters[i])
tmp.Exp(coset, bn).Sub(&tmp, &one)
// bl <- bl *( (s*ωⁱ)ⁿ-1 )s
for _, q := range s.bp {
cq := q.Coefficients()
acc := tmp
for j := 0; j < len(cq); j++ {
cq[j].Mul(&cq[j], &acc)
acc.Mul(&acc, &shifters[i])
}
}
if i == 1 {
// we have to update the scalingVector; instead of scaling by
// cosets we scale by the twiddles of the large domain.
w := s.domain1.Generator
scalingVector = make([]fr.Element, n)
fft.BuildExpTable(w, scalingVector)
// reuse memory
copy(scalingVectorRev, scalingVector)
fft.BitReverse(scalingVectorRev)
}
// we do **a lot** of FFT here, but on the small domain.
// note that for all the polynomials in the proving key
// (Ql, Qr, Qm, Qo, S1, S2, S3, Qcp, Qc) and ID, LOne
// we could pre-compute theses rho*2 FFTs and store them
// at the cost of a huge memory footprint.
batchApply(s.x, func(p *iop.Polynomial) {
nbTasks := calculateNbTasks(len(s.x)-1) * 2
// shift polynomials to be in the correct coset
p.ToCanonical(s.domain0, nbTasks)