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
use crate::{
    evm_circuit::util::{
        constraint_builder::{ConstrainBuilderCommon, EVMConstraintBuilder},
        math_gadget::*,
        CachedRegion, Cell, CellType,
    },
    util::Expr,
};
use eth_types::Field;
use halo2_proofs::{
    circuit::Value,
    plonk::{Error, Expression},
};
/// Returns (quotient: numerator/denominator, remainder: numerator%denominator),
/// with `numerator` an expression and `denominator` a constant.
/// Input requirements:
/// - `quotient < 256**N_BYTES`
/// - `quotient * denominator < field size`
/// - `remainder < denominator` requires a range lookup table for `denominator`
#[derive(Clone, Debug)]
pub struct ConstantDivisionGadget<F, const N_BYTES: usize> {
    quotient: Cell<F>,
    remainder: Cell<F>,
    denominator: u64,
    quotient_range_check: RangeCheckGadget<F, N_BYTES>,
}

impl<F: Field, const N_BYTES: usize> ConstantDivisionGadget<F, N_BYTES> {
    pub(crate) fn construct(
        cb: &mut EVMConstraintBuilder<F>,
        numerator: Expression<F>,
        denominator: u64,
    ) -> Self {
        let quotient = cb.query_cell_with_type(CellType::storage_for_expr(&numerator));
        let remainder = cb.query_cell_with_type(CellType::storage_for_expr(&numerator));

        // Require that remainder < denominator
        cb.range_lookup(remainder.expr(), denominator);

        // Require that quotient < 256**N_BYTES
        // so we can't have any overflow when doing `quotient * denominator`.
        let quotient_range_check = RangeCheckGadget::construct(cb, quotient.expr());

        // Check if the division was done correctly
        cb.require_equal(
            "numerator - remainder == quotient ⋅ denominator",
            numerator - remainder.expr(),
            quotient.expr() * denominator.expr(),
        );

        Self {
            quotient,
            remainder,
            denominator,
            quotient_range_check,
        }
    }

    pub(crate) fn quotient(&self) -> Expression<F> {
        self.quotient.expr()
    }
    #[allow(dead_code, reason = "remainder is a valid API but only used in tests")]
    pub(crate) fn remainder(&self) -> Expression<F> {
        self.remainder.expr()
    }

    pub(crate) fn assign(
        &self,
        region: &mut CachedRegion<'_, '_, F>,
        offset: usize,
        numerator: u128,
    ) -> Result<(u128, u128), Error> {
        let denominator = self.denominator as u128;
        let quotient = numerator / denominator;
        let remainder = numerator % denominator;

        self.quotient
            .assign(region, offset, Value::known(F::from_u128(quotient)))?;
        self.remainder
            .assign(region, offset, Value::known(F::from_u128(remainder)))?;

        self.quotient_range_check
            .assign(region, offset, F::from_u128(quotient))?;

        Ok((quotient, remainder))
    }
}

#[cfg(test)]
mod tests {
    use super::{test_util::*, *};
    use eth_types::*;
    use halo2_proofs::{halo2curves::bn256::Fr, plonk::Error};

    #[derive(Clone)]
    /// ConstantDivisionTestContainer:
    /// require(a(N_BYTES) == DENOMINATOR * QUOTIENT + REMAINDER)
    struct ConstantDivisionTestContainer<
        F,
        const N_BYTES: usize,
        const DENOMINATOR: u64,
        const QUOTIENT: u64,
        const REMINDER: u64,
    > {
        constdiv_gadget: ConstantDivisionGadget<F, N_BYTES>,
        a: Cell<F>,
    }

    impl<
            F: Field,
            const N_BYTES: usize,
            const DENOMINATOR: u64,
            const QUOTIENT: u64,
            const REMAINDER: u64,
        > MathGadgetContainer<F>
        for ConstantDivisionTestContainer<F, N_BYTES, DENOMINATOR, QUOTIENT, REMAINDER>
    {
        fn configure_gadget_container(cb: &mut EVMConstraintBuilder<F>) -> Self {
            let a = cb.query_cell();
            let constdiv_gadget =
                ConstantDivisionGadget::<F, N_BYTES>::construct(cb, a.expr(), DENOMINATOR);

            cb.require_equal(
                "correct remainder",
                constdiv_gadget.remainder(),
                REMAINDER.expr(),
            );

            cb.require_equal(
                "correct quotient",
                constdiv_gadget.quotient(),
                QUOTIENT.expr(),
            );

            ConstantDivisionTestContainer { constdiv_gadget, a }
        }

        fn assign_gadget_container(
            &self,
            witnesses: &[Word],
            region: &mut CachedRegion<'_, '_, F>,
        ) -> Result<(), Error> {
            let a = u64::from_le_bytes(witnesses[0].to_le_bytes()[..8].try_into().unwrap());
            let offset = 0;

            self.a.assign(region, offset, Value::known(F::from(a)))?;
            self.constdiv_gadget.assign(region, offset, a as u128)?;

            Ok(())
        }
    }

    #[test]
    fn test_constantdivisiongadget_0div5_rem0() {
        try_test!(
            ConstantDivisionTestContainer<Fr, 4, 5, 0, 0>,
            [Word::from(0)],
            true,
        );
    }

    #[test]
    fn test_constantdivisiongadget_5div5_rem0() {
        try_test!(
            ConstantDivisionTestContainer<Fr, 4, 5, 1, 0>,
            [Word::from(5)],
            true,
        );
    }

    #[test]
    fn test_constantdivisiongadget_1div5_rem1() {
        try_test!(
            ConstantDivisionTestContainer<Fr, 4, 5, 0, 1>,
            [Word::from(1)],
            true,
        );
    }

    #[test]
    fn test_constantdivisiongadget_1div5_rem4() {
        try_test!(
            ConstantDivisionTestContainer<Fr, 4, 5, 1, 4>,
            [Word::from(1)],
            false,
        );
    }

    #[test]
    fn test_constantdivisiongadget_quotient_overflow() {
        try_test!(
            ConstantDivisionTestContainer<Fr, 4, 5, 4294967296u64, 1>,
            [Word::from(1u64 << (4 * 8)) * 5 + 1],
            false,
        );
    }

    #[test]
    fn test_constantdivisiongadget_33_div16_rem17() {
        try_test!(
            ConstantDivisionTestContainer<Fr, 4, 16, 1, 17>,
            [Word::from(33)],
            false,
        );
    }
}