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
use super::{lookups, param::*};
use crate::util::Expr;
use eth_types::{Address, Field, ToLittleEndian, Word};
use halo2_proofs::{
    circuit::{Region, Value},
    plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells},
    poly::Rotation,
};
use itertools::Itertools;
use std::marker::PhantomData;

pub trait ToLimbs<const N: usize> {
    fn to_limbs(&self) -> [u16; N];
    fn annotation() -> &'static str;
}

impl ToLimbs<N_LIMBS_ACCOUNT_ADDRESS> for Address {
    fn to_limbs(&self) -> [u16; N_LIMBS_ACCOUNT_ADDRESS] {
        // address bytes are be.... maybe just have everything be later?
        // you will need this in the future later because it makes the key ordering more
        // obvious
        let le_bytes: Vec<_> = self.0.iter().rev().cloned().collect();
        le_bytes_to_limbs(&le_bytes).try_into().unwrap()
    }
    fn annotation() -> &'static str {
        "Address"
    }
}

impl ToLimbs<N_LIMBS_RW_COUNTER> for u32 {
    fn to_limbs(&self) -> [u16; N_LIMBS_RW_COUNTER] {
        le_bytes_to_limbs(&self.to_le_bytes()).try_into().unwrap()
    }
    fn annotation() -> &'static str {
        "u32"
    }
}

impl ToLimbs<N_LIMBS_WORD> for Word {
    fn to_limbs(&self) -> [u16; N_LIMBS_WORD] {
        le_bytes_to_limbs(&self.to_le_bytes()).try_into().unwrap()
    }
    fn annotation() -> &'static str {
        "Word"
    }
}

#[derive(Clone, Copy)]
pub struct Config<T, const N: usize>
where
    T: ToLimbs<N>,
{
    // TODO: we can save a column here by not storing the lsb, and then checking that
    // value - value_from_limbs(limbs.prepend(0)) fits into a limb.
    // Does this apply for RLC's too?
    pub limbs: [Column<Advice>; N],
    _marker: PhantomData<T>,
}

#[derive(Clone)]
pub struct Queries<F: Field, const N: usize> {
    pub limbs: [Expression<F>; N],
    pub limbs_prev: [Expression<F>; N],
}

impl<F: Field, const N: usize> Queries<F, N> {
    pub fn new<T: ToLimbs<N>>(meta: &mut VirtualCells<'_, F>, c: Config<T, N>) -> Self {
        Self {
            limbs: c.limbs.map(|limb| meta.query_advice(limb, Rotation::cur())),
            limbs_prev: c
                .limbs
                .map(|limb| meta.query_advice(limb, Rotation::prev())),
        }
    }
}

impl<T, const N: usize> Config<T, N>
where
    T: ToLimbs<N>,
{
    pub fn assign<F: Field>(
        &self,
        region: &mut Region<'_, F>,
        offset: usize,
        value: T,
    ) -> Result<(), Error> {
        for (i, &limb) in value.to_limbs().iter().enumerate() {
            region.assign_advice(
                || format!("limb[{}] in {} mpi", i, T::annotation()),
                self.limbs[i],
                offset,
                || Value::known(F::from(limb as u64)),
            )?;
        }
        Ok(())
    }

    /// Annotates columns of this gadget embedded within a circuit region.
    pub fn annotate_columns_in_region<F: Field>(&self, region: &mut Region<F>, prefix: &str) {
        let mut annotations = Vec::new();
        for (i, _) in self.limbs.iter().enumerate() {
            annotations.push(format!("MPI_limbs_{}_{}", T::annotation(), i));
        }
        self.limbs
            .iter()
            .zip(annotations.iter())
            .for_each(|(col, ann)| region.name_column(|| format!("{}_{}", prefix, ann), *col));
    }
}

pub struct Chip<F: Field, T, const N_LIMBS: usize, const N_VALUES: usize>
where
    T: ToLimbs<N_LIMBS>,
{
    _config: Config<T, N_LIMBS>,
    _marker: PhantomData<F>,
}

impl<F: Field, T, const N_LIMBS: usize, const N_VALUES: usize> Chip<F, T, N_LIMBS, N_VALUES>
where
    T: ToLimbs<N_LIMBS>,
{
    pub fn configure(
        meta: &mut ConstraintSystem<F>,
        selector: Column<Fixed>,
        values: [Column<Advice>; N_VALUES],
        lookup: lookups::Config,
    ) -> Config<T, N_LIMBS> {
        assert_eq!(N_LIMBS & N_VALUES, 0);
        let limbs_per_value = N_LIMBS / N_VALUES;

        let limbs = [0; N_LIMBS].map(|_| meta.advice_column());

        for &limb in &limbs {
            lookup.range_check_u16(meta, "mpi limb fits into u16", |meta| {
                meta.query_advice(limb, Rotation::cur())
            });
        }

        for (n, value) in values.iter().enumerate() {
            meta.create_gate("mpi value matches claimed limbs", |meta| {
                let selector = meta.query_fixed(selector, Rotation::cur());
                let value_expr = meta.query_advice(*value, Rotation::cur());
                let value_limbs = &limbs[n * limbs_per_value..(n + 1) * limbs_per_value];
                let limbs_expr = value_limbs
                    .iter()
                    .map(|limb| meta.query_advice(*limb, Rotation::cur()));
                vec![selector * (value_expr - value_from_limbs(&limbs_expr.collect::<Vec<_>>()))]
            });
        }

        Config {
            limbs,
            _marker: PhantomData,
        }
    }
}

fn le_bytes_to_limbs(bytes: &[u8]) -> Vec<u16> {
    bytes
        .iter()
        .tuples()
        .map(|(lo, hi)| u16::from_le_bytes([*lo, *hi]))
        .collect()
}

fn value_from_limbs<F: Field>(limbs: &[Expression<F>]) -> Expression<F> {
    limbs.iter().rev().fold(0u64.expr(), |result, limb| {
        limb.clone() + result * (1u64 << 16).expr()
    })
}