-
Notifications
You must be signed in to change notification settings - Fork 102
/
bool.ts
402 lines (355 loc) · 9.79 KB
/
bool.ts
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
import { Snarky } from '../../snarky.js';
import { Field, readVarMessage, withMessage } from './field.js';
import { FieldVar, FieldConst, FieldType } from './core/fieldvar.js';
import { defineBinable } from '../../bindings/lib/binable.js';
import { NonNegativeInteger } from '../../bindings/crypto/non-negative.js';
import { asProver } from './core/provable-context.js';
import { existsOne } from './core/exists.js';
import { assertMul } from './gadgets/compatible.js';
import { setBoolConstructor } from './core/field-constructor.js';
export { BoolVar, Bool };
// same representation, but use a different name to communicate intent / constraints
type BoolVar = FieldVar;
type ConstantBoolVar = [FieldType.Constant, FieldConst];
type ConstantBool = Bool & { value: ConstantBoolVar };
/**
* A boolean value. You can use it like this:
*
* ```
* const x = new Bool(true);
* ```
*
* You can also combine multiple booleans via [[`not`]], [[`and`]], [[`or`]].
*
* Use [[assertEquals]] to enforce the value of a Bool.
*/
class Bool {
value: BoolVar;
constructor(x: boolean | Bool | BoolVar) {
if (x instanceof Bool) {
this.value = x.value;
return;
}
if (Array.isArray(x)) {
this.value = x;
return;
}
this.value = FieldVar.constant(BigInt(x));
}
isConstant(): this is { value: ConstantBoolVar } {
return this.value[0] === FieldType.Constant;
}
/**
* Converts a {@link Bool} to a {@link Field}. `false` becomes 0 and `true` becomes 1.
*/
toField(): Field {
return Bool.toField(this);
}
/**
* @returns a new {@link Bool} that is the negation of this {@link Bool}.
*/
not(): Bool {
if (this.isConstant()) {
return new Bool(!this.toBoolean());
}
// 1 - x
let not = new Field(1).sub(this.toField());
return new Bool(not.value);
}
/**
* @param y A {@link Bool} to AND with this {@link Bool}.
* @returns a new {@link Bool} that is set to true only if
* this {@link Bool} and `y` are also true.
*/
and(y: Bool | boolean): Bool {
if (this.isConstant() && isConstant(y)) {
return new Bool(this.toBoolean() && toBoolean(y));
}
// x * y
return new Bool(this.toField().mul(Bool.toField(y)).value);
}
/**
* @param y a {@link Bool} to OR with this {@link Bool}.
* @returns a new {@link Bool} that is set to true if either
* this {@link Bool} or `y` is true.
*/
or(y: Bool | boolean): Bool {
if (this.isConstant() && isConstant(y)) {
return new Bool(this.toBoolean() || toBoolean(y));
}
// 1 - (1 - x)(1 - y) = x + y - xy
return this.not().and(new Bool(y).not()).not();
}
/**
* Proves that this {@link Bool} is equal to `y`.
* @param y a {@link Bool}.
*/
assertEquals(y: Bool | boolean, message?: string): void {
try {
if (this.isConstant() && isConstant(y)) {
if (this.toBoolean() !== toBoolean(y)) {
throw Error(`Bool.assertEquals(): ${this} != ${y}`);
}
return;
}
this.toField().assertEquals(Bool.toField(y));
} catch (err) {
throw withMessage(err, message);
}
}
/**
* Proves that this {@link Bool} is `true`.
*/
assertTrue(message?: string): void {
try {
if (this.isConstant() && !this.toBoolean()) {
throw Error(`Bool.assertTrue(): ${this} != ${true}`);
}
this.assertEquals(true);
} catch (err) {
throw withMessage(err, message);
}
}
/**
* Proves that this {@link Bool} is `false`.
*/
assertFalse(message?: string): void {
try {
if (this.isConstant() && this.toBoolean()) {
throw Error(`Bool.assertFalse(): ${this} != ${false}`);
}
this.assertEquals(false);
} catch (err) {
throw withMessage(err, message);
}
}
/**
* Returns true if this {@link Bool} is equal to `y`.
* @param y a {@link Bool}.
*/
equals(y: Bool | boolean): Bool {
if (this.isConstant() && isConstant(y)) {
return new Bool(this.toBoolean() === toBoolean(y));
}
if (isConstant(y)) {
if (toBoolean(y)) return this;
else return this.not();
}
if (this.isConstant()) {
return new Bool(y).equals(this);
}
// 1 - (x - y)^2 = 2xy - x - y + 1
// match snarky logic:
// 2x * y === x + y - z
// return 1 - z
let z = existsOne(() => BigInt(this.toBoolean() !== toBoolean(y)));
let x = this.toField();
let y_ = Bool.toField(y);
assertMul(x.add(x), y_, x.add(y_).sub(z));
return new Bool(z.value).not();
}
/**
* Returns the size of this type.
*/
sizeInFields(): number {
return 1;
}
/**
* Serializes this {@link Bool} into {@link Field} elements.
*/
toFields(): Field[] {
return Bool.toFields(this);
}
/**
* Serialize the {@link Bool} to a string, e.g. for printing.
* This operation does _not_ affect the circuit and can't be used to prove anything about the string representation of the Field.
*/
toString(): string {
return this.toBoolean().toString();
}
/**
* Serialize the {@link Bool} to a JSON string.
* This operation does _not_ affect the circuit and can't be used to prove anything about the string representation of the Field.
*/
toJSON(): boolean {
return this.toBoolean();
}
/**
* This converts the {@link Bool} to a JS `boolean`.
* This can only be called on non-witness values.
*/
toBoolean(): boolean {
if (this.isConstant()) {
return FieldConst.equal(this.value[1], FieldConst[1]);
}
if (!Snarky.run.inProverBlock()) {
throw Error(readVarMessage('toBoolean', 'b', 'Bool'));
}
let value = Snarky.field.readVar(this.value);
return FieldConst.equal(value, FieldConst[1]);
}
static toField(x: Bool | boolean): Field {
return new Field(toFieldVar(x));
}
/**
* Boolean negation.
*/
static not(x: Bool | boolean): Bool {
if (x instanceof Bool) {
return x.not();
}
return new Bool(!x);
}
/**
* Boolean AND operation.
*/
static and(x: Bool | boolean, y: Bool | boolean): Bool {
if (x instanceof Bool) {
return x.and(y);
}
return new Bool(x).and(y);
}
/**
* Boolean OR operation.
*/
static or(x: Bool | boolean, y: Bool | boolean): Bool {
if (x instanceof Bool) {
return x.or(y);
}
return new Bool(x).or(y);
}
/**
* Asserts if both {@link Bool} are equal.
*/
static assertEqual(x: Bool, y: Bool | boolean): void {
if (x instanceof Bool) {
x.assertEquals(y);
return;
}
new Bool(x).assertEquals(y);
}
/**
* Checks two {@link Bool} for equality.
*/
static equal(x: Bool | boolean, y: Bool | boolean): Bool {
if (x instanceof Bool) {
return x.equals(y);
}
return new Bool(x).equals(y);
}
/**
* Static method to serialize a {@link Bool} into an array of {@link Field} elements.
*/
static toFields(x: Bool): Field[] {
return [Bool.toField(x)];
}
/**
* Static method to serialize a {@link Bool} into its auxiliary data.
*/
static toAuxiliary(_?: Bool): [] {
return [];
}
/**
* Creates a data structure from an array of serialized {@link Field} elements.
*/
static fromFields(fields: Field[]): Bool {
if (fields.length !== 1) {
throw Error(`Bool.fromFields(): expected 1 field, got ${fields.length}`);
}
return new Bool(fields[0].value);
}
/**
* `Provable<Bool>.toValue()`
*/
static toValue(x: Bool): boolean {
return x.toBoolean();
}
/**
* `Provable<Bool>.fromValue()`
*/
static fromValue(b: boolean | Bool) {
if (typeof b === 'boolean') return new Bool(b);
return b;
}
/**
* Serialize a {@link Bool} to a JSON string.
* This operation does _not_ affect the circuit and can't be used to prove anything about the string representation of the Field.
*/
static toJSON(x: Bool): boolean {
return x.toBoolean();
}
/**
* Deserialize a JSON structure into a {@link Bool}.
* This operation does _not_ affect the circuit and can't be used to prove anything about the string representation of the Field.
*/
static fromJSON(b: boolean): Bool {
return new Bool(b);
}
/**
* Returns the size of this type.
*/
static sizeInFields() {
return 1;
}
static empty() {
return new Bool(false);
}
static toInput(x: Bool): { packed: [Field, number][] } {
return { packed: [[x.toField(), 1] as [Field, number]] };
}
static toBytes(b: Bool): number[] {
return BoolBinable.toBytes(b);
}
static fromBytes(bytes: number[]): Bool {
return BoolBinable.fromBytes(bytes);
}
static readBytes<N extends number>(
bytes: number[],
offset: NonNegativeInteger<N>
): [value: Bool, offset: number] {
return BoolBinable.readBytes(bytes, offset);
}
static sizeInBytes = 1;
static check(x: Bool): void {
x.toField().assertBool();
}
static Unsafe = {
/**
* Converts a {@link Field} into a {@link Bool}. This is an **unsafe** operation
* as it assumes that the field element is either 0 or 1 (which might not be true).
*
* Only use this if you have already constrained the Field element to be 0 or 1.
*
* @param x a {@link Field}
*/
fromField(x: Field) {
return new Bool(x.value);
},
};
}
setBoolConstructor(Bool);
const BoolBinable = defineBinable({
toBytes(b: Bool) {
return [Number(b.toBoolean())];
},
readBytes(bytes, offset) {
return [new Bool(!!bytes[offset]), offset + 1];
},
});
// internal helper functions
function isConstant(x: boolean | Bool): x is boolean | ConstantBool {
if (typeof x === 'boolean') {
return true;
}
return x.isConstant();
}
function toBoolean(x: boolean | Bool): boolean {
if (typeof x === 'boolean') {
return x;
}
return x.toBoolean();
}
function toFieldVar(x: boolean | Bool): BoolVar {
if (x instanceof Bool) return x.value;
return FieldVar.constant(BigInt(x));
}