-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathfibonacci_rap.rs
387 lines (327 loc) · 11 KB
/
fibonacci_rap.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
use std::{marker::PhantomData, ops::Div};
use crate::{
constraints::{
boundary::{BoundaryConstraint, BoundaryConstraints},
transition::TransitionConstraint,
},
context::AirContext,
proof::options::ProofOptions,
trace::TraceTable,
traits::{TransitionEvaluationContext, AIR},
};
use lambdaworks_crypto::fiat_shamir::is_transcript::IsTranscript;
use lambdaworks_math::{
field::{element::FieldElement, traits::IsFFTField},
helpers::resize_to_next_power_of_two,
traits::ByteConversion,
};
#[derive(Clone)]
struct FibConstraint<F: IsFFTField> {
phantom: PhantomData<F>,
}
impl<F: IsFFTField> FibConstraint<F> {
pub fn new() -> Self {
Self {
phantom: PhantomData,
}
}
}
impl<F> TransitionConstraint<F, F> for FibConstraint<F>
where
F: IsFFTField + Send + Sync,
{
fn degree(&self) -> usize {
1
}
fn constraint_idx(&self) -> usize {
0
}
fn end_exemptions(&self) -> usize {
// NOTE: This is hard-coded for the example of steps = 16 in the integration tests.
// If that number changes in the test, this should be changed too or the test will fail.
3 + 32 - 16 - 1
}
fn evaluate(
&self,
evaluation_context: &TransitionEvaluationContext<F, F>,
transition_evaluations: &mut [FieldElement<F>],
) {
let (frame, _periodic_values, _rap_challenges) = match evaluation_context {
TransitionEvaluationContext::Prover {
frame,
periodic_values,
rap_challenges,
}
| TransitionEvaluationContext::Verifier {
frame,
periodic_values,
rap_challenges,
} => (frame, periodic_values, rap_challenges),
};
let first_step = frame.get_evaluation_step(0);
let second_step = frame.get_evaluation_step(1);
let third_step = frame.get_evaluation_step(2);
let a0 = first_step.get_main_evaluation_element(0, 0);
let a1 = second_step.get_main_evaluation_element(0, 0);
let a2 = third_step.get_main_evaluation_element(0, 0);
let res = a2 - a1 - a0;
transition_evaluations[self.constraint_idx()] = res;
}
}
#[derive(Clone)]
struct PermutationConstraint<F: IsFFTField> {
phantom: PhantomData<F>,
}
impl<F: IsFFTField> PermutationConstraint<F> {
pub fn new() -> Self {
Self {
phantom: PhantomData,
}
}
}
impl<F> TransitionConstraint<F, F> for PermutationConstraint<F>
where
F: IsFFTField + Send + Sync,
{
fn degree(&self) -> usize {
2
}
fn constraint_idx(&self) -> usize {
1
}
fn end_exemptions(&self) -> usize {
1
}
fn evaluate(
&self,
evaluation_context: &TransitionEvaluationContext<F, F>,
transition_evaluations: &mut [FieldElement<F>],
) {
let (frame, _periodic_values, rap_challenges) = match evaluation_context {
TransitionEvaluationContext::Prover {
frame,
periodic_values,
rap_challenges,
}
| TransitionEvaluationContext::Verifier {
frame,
periodic_values,
rap_challenges,
} => (frame, periodic_values, rap_challenges),
};
let first_step = frame.get_evaluation_step(0);
let second_step = frame.get_evaluation_step(1);
// Auxiliary constraints
let z_i = first_step.get_aux_evaluation_element(0, 0);
let z_i_plus_one = second_step.get_aux_evaluation_element(0, 0);
let gamma = &rap_challenges[0];
let a_i = first_step.get_main_evaluation_element(0, 0);
let b_i = first_step.get_main_evaluation_element(0, 1);
let res = z_i_plus_one * (b_i + gamma) - z_i * (a_i + gamma);
transition_evaluations[self.constraint_idx()] = res;
}
}
pub struct FibonacciRAP<F>
where
F: IsFFTField,
{
context: AirContext,
trace_length: usize,
pub_inputs: FibonacciRAPPublicInputs<F>,
transition_constraints: Vec<Box<dyn TransitionConstraint<F, F>>>,
}
#[derive(Clone, Debug)]
pub struct FibonacciRAPPublicInputs<F>
where
F: IsFFTField,
{
pub steps: usize,
pub a0: FieldElement<F>,
pub a1: FieldElement<F>,
}
impl<F> AIR for FibonacciRAP<F>
where
F: IsFFTField + Send + Sync + 'static,
FieldElement<F>: ByteConversion,
{
type Field = F;
type FieldExtension = F;
type PublicInputs = FibonacciRAPPublicInputs<Self::Field>;
const STEP_SIZE: usize = 1;
fn new(
trace_length: usize,
pub_inputs: &Self::PublicInputs,
proof_options: &ProofOptions,
) -> Self {
let transition_constraints: Vec<
Box<dyn TransitionConstraint<Self::Field, Self::FieldExtension>>,
> = vec![
Box::new(FibConstraint::new()),
Box::new(PermutationConstraint::new()),
];
let context = AirContext {
proof_options: proof_options.clone(),
trace_columns: 3,
transition_offsets: vec![0, 1, 2],
num_transition_constraints: transition_constraints.len(),
};
Self {
context,
trace_length,
pub_inputs: pub_inputs.clone(),
transition_constraints,
}
}
fn build_auxiliary_trace(
&self,
trace: &mut TraceTable<Self::Field, Self::FieldExtension>,
challenges: &[FieldElement<F>],
) {
let main_segment_cols = trace.columns_main();
let not_perm = &main_segment_cols[0];
let perm = &main_segment_cols[1];
let gamma = &challenges[0];
let trace_len = trace.num_rows();
let mut aux_col = Vec::new();
for i in 0..trace_len {
if i == 0 {
aux_col.push(FieldElement::<Self::Field>::one());
} else {
let z_i = &aux_col[i - 1];
let n_p_term = not_perm[i - 1].clone() + gamma;
let p_term = &perm[i - 1] + gamma;
// We are using that with high probability p_term != 0 because gamma is a random element.
aux_col.push(z_i * n_p_term.div(p_term).unwrap());
}
}
for (i, aux_elem) in aux_col.iter().enumerate().take(trace.num_rows()) {
trace.set_aux(i, 0, aux_elem.clone())
}
}
fn build_rap_challenges(
&self,
transcript: &mut impl IsTranscript<Self::Field>,
) -> Vec<FieldElement<Self::FieldExtension>> {
vec![transcript.sample_field_element()]
}
fn trace_layout(&self) -> (usize, usize) {
(2, 1)
}
fn boundary_constraints(
&self,
_rap_challenges: &[FieldElement<Self::FieldExtension>],
) -> BoundaryConstraints<Self::FieldExtension> {
// Main boundary constraints
let a0 =
BoundaryConstraint::new_simple_main(0, FieldElement::<Self::FieldExtension>::one());
let a1 =
BoundaryConstraint::new_simple_main(1, FieldElement::<Self::FieldExtension>::one());
// Auxiliary boundary constraints
let a0_aux = BoundaryConstraint::new_aux(0, 0, FieldElement::<Self::FieldExtension>::one());
BoundaryConstraints::from_constraints(vec![a0, a1, a0_aux])
}
fn transition_constraints(
&self,
) -> &Vec<Box<dyn TransitionConstraint<Self::Field, Self::FieldExtension>>> {
&self.transition_constraints
}
fn context(&self) -> &AirContext {
&self.context
}
fn composition_poly_degree_bound(&self) -> usize {
self.trace_length()
}
fn trace_length(&self) -> usize {
self.trace_length
}
fn pub_inputs(&self) -> &Self::PublicInputs {
&self.pub_inputs
}
}
pub fn fibonacci_rap_trace<F: IsFFTField>(
initial_values: [FieldElement<F>; 2],
trace_length: usize,
) -> TraceTable<F, F> {
let mut fib_seq: Vec<FieldElement<F>> = vec![];
fib_seq.push(initial_values[0].clone());
fib_seq.push(initial_values[1].clone());
for i in 2..(trace_length) {
fib_seq.push(fib_seq[i - 1].clone() + fib_seq[i - 2].clone());
}
let last_value = fib_seq[trace_length - 1].clone();
let mut fib_permuted = fib_seq.clone();
fib_permuted[0] = last_value;
fib_permuted[trace_length - 1] = initial_values[0].clone();
fib_seq.push(FieldElement::<F>::zero());
fib_permuted.push(FieldElement::<F>::zero());
let mut trace_cols = vec![fib_seq, fib_permuted];
resize_to_next_power_of_two(&mut trace_cols);
let mut trace = TraceTable::allocate_with_zeros(trace_cols[0].len(), 2, 1, 1);
for i in 0..trace.num_rows() {
trace.set_main(i, 0, trace_cols[0][i].clone());
trace.set_main(i, 1, trace_cols[1][i].clone());
}
trace
}
#[cfg(test)]
mod test {
use super::*;
use lambdaworks_math::field::fields::u64_prime_field::FE17;
#[test]
fn test_build_fibonacci_rap_trace() {
// The fibonacci RAP trace should have two columns:
// * The usual fibonacci sequence column
// * The permuted fibonacci sequence column. The first and last elements are permuted.
// Also, a 0 is appended at the end of both columns. The reason for this can be read in
// https://hackmd.io/@aztec-network/plonk-arithmetiization-air#RAPs---PAIRs-with-interjected-verifier-randomness
let trace = fibonacci_rap_trace([FE17::from(1), FE17::from(1)], 8);
let mut expected_trace = vec![
vec![
FE17::one(),
FE17::one(),
FE17::from(2),
FE17::from(3),
FE17::from(5),
FE17::from(8),
FE17::from(13),
FE17::from(21),
FE17::zero(),
],
vec![
FE17::from(21),
FE17::one(),
FE17::from(2),
FE17::from(3),
FE17::from(5),
FE17::from(8),
FE17::from(13),
FE17::one(),
FE17::zero(),
],
];
resize_to_next_power_of_two(&mut expected_trace);
assert_eq!(trace.columns_main(), expected_trace);
}
#[test]
fn aux_col() {
let trace = fibonacci_rap_trace([FE17::from(1), FE17::from(1)], 64);
let trace_cols = trace.columns_main();
let not_perm = trace_cols[0].clone();
let perm = trace_cols[1].clone();
let gamma = FE17::from(10);
assert_eq!(perm.len(), not_perm.len());
let trace_len = not_perm.len();
let mut aux_col = Vec::new();
for i in 0..trace_len {
if i == 0 {
aux_col.push(FE17::one());
} else {
let z_i = aux_col[i - 1];
let n_p_term = not_perm[i - 1] + gamma;
let p_term = perm[i - 1] + gamma;
aux_col.push(z_i * n_p_term.div(p_term).unwrap());
}
}
assert_eq!(aux_col.last().unwrap(), &FE17::one());
}
}