openvm_mod_circuit_builder/
field_variable.rs

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
use std::{
    cell::RefCell,
    cmp::{max, min},
    ops::{Add, Div, Mul, Sub},
    rc::Rc,
};

use openvm_circuit_primitives::bigint::check_carry_to_zero::get_carry_max_abs_and_bits;
use openvm_stark_backend::p3_util::log2_ceil_usize;

use super::{ExprBuilder, SymbolicExpr};

#[derive(Clone)]
pub struct FieldVariable {
    // 1. This will be "reset" to Var(n), when calling save on it.
    // 2. This is an expression to "compute" (instead of to "constrain")
    // But it will NOT have division, as it will be auto save and reset.
    // For example, if we want to compute d = a * b + c, the expr here will be a * b + c
    // So this is not a constraint that should be equal to zero (a * b + c - d is the constraint).
    pub expr: SymbolicExpr,

    pub builder: Rc<RefCell<ExprBuilder>>,

    // Limb related information when evaluated as an OverflowInt (vector of limbs).
    // Max abs of each limb.
    pub limb_max_abs: usize,
    // All limbs should be within [-2^max_overflow_bits, 2^max_overflow_bits)
    // This is log2_ceil(limb_max_abs)
    pub max_overflow_bits: usize,
    // Number of limbs to represent the expression.
    pub expr_limbs: usize,

    // This is the same for all FieldVariable, but we might use different values at runtime,
    // so store it here for easy configuration.
    pub range_checker_bits: usize,
}

impl FieldVariable {
    // Returns the index of the new variable.
    // There should be no division in the expression.
    /// This function is idempotent, i.e., if you already saved, then saving again does nothing.
    pub fn save(&mut self) -> usize {
        if let SymbolicExpr::Var(var_id) = self.expr {
            // If self.expr is already a Var, no need to save
            return var_id;
        }
        let mut builder = self.builder.borrow_mut();

        // Introduce a new variable to replace self.expr.
        let (new_var_idx, new_var) = builder.new_var();
        // self.expr - new_var = 0
        let new_constraint =
            SymbolicExpr::Sub(Box::new(self.expr.clone()), Box::new(new_var.clone()));
        // limbs information.
        builder.set_constraint(new_var_idx, new_constraint);
        builder.set_compute(new_var_idx, self.expr.clone());

        self.expr = new_var;
        self.limb_max_abs = (1 << builder.limb_bits) - 1;
        self.max_overflow_bits = builder.limb_bits;
        self.expr_limbs = builder.num_limbs;

        builder.num_variables - 1
    }

    pub fn save_output(&mut self) {
        let index = self.save();
        let mut builder = self.builder.borrow_mut();
        builder.output_indices.push(index);
    }

    pub fn canonical_limb_bits(&self) -> usize {
        self.builder.borrow().limb_bits
    }

    fn get_q_limbs(expr: SymbolicExpr, builder: &ExprBuilder) -> usize {
        let constraint_expr = SymbolicExpr::Sub(
            Box::new(expr),
            Box::new(SymbolicExpr::Var(builder.num_variables)),
        );
        let (q_limbs, _) =
            constraint_expr.constraint_limbs(&builder.prime, builder.limb_bits, builder.num_limbs);
        q_limbs
    }

    fn save_if_overflow(
        a: &mut FieldVariable, // will save this variable if overflow
        expr: SymbolicExpr, // the "compute" expression of the result variable. Note that we need to check if constraint overflows
        limb_max_abs: usize, // The max abs of limbs of compute expression.
    ) {
        if let SymbolicExpr::Var(_) = a.expr {
            return;
        }
        let builder = a.builder.borrow();
        let canonical_limb_bits = builder.limb_bits;
        let q_limbs = FieldVariable::get_q_limbs(expr, &builder);
        let canonical_limb_max_abs = (1 << canonical_limb_bits) - 1;

        // The constraint equation is expr - new_var - qp, and we need to check if it overflows.
        let limb_max_abs = limb_max_abs
            + canonical_limb_max_abs  // new var
            + canonical_limb_max_abs * canonical_limb_max_abs * min(q_limbs, builder.num_limbs); // qp
        drop(builder);

        let max_overflow_bits = log2_ceil_usize(limb_max_abs);
        let (_, carry_bits) = get_carry_max_abs_and_bits(max_overflow_bits, canonical_limb_bits);
        if carry_bits > a.range_checker_bits {
            a.save();
        }
    }

