-
Notifications
You must be signed in to change notification settings - Fork 353
/
r1cs.go
451 lines (383 loc) · 12.8 KB
/
r1cs.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
// 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 cs
import (
"errors"
"fmt"
"github.com/fxamacker/cbor/v2"
"io"
"runtime"
"sync"
"time"
"github.com/consensys/gnark/backend"
"github.com/consensys/gnark/backend/witness"
"github.com/consensys/gnark/constraint"
"github.com/consensys/gnark/internal/backend/ioutils"
"github.com/consensys/gnark/logger"
"github.com/consensys/gnark/profile"
"github.com/consensys/gnark-crypto/ecc"
"math"
"github.com/consensys/gnark-crypto/ecc/bw6-761/fr"
)
// R1CS describes a set of R1CS constraint
type R1CS struct {
constraint.R1CSCore
CoeffTable
arithEngine
}
// NewR1CS returns a new R1CS and sets cs.Coefficient (fr.Element) from provided big.Int values
//
// capacity pre-allocates memory for capacity nbConstraints
func NewR1CS(capacity int) *R1CS {
r := R1CS{
R1CSCore: constraint.R1CSCore{
System: constraint.NewSystem(fr.Modulus()),
Constraints: make([]constraint.R1C, 0, capacity),
},
CoeffTable: newCoeffTable(capacity / 10),
}
return &r
}
func (cs *R1CS) AddConstraint(r1c constraint.R1C, debugInfo ...constraint.DebugInfo) int {
profile.RecordConstraint()
cs.Constraints = append(cs.Constraints, r1c)
cID := len(cs.Constraints) - 1
if len(debugInfo) == 1 {
cs.DebugInfo = append(cs.DebugInfo, constraint.LogEntry(debugInfo[0]))
cs.MDebug[cID] = len(cs.DebugInfo) - 1
}
cs.UpdateLevel(cID, &r1c)
return cID
}
// Solve sets all the wires and returns the a, b, c vectors.
// the cs system should have been compiled before. The entries in a, b, c are in Montgomery form.
// a, b, c vectors: ab-c = hz
// witness = [publicWires | secretWires] (without the ONE_WIRE !)
// returns [publicWires | secretWires | internalWires ]
func (cs *R1CS) Solve(witness, a, b, c fr.Vector, opt backend.ProverConfig) (fr.Vector, error) {
log := logger.Logger().With().Int("nbConstraints", len(cs.Constraints)).Str("backend", "groth16").Logger()
nbWires := len(cs.Public) + len(cs.Secret) + cs.NbInternalVariables
solution, err := newSolution(nbWires, opt.HintFunctions, cs.MHintsDependencies, cs.MHints, cs.Coefficients, &cs.System.SymbolTable)
if err != nil {
return make(fr.Vector, nbWires), err
}
start := time.Now()
if len(witness) != len(cs.Public)-1+len(cs.Secret) { // - 1 for ONE_WIRE
err = fmt.Errorf("invalid witness size, got %d, expected %d = %d (public) + %d (secret)", len(witness), int(len(cs.Public)-1+len(cs.Secret)), len(cs.Public)-1, len(cs.Secret))
log.Err(err).Send()
return solution.values, err
}
// compute the wires and the a, b, c polynomials
if len(a) != len(cs.Constraints) || len(b) != len(cs.Constraints) || len(c) != len(cs.Constraints) {
err = errors.New("invalid input size: len(a, b, c) == len(Constraints)")
log.Err(err).Send()
return solution.values, err
}
solution.solved[0] = true // ONE_WIRE
solution.values[0].SetOne()
copy(solution.values[1:], witness)
for i := range witness {
solution.solved[i+1] = true
}
// keep track of the number of wire instantiations we do, for a sanity check to ensure
// we instantiated all wires
solution.nbSolved += uint64(len(witness) + 1)
// now that we know all inputs are set, defer log printing once all solution.values are computed
// (or sooner, if a constraint is not satisfied)
defer solution.printLogs(opt.CircuitLogger, cs.Logs)
if err := cs.parallelSolve(a, b, c, &solution); err != nil {
if unsatisfiedErr, ok := err.(*UnsatisfiedConstraintError); ok {
log.Err(errors.New("unsatisfied constraint")).Int("id", unsatisfiedErr.CID).Send()
} else {
log.Err(err).Send()
}
return solution.values, err
}
// sanity check; ensure all wires are marked as "instantiated"
if !solution.isValid() {
log.Err(errors.New("solver didn't instantiate all wires")).Send()
panic("solver didn't instantiate all wires")
}
log.Debug().Dur("took", time.Since(start)).Msg("constraint system solver done")
return solution.values, nil
}
func (cs *R1CS) parallelSolve(a, b, c fr.Vector, solution *solution) error {
// minWorkPerCPU is the minimum target number of constraint a task should hold
// in other words, if a level has less than minWorkPerCPU, it will not be parallelized and executed
// sequentially without sync.
const minWorkPerCPU = 50.0
// cs.Levels has a list of levels, where all constraints in a level l(n) are independent
// and may only have dependencies on previous levels
// for each constraint
// we are guaranteed that each R1C contains at most one unsolved wire
// first we solve the unsolved wire (if any)
// then we check that the constraint is valid
// if a[i] * b[i] != c[i]; it means the constraint is not satisfied
var wg sync.WaitGroup
chTasks := make(chan []int, runtime.NumCPU())
chError := make(chan *UnsatisfiedConstraintError, runtime.NumCPU())
// start a worker pool
// each worker wait on chTasks
// a task is a slice of constraint indexes to be solved
for i := 0; i < runtime.NumCPU(); i++ {
go func() {
for t := range chTasks {
for _, i := range t {
// for each constraint in the task, solve it.
if err := cs.solveConstraint(cs.Constraints[i], solution, &a[i], &b[i], &c[i]); err != nil {
var debugInfo *string
if dID, ok := cs.MDebug[i]; ok {
debugInfo = new(string)
*debugInfo = solution.logValue(cs.DebugInfo[dID])
}
chError <- &UnsatisfiedConstraintError{CID: i, Err: err, DebugInfo: debugInfo}
wg.Done()
return
}
}
wg.Done()
}
}()
}
// clean up pool go routines
defer func() {
close(chTasks)
close(chError)
}()
// for each level, we push the tasks
for _, level := range cs.Levels {
// max CPU to use
maxCPU := float64(len(level)) / minWorkPerCPU
if maxCPU <= 1.0 {
// we do it sequentially
for _, i := range level {
if err := cs.solveConstraint(cs.Constraints[i], solution, &a[i], &b[i], &c[i]); err != nil {
var debugInfo *string
if dID, ok := cs.MDebug[i]; ok {
debugInfo = new(string)
*debugInfo = solution.logValue(cs.DebugInfo[dID])
}
return &UnsatisfiedConstraintError{CID: i, Err: err, DebugInfo: debugInfo}
}
}
continue
}
// number of tasks for this level is set to num cpus
// but if we don't have enough work for all our CPUS, it can be lower.
nbTasks := runtime.NumCPU()
maxTasks := int(math.Ceil(maxCPU))
if nbTasks > maxTasks {
nbTasks = maxTasks
}
nbIterationsPerCpus := len(level) / nbTasks
// more CPUs than tasks: a CPU will work on exactly one iteration
// note: this depends on minWorkPerCPU constant
if nbIterationsPerCpus < 1 {
nbIterationsPerCpus = 1
nbTasks = len(level)
}
extraTasks := len(level) - (nbTasks * nbIterationsPerCpus)
extraTasksOffset := 0
for i := 0; i < nbTasks; i++ {
wg.Add(1)
_start := i*nbIterationsPerCpus + extraTasksOffset
_end := _start + nbIterationsPerCpus
if extraTasks > 0 {
_end++
extraTasks--
extraTasksOffset++
}
// since we're never pushing more than num CPU tasks
// we will never be blocked here
chTasks <- level[_start:_end]
}
// wait for the level to be done
wg.Wait()
if len(chError) > 0 {
return <-chError
}
}
return nil
}
// IsSolved returns nil if given witness solves the R1CS and error otherwise
// this method wraps cs.Solve() and allocates cs.Solve() inputs
func (cs *R1CS) IsSolved(witness witness.Witness, opts ...backend.ProverOption) error {
opt, err := backend.NewProverConfig(opts...)
if err != nil {
return err
}
a := make(fr.Vector, len(cs.Constraints))
b := make(fr.Vector, len(cs.Constraints))
c := make(fr.Vector, len(cs.Constraints))
v := witness.Vector().(fr.Vector)
_, err = cs.Solve(v, a, b, c, opt)
return err
}
// divByCoeff sets res = res / t.Coeff
func (cs *R1CS) divByCoeff(res *fr.Element, t constraint.Term) {
cID := t.CoeffID()
switch cID {
case constraint.CoeffIdOne:
return
case constraint.CoeffIdMinusOne:
res.Neg(res)
case constraint.CoeffIdZero:
panic("division by 0")
default:
// this is slow, but shouldn't happen as divByCoeff is called to
// remove the coeff of an unsolved wire
// but unsolved wires are (in gnark frontend) systematically set with a coeff == 1 or -1
res.Div(res, &cs.Coefficients[cID])
}
}
// solveConstraint compute unsolved wires in the constraint, if any and set the solution accordingly
//
// returns an error if the solver called a hint function that errored
// returns false, nil if there was no wire to solve
// returns true, nil if exactly one wire was solved. In that case, it is redundant to check that
// the constraint is satisfied later.
func (cs *R1CS) solveConstraint(r constraint.R1C, solution *solution, a, b, c *fr.Element) error {
// the index of the non-zero entry shows if L, R or O has an uninstantiated wire
// the content is the ID of the wire non instantiated
var loc uint8
var termToCompute constraint.Term
processLExp := func(l constraint.LinearExpression, val *fr.Element, locValue uint8) error {
for _, t := range l {
vID := t.WireID()
// wire is already computed, we just accumulate in val
if solution.solved[vID] {
solution.accumulateInto(t, val)
continue
}
// first we check if this is a hint wire
if hint, ok := cs.MHints[vID]; ok {
if err := solution.solveWithHint(vID, hint); err != nil {
return err
}
// now that the wire is saved, accumulate it into a, b or c
solution.accumulateInto(t, val)
continue
}
if loc != 0 {
panic("found more than one wire to instantiate")
}
termToCompute = t
loc = locValue
}
return nil
}
if err := processLExp(r.L, a, 1); err != nil {
return err
}
if err := processLExp(r.R, b, 2); err != nil {
return err
}
if err := processLExp(r.O, c, 3); err != nil {
return err
}
if loc == 0 {
// there is nothing to solve, may happen if we have an assertion
// (ie a constraints that doesn't yield any output)
// or if we solved the unsolved wires with hint functions
var check fr.Element
if !check.Mul(a, b).Equal(c) {
return fmt.Errorf("%s ⋅ %s != %s", a.String(), b.String(), c.String())
}
return nil
}
// we compute the wire value and instantiate it
wID := termToCompute.WireID()
// solver result
var wire fr.Element
switch loc {
case 1:
if !b.IsZero() {
wire.Div(c, b).
Sub(&wire, a)
a.Add(a, &wire)
} else {
// we didn't actually ensure that a * b == c
var check fr.Element
if !check.Mul(a, b).Equal(c) {
return fmt.Errorf("%s ⋅ %s != %s", a.String(), b.String(), c.String())
}
}
case 2:
if !a.IsZero() {
wire.Div(c, a).
Sub(&wire, b)
b.Add(b, &wire)
} else {
var check fr.Element
if !check.Mul(a, b).Equal(c) {
return fmt.Errorf("%s ⋅ %s != %s", a.String(), b.String(), c.String())
}
}
case 3:
wire.Mul(a, b).
Sub(&wire, c)
c.Add(c, &wire)
}
// wire is the term (coeff * value)
// but in the solution we want to store the value only
// note that in gnark frontend, coeff here is always 1 or -1
cs.divByCoeff(&wire, termToCompute)
solution.set(wID, wire)
return nil
}
// GetConstraints return the list of R1C and a coefficient resolver
func (cs *R1CS) GetConstraints() ([]constraint.R1C, constraint.Resolver) {
return cs.Constraints, cs
}
// GetNbCoefficients return the number of unique coefficients needed in the R1CS
func (cs *R1CS) GetNbCoefficients() int {
return len(cs.Coefficients)
}
// CurveID returns curve ID as defined in gnark-crypto
func (cs *R1CS) CurveID() ecc.ID {
return ecc.BW6_761
}
// WriteTo encodes R1CS into provided io.Writer using cbor
func (cs *R1CS) WriteTo(w io.Writer) (int64, error) {
_w := ioutils.WriterCounter{W: w} // wraps writer to count the bytes written
enc, err := cbor.CoreDetEncOptions().EncMode()
if err != nil {
return 0, err
}
encoder := enc.NewEncoder(&_w)
// encode our object
err = encoder.Encode(cs)
return _w.N, err
}
// ReadFrom attempts to decode R1CS from io.Reader using cbor
func (cs *R1CS) ReadFrom(r io.Reader) (int64, error) {
dm, err := cbor.DecOptions{
MaxArrayElements: 134217728,
MaxMapPairs: 134217728,
}.DecMode()
if err != nil {
return 0, err
}
decoder := dm.NewDecoder(r)
// initialize coeff table
cs.CoeffTable = newCoeffTable(0)
if err := decoder.Decode(&cs); err != nil {
return int64(decoder.NumBytesRead()), err
}
if err := cs.CheckSerializationHeader(); err != nil {
return int64(decoder.NumBytesRead()), err
}
return int64(decoder.NumBytesRead()), nil
}