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
use crate::circuit_tools::cell_manager::Cell;
use eth_types::Field;
use halo2_proofs::{
    circuit::{AssignedCell, Region, Value},
    plonk::{Advice, Any, Assigned, Column, Error, Expression, Fixed},
    poly::Rotation,
};
use std::{
    collections::HashMap,
    hash::{Hash, Hasher},
};

use super::{
    cell_manager::{CellColumn, CellType},
    constraint_builder::ConstraintBuilder,
};

pub trait ChallengeSet<F: Field> {
    fn indexed(&self) -> Vec<&Value<F>>;
}

impl<F: Field, V: AsRef<[Value<F>]>> ChallengeSet<F> for V {
    fn indexed(&self) -> Vec<&Value<F>> {
        self.as_ref().iter().collect()
    }
}

pub struct CachedRegion<'r, 'b, F: Field> {
    region: &'r mut Region<'b, F>,
    pub advice: HashMap<(usize, usize), F>,
    pub fixed: HashMap<(usize, usize), F>,
    disable_description: bool,
    regions: Vec<(usize, usize)>,
    pub key_r: F,
    pub keccak_r: F,
}

impl<'r, 'b, F: Field> CachedRegion<'r, 'b, F> {
    pub(crate) fn new(region: &'r mut Region<'b, F>, keccak_r: F) -> Self {
        Self {
            region,
            advice: HashMap::new(),
            fixed: HashMap::new(),
            disable_description: false,
            regions: Vec::new(),
            key_r: keccak_r,
            keccak_r,
        }
    }

    pub(crate) fn set_disable_description(&mut self, disable_description: bool) {
        self.disable_description = disable_description;
    }

    pub(crate) fn push_region(&mut self, offset: usize, region_id: usize) {
        self.regions.push((offset, region_id));
    }

    pub(crate) fn pop_region(&mut self) {
        // Nothing to do
    }

    pub(crate) fn assign_stored_expressions<C: CellType, S: ChallengeSet<F>>(
        &mut self,
        cb: &ConstraintBuilder<F, C>,
        challenges: &S,
    ) -> Result<(), Error> {
        for n in 0..self.regions.len() {
            let (offset, region_id) = self.regions[n];
            for stored_expression in cb.get_stored_expressions(region_id).iter() {
                stored_expression.assign(self, challenges, offset)?;
            }
        }
        Ok(())
    }

    pub(crate) fn annotate_columns<C: CellType>(&mut self, cell_columns: &[CellColumn<F, C>]) {
        for c in cell_columns {
            self.region.name_column(
                || format!("{:?} {:?}: {:?} queried", c.cell_type, c.index, c.height),
                c.column,
            );
        }
    }

    /// Assign an advice column value (witness).
    pub fn assign_advice<'v, V, VR, A, AR>(
        &'v mut self,
        annotation: A,
        column: Column<Advice>,
        offset: usize,
        to: V,
    ) -> Result<AssignedCell<VR, F>, Error>
    where
        V: Fn() -> Value<VR> + 'v,
        for<'vr> Assigned<F>: From<&'vr VR>,
        A: Fn() -> AR,
        AR: Into<String>,
    {
        // Actually set the value
        let res = self.region.assign_advice(annotation, column, offset, &to);
        // Cache the value
        // Note that the `value_field` in `AssignedCell` might be `Value::unknown` if
        // the column has different phase than current one, so we call to `to`
        // again here to cache the value.
        if res.is_ok() {
            to().map(|f: VR| {
                let existing = self
                    .advice
                    .insert((column.index(), offset), Assigned::from(&f).evaluate());
                assert!(existing.is_none());
                existing
            });
        }
        res
    }

    pub fn name_column<A, AR, T>(&mut self, annotation: A, column: T)
    where
        A: Fn() -> AR,
        AR: Into<String>,
        T: Into<Column<Any>>,
    {
        self.region
            .name_column(|| annotation().into(), column.into());
    }

    pub fn assign_fixed<'v, V, VR, A, AR>(
        &'v mut self,
        annotation: A,
        column: Column<Fixed>,
        offset: usize,
        to: V,
    ) -> Result<AssignedCell<VR, F>, Error>
    where
        V: Fn() -> Value<VR> + 'v,
        for<'vr> Assigned<F>: From<&'vr VR>,
        A: Fn() -> AR,
        AR: Into<String>,
    {
        // Actually set the value
        let res = self.region.assign_fixed(annotation, column, offset, &to);
        // Cache the value
        // Note that the `value_field` in `AssignedCell` might be `Value::unknown` if
        // the column has different phase than current one, so we call to `to`
        // again here to cache the value.
        if res.is_ok() {
            to().map(|f: VR| {
                let existing = self
                    .fixed
                    .insert((column.index(), offset), Assigned::from(&f).evaluate());
                assert!(existing.is_none());
                existing
            });
        }
        res
    }

    pub fn get_fixed(&self, row_index: usize, column_index: usize, rotation: Rotation) -> F {
        let zero = F::ZERO;
        *self
            .fixed
            .get(&(column_index, row_index + rotation.0 as usize))
            .unwrap_or(&zero)
    }

    pub fn get_advice(&self, row_index: usize, column_index: usize, rotation: Rotation) -> F {
        let zero = F::ZERO;
        *self
            .advice
            .get(&(column_index, row_index + rotation.0 as usize))
            .unwrap_or(&zero)
    }

    /// Constrains a cell to have a constant value.
    ///
    /// Returns an error if the cell is in a column where equality has not been
    /// enabled.
    pub fn constrain_constant<VR>(
        &mut self,
        cell: AssignedCell<F, F>,
        constant: VR,
    ) -> Result<(), Error>
    where
        VR: Into<Assigned<F>>,
    {
        self.region.constrain_constant(cell.cell(), constant.into())
    }
}

#[derive(Debug, Clone)]
pub struct StoredExpression<F, C: CellType> {
    pub(crate) name: String,
    pub(crate) cell: Cell<F>,
    pub(crate) cell_type: C,
    pub(crate) expr: Expression<F>,
    pub(crate) expr_id: String,
}

impl<F, C: CellType> Hash for StoredExpression<F, C> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.expr_id.hash(state);
        self.cell_type.hash(state);
    }
}

impl<F: Field, C: CellType> StoredExpression<F, C> {
    pub fn assign<S: ChallengeSet<F>>(
        &self,
        region: &mut CachedRegion<'_, '_, F>,
        challenges: &S,
        offset: usize,
    ) -> Result<Value<F>, Error> {
        let value = self.expr.evaluate(
            &|scalar| Value::known(scalar),
            &|_| unimplemented!("selector column"),
            &|fixed_query| {
                Value::known(region.get_fixed(
                    offset,
                    fixed_query.column_index(),
                    fixed_query.rotation(),
                ))
            },
            &|advice_query| {
                Value::known(region.get_advice(
                    offset,
                    advice_query.column_index(),
                    advice_query.rotation(),
                ))
            },
            &|_| unimplemented!("instance column"),
            &|challenge| *challenges.indexed()[challenge.index()],
            &|a| -a,
            &|a, b| a + b,
            &|a, b| a * b,
            &|a, scalar| a * Value::known(scalar),
        );
        self.cell.assign_value(region, offset, value)?;
        Ok(value)
    }
}