    // TODO: rethink about how should auto-save work.
    // This implementation requires self and other to be mutable, and might actually mutate them.
    // This might surprise the caller or introduce hard bug if the caller clone the FieldVariable and then call this.
    pub fn add(&mut self, other: &mut FieldVariable) -> FieldVariable {
        assert!(Rc::ptr_eq(&self.builder, &other.builder));
        let limb_max_fn = |a: &FieldVariable, b: &FieldVariable| a.limb_max_abs + b.limb_max_abs;
        FieldVariable::save_if_overflow(
            self,
            SymbolicExpr::Add(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            limb_max_fn(self, other),
        );
        // Do again to check if the other also needs to be saved.
        FieldVariable::save_if_overflow(
            other,
            SymbolicExpr::Add(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            limb_max_fn(self, other),
        );

        let limb_max_abs = limb_max_fn(self, other);
        let max_overflow_bits = log2_ceil_usize(limb_max_abs);
        FieldVariable {
            expr: SymbolicExpr::Add(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            builder: self.builder.clone(),
            limb_max_abs,
            max_overflow_bits,
            expr_limbs: max(self.expr_limbs, other.expr_limbs),
            range_checker_bits: self.range_checker_bits,
        }
    }

    pub fn sub(&mut self, other: &mut FieldVariable) -> FieldVariable {
        assert!(Rc::ptr_eq(&self.builder, &other.builder));
        let limb_max_fn = |a: &FieldVariable, b: &FieldVariable| a.limb_max_abs + b.limb_max_abs;
        FieldVariable::save_if_overflow(
            self,
            SymbolicExpr::Sub(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            limb_max_fn(self, other),
        );
        // Do again to check if the other also needs to be saved.
        FieldVariable::save_if_overflow(
            other,
            SymbolicExpr::Sub(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            limb_max_fn(self, other),
        );

        let limb_max_abs = limb_max_fn(self, other);
        let max_overflow_bits = log2_ceil_usize(limb_max_abs);
        FieldVariable {
            expr: SymbolicExpr::Sub(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            builder: self.builder.clone(),
            limb_max_abs,
            max_overflow_bits,
            expr_limbs: max(self.expr_limbs, other.expr_limbs),
            range_checker_bits: self.range_checker_bits,
        }
    }

    pub fn mul(&mut self, other: &mut FieldVariable) -> FieldVariable {
        assert!(Rc::ptr_eq(&self.builder, &other.builder));
        let limb_max_fn = |a: &FieldVariable, b: &FieldVariable| {
            a.limb_max_abs * b.limb_max_abs * min(a.expr_limbs, b.expr_limbs)
        };
        FieldVariable::save_if_overflow(
            self,
            SymbolicExpr::Mul(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            limb_max_fn(self, other),
        );
        // Do again to check if the other also needs to be saved.
        FieldVariable::save_if_overflow(
            other,
            SymbolicExpr::Mul(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            limb_max_fn(self, other),
        );

        let limb_max_abs = limb_max_fn(self, other);
        let max_overflow_bits = log2_ceil_usize(limb_max_abs);
        FieldVariable {
            expr: SymbolicExpr::Mul(Box::new(self.expr.clone()), Box::new(other.expr.clone())),
            builder: self.builder.clone(),
            limb_max_abs,
            max_overflow_bits,
            expr_limbs: self.expr_limbs + other.expr_limbs - 1,
            range_checker_bits: self.range_checker_bits,
        }
    }

    pub fn square(&mut self) -> FieldVariable {
        let limb_max_abs = self.limb_max_abs * self.limb_max_abs * self.expr_limbs;
        FieldVariable::save_if_overflow(
            self,
            SymbolicExpr::Mul(Box::new(self.expr.clone()), Box::new(self.expr.clone())),
            limb_max_abs,
        );

        let limb_max_abs = self.limb_max_abs * self.limb_max_abs * self.expr_limbs;
        let max_overflow_bits = log2_ceil_usize(limb_max_abs);
        FieldVariable {
            expr: SymbolicExpr::Mul(Box::new(self.expr.clone()), Box::new(self.expr.clone())),
            builder: self.builder.clone(),
            limb_max_abs,
            max_overflow_bits,
            expr_limbs: self.expr_limbs * 2 - 1,
            range_checker_bits: self.range_checker_bits,
        }
    }

    pub fn int_add(&mut self, scalar: isize) -> FieldVariable {
        let limb_max_abs = self.limb_max_abs + scalar.unsigned_abs();
        FieldVariable::save_if_overflow(
            self,
            SymbolicExpr::IntAdd(Box::new(self.expr.clone()), scalar),
            limb_max_abs,
        );

        let limb_max_abs = self.limb_max_abs + scalar.unsigned_abs();
        let max_overflow_bits = log2_ceil_usize(limb_max_abs);
        FieldVariable {
            expr: SymbolicExpr::IntAdd(Box::new(self.expr.clone()), scalar),
            builder: self.builder.clone(),
            limb_max_abs,
            max_overflow_bits,
            expr_limbs: self.expr_limbs,
            range_checker_bits: self.range_checker_bits,
        }
    }

    pub fn int_mul(&mut self, scalar: isize) -> FieldVariable {
        let limb_max_abs = self.limb_max_abs * scalar.unsigned_abs();
        FieldVariable::save_if_overflow(
            self,
            SymbolicExpr::IntMul(Box::new(self.expr.clone()), scalar),
            limb_max_abs,
        );

        let limb_max_abs = self.limb_max_abs * scalar.unsigned_abs();
        let max_overflow_bits = log2_ceil_usize(limb_max_abs);
        FieldVariable {
            expr: SymbolicExpr::IntMul(Box::new(self.expr.clone()), scalar),
            builder: self.builder.clone(),
            limb_max_abs,
            max_overflow_bits,
            expr_limbs: self.expr_limbs,
            range_checker_bits: self.range_checker_bits,
        }
    }

    // expr cannot have division, so auto-save a new variable.
    pub fn div(&mut self, other: &mut FieldVariable) -> FieldVariable {
        assert!(Rc::ptr_eq(&self.builder, &other.builder));
        let builder = self.builder.borrow();
        let prime = builder.prime.clone();
        let limb_bits = builder.limb_bits;
        let num_limbs = builder.num_limbs;
        drop(builder);

        // This is a dummy variable, will be replaced later so the index within it doesn't matter.
        // We use this to check if we need to save self/other first.
        let fake_var = SymbolicExpr::Var(0);

        // Constraint: other.expr * new_var - self.expr = 0 (mod p)
        let new_constraint = SymbolicExpr::Sub(
            Box::new(SymbolicExpr::Mul(
                Box::new(other.expr.clone()),
                Box::new(fake_var.clone()),
            )),
            Box::new(self.expr.clone()),
        );
        let carry_bits = new_constraint.constraint_carry_bits_with_pq(&prime, limb_bits, num_limbs);
        if carry_bits > self.range_checker_bits {
            // TODO: should save the "bigger" one first (the one with higher limb_max_abs)
            self.save();
        }
        // Do it again to check if other needs to be saved.
        let new_constraint = SymbolicExpr::Sub(
            Box::new(SymbolicExpr::Mul(
                Box::new(other.expr.clone()),
                Box::new(fake_var.clone()),
            )),
            Box::new(self.expr.clone()),
        );
        let carry_bits = new_constraint.constraint_carry_bits_with_pq(&prime, limb_bits, num_limbs);
        if carry_bits > self.range_checker_bits {
            other.save();
        }

        let mut builder = self.builder.borrow_mut();
        let (new_var_idx, new_var) = builder.new_var();
        let new_constraint = SymbolicExpr::Sub(
            Box::new(SymbolicExpr::Mul(
                Box::new(other.expr.clone()),
                Box::new(new_var.clone()),
            )),
            Box::new(self.expr.clone()),
        );
        builder.set_constraint(new_var_idx, new_constraint);
        // Only compute can have division.
        let compute = SymbolicExpr::Div(Box::new(self.expr.clone()), Box::new(other.expr.clone()));
        builder.set_compute(new_var_idx, compute);
        drop(builder);

        FieldVariable::from_var(self.builder.clone(), new_var)
    }

    pub fn from_var(builder: Rc<RefCell<ExprBuilder>>, var: SymbolicExpr) -> FieldVariable {
        let borrowed_builder = builder.borrow();
        let range_checker_bits = borrowed_builder.range_checker_bits;
        assert!(
            matches!(var, SymbolicExpr::Var(_)),
            "Expected var to be of type SymbolicExpr::Var"
        );
        let num_limbs = borrowed_builder.num_limbs;
        let canonical_limb_bits = borrowed_builder.limb_bits;
        drop(borrowed_builder);
        FieldVariable {
            expr: var,
            builder,
            limb_max_abs: (1 << canonical_limb_bits) - 1,
            max_overflow_bits: canonical_limb_bits,
            expr_limbs: num_limbs,
            range_checker_bits,
        }
    }

    pub fn select(flag_id: usize, a: &FieldVariable, b: &FieldVariable) -> FieldVariable {
        assert!(Rc::ptr_eq(&a.builder, &b.builder));
        let left_limb_max_abs = max(a.limb_max_abs, b.limb_max_abs);
        let left_max_overflow_bits = max(a.max_overflow_bits, b.max_overflow_bits);
        let left_expr_limbs = max(a.expr_limbs, b.expr_limbs);
        let right_limb_max_abs = left_limb_max_abs;
        let right_max_overflow_bits = left_max_overflow_bits;
        let right_expr_limbs = left_expr_limbs;
        assert_eq!(left_limb_max_abs, right_limb_max_abs);
        assert_eq!(left_max_overflow_bits, right_max_overflow_bits);
        assert_eq!(left_expr_limbs, right_expr_limbs);
        FieldVariable {
            expr: SymbolicExpr::Select(flag_id, Box::new(a.expr.clone()), Box::new(b.expr.clone())),
            builder: a.builder.clone(),
            limb_max_abs: left_limb_max_abs,
            max_overflow_bits: left_max_overflow_bits,
            expr_limbs: left_expr_limbs,
            range_checker_bits: a.range_checker_bits,
        }
    }
}

impl Add<&mut FieldVariable> for &mut FieldVariable {
    type Output = FieldVariable;

    fn add(self, rhs: &mut FieldVariable) -> Self::Output {
        self.add(rhs)
    }
}

impl Add<FieldVariable> for FieldVariable {
    type Output = FieldVariable;

    fn add(mut self, mut rhs: FieldVariable) -> Self::Output {
        let x = &mut self;
        x.add(&mut rhs)
    }
}

impl Sub<FieldVariable> for FieldVariable {
    type Output = FieldVariable;

    fn sub(mut self, mut rhs: FieldVariable) -> Self::Output {
        let x = &mut self;
        x.sub(&mut rhs)
    }
}

impl Sub<&mut FieldVariable> for &mut FieldVariable {
    type Output = FieldVariable;

    fn sub(self, rhs: &mut FieldVariable) -> Self::Output {
        self.sub(rhs)
    }
}

impl Mul<FieldVariable> for FieldVariable {
    type Output = FieldVariable;

    fn mul(mut self, mut rhs: FieldVariable) -> Self::Output {
        let x = &mut self;
        x.mul(&mut rhs)
    }
}

impl Mul<&mut FieldVariable> for &mut FieldVariable {
    type Output = FieldVariable;

    fn mul(self, rhs: &mut FieldVariable) -> Self::Output {
        FieldVariable::mul(self, rhs)
    }
}

impl Div<FieldVariable> for FieldVariable {
    type Output = FieldVariable;

    fn div(mut self, mut rhs: FieldVariable) -> Self::Output {
        let x = &mut self;
        x.div(&mut rhs)
    }
}

impl Div<&mut FieldVariable> for &mut FieldVariable {
    type Output = FieldVariable;

    fn div(self, rhs: &mut FieldVariable) -> Self::Output {
        FieldVariable::div(self, rhs)
    }
}