Repository navigation
Expand file tree
/
Copy pathexample1.rs
More file actions
239 lines (201 loc) · 8.14 KB
/
Copy pathexample1.rs
File metadata and controls
239 lines (201 loc) · 8.14 KB
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
use halo2_proofs::{arithmetic::FieldExt, circuit::*, plonk::*, poly::Rotation};
use std::marker::PhantomData;
#[derive(Debug, Clone)]
// Defines the configuration of all the columns, and all of the column definitions
// Will be incrementally populated and passed around
struct FibonacciConfig {
pub col_a: Column<Advice>,
pub col_b: Column<Advice>,
pub col_c: Column<Advice>,
pub selector: Selector,
pub instance: Column<Instance>,
}
#[derive(Debug, Clone)]
struct FibonacciChip<F: FieldExt> {
config: FibonacciConfig,
_marker: PhantomData<F>,
// In rust, when you have a struct that is generic over a type parameter (here F),
// but the type parameter is not referenced in a field of the struct,
// you have to use PhantomData to virtually reference the type parameter,
// so that the compiler can track it. Otherwise it would give an error. - Jason
}
impl<F: FieldExt> FibonacciChip<F> {
// Default constructor
pub fn construct(config: FibonacciConfig) -> Self {
Self {
config,
_marker: PhantomData,
}
}
// Configure will set what type of columns things are, enable equality, create gates, and return a config with all the gates
pub fn configure(meta: &mut ConstraintSystem<F>) -> FibonacciConfig {
let col_a = meta.advice_column();
let col_b = meta.advice_column();
let col_c = meta.advice_column();
let selector = meta.selector();
let instance = meta.instance_column();
// enable_equality has some cost, so we only want to define it on rows where we need copy constraints
meta.enable_equality(col_a);
meta.enable_equality(col_b);
meta.enable_equality(col_c);
meta.enable_equality(instance);
// Defining a create_gate here applies it over every single column in the circuit.
// We will use the selector column to decide when to turn this gate on and off, since we probably don't want it on every row
meta.create_gate("add", |meta| {
//
// col_a | col_b | col_c | selector
// a b c s
//
let s = meta.query_selector(selector);
let a = meta.query_advice(col_a, Rotation::cur());
let b = meta.query_advice(col_b, Rotation::cur());
let c = meta.query_advice(col_c, Rotation::cur());
vec![s * (a + b - c)]
});
FibonacciConfig {
col_a,
col_b,
col_c,
selector,
instance,
}
}
// These assign functions are to be called by the synthesizer, and will be used to assign values to the columns (the witness)
// The layouter will collect all the region definitions and compress it horizontally (i.e. squeeze up/down)
// but not vertically (i.e. will not squeeze left/right, at least right now)
#[allow(clippy::type_complexity)]
pub fn assign_first_row(
&self,
mut layouter: impl Layouter<F>,
) -> Result<(AssignedCell<F, F>, AssignedCell<F, F>, AssignedCell<F, F>), Error> {
layouter.assign_region(
|| "first row",
|mut region| {
self.config.selector.enable(&mut region, 0)?;
let a_cell = region.assign_advice_from_instance(
|| "f(0)",
self.config.instance,
0,
self.config.col_a,
0,
)?;
let b_cell = region.assign_advice_from_instance(
|| "f(1)",
self.config.instance,
1,
self.config.col_b,
0,
)?;
let c_cell = region.assign_advice(
|| "a + b",
self.config.col_c,
0,
|| a_cell.value().copied() + b_cell.value(),
)?;
Ok((a_cell, b_cell, c_cell))
},
)
}
// This will be repeatedly called. Note that each time it makes a new region, comprised of a, b, c, s that happen to all be in the same row
pub fn assign_row(
&self,
mut layouter: impl Layouter<F>,
prev_b: &AssignedCell<F, F>,
prev_c: &AssignedCell<F, F>,
) -> Result<AssignedCell<F, F>, Error> {
layouter.assign_region(
|| "next row",
|mut region| {
self.config.selector.enable(&mut region, 0)?;
// Copy the value from b & c in previous row to a & b in current row
prev_b.copy_advice(|| "a", &mut region, self.config.col_a, 0)?;
prev_c.copy_advice(|| "b", &mut region, self.config.col_b, 0)?;
let c_cell = region.assign_advice(
|| "c",
self.config.col_c,
0,
|| prev_b.value().copied() + prev_c.value(),
)?;
Ok(c_cell)
},
)
}
pub fn expose_public(
&self,
mut layouter: impl Layouter<F>,
cell: &AssignedCell<F, F>,
row: usize,
) -> Result<(), Error> {
layouter.constrain_instance(cell.cell(), self.config.instance, row)
}
}
#[derive(Default)]
struct MyCircuit<F>(PhantomData<F>);
// Our circuit will instantiate an instance based on the interface defined on the chip and floorplanner (layouter)
// There isn't a clear reason this and the chip aren't the same thing, except for better abstractions for complex circuits
impl<F: FieldExt> Circuit<F> for MyCircuit<F> {
type Config = FibonacciConfig;
type FloorPlanner = SimpleFloorPlanner;
// Circuit without witnesses, called only during key generation
fn without_witnesses(&self) -> Self {
Self::default()
}
// Has the arrangement of columns. Called only during keygen, and will just call chip config most of the time
fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
FibonacciChip::configure(meta)
}
// Take the output of configure and floorplanner type to make the actual circuit
// Called both at key generation time, and proving time with a specific witness
// Will call all of the copy constraints
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<F>,
) -> Result<(), Error> {
let chip = FibonacciChip::construct(config);
let (_, mut prev_b, mut prev_c) =
chip.assign_first_row(layouter.namespace(|| "first row"))?;
for _i in 3..10 {
let c_cell = chip.assign_row(layouter.namespace(|| "next row"), &prev_b, &prev_c)?;
prev_b = prev_c;
prev_c = c_cell;
}
chip.expose_public(layouter.namespace(|| "out"), &prev_c, 2)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::marker::PhantomData;
use super::MyCircuit;
use halo2_proofs::{dev::MockProver, pasta::Fp};
#[test]
fn fibonacci_example1() {
let k = 4;
let a = Fp::from(1); // F[0]
let b = Fp::from(1); // F[1]
let out = Fp::from(55); // F[9]
let circuit = MyCircuit(PhantomData);
let mut public_input = vec![a, b, out];
// This prover is faster and 'fake', but is mostly a devtool for debugging
let prover = MockProver::run(k, &circuit, vec![public_input.clone()]).unwrap();
// This function will pretty-print on errors
prover.assert_satisfied();
public_input[2] += Fp::one();
let _prover = MockProver::run(k, &circuit, vec![public_input]).unwrap();
// uncomment the following line and the assert will fail
// _prover.assert_satisfied();
}
#[cfg(feature = "dev-graph")]
#[test]
fn plot_fibonacci1() {
use plotters::prelude::*;
let root = BitMapBackend::new("fib-1-layout.png", (1024, 3096)).into_drawing_area();
root.fill(&WHITE).unwrap();
let root = root.titled("Fib 1 Layout", ("sans-serif", 60)).unwrap();
let circuit = MyCircuit::<Fp>(PhantomData);
halo2_proofs::dev::CircuitLayout::default()
.render(4, &circuit, &root)
.unwrap();
}
}