Debian Codegraph @

third_party/rust/prio/src/polynomial.rs

raw
1 // Copyright (c) 2020 Apple Inc.
2 // SPDX-License-Identifier: MPL-2.0
3
4 //! Functions for polynomial interpolation and evaluation
5
6 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
7 use crate::fft::{discrete_fourier_transform, discrete_fourier_transform_inv_finish};
8 use crate::field::FftFriendlyFieldElement;
9
10 use std::convert::TryFrom;
11
12 /// Temporary memory used for FFT
13 #[derive(Clone, Debug)]
14 pub struct PolyFFTTempMemory<F> {
15 fft_tmp: Vec<F>,
16 fft_y_sub: Vec<F>,
17 fft_roots_sub: Vec<F>,
18 }
19
20 impl<F: FftFriendlyFieldElement> PolyFFTTempMemory<F> {
21 fn new(length: usize) -> Self {
22 PolyFFTTempMemory {
23 fft_tmp: vec![F::zero(); length],
24 fft_y_sub: vec![F::zero(); length],
25 fft_roots_sub: vec![F::zero(); length],
26 }
27 }
28 }
29
30 /// Auxiliary memory for polynomial interpolation and evaluation
31 #[derive(Clone, Debug)]
32 pub struct PolyAuxMemory<F> {
33 pub roots_2n: Vec<F>,
34 pub roots_2n_inverted: Vec<F>,
35 pub roots_n: Vec<F>,
36 pub roots_n_inverted: Vec<F>,
37 pub coeffs: Vec<F>,
38 pub fft_memory: PolyFFTTempMemory<F>,
39 }
40
41 impl<F: FftFriendlyFieldElement> PolyAuxMemory<F> {
42 pub fn new(n: usize) -> Self {
43 PolyAuxMemory {
44 roots_2n: fft_get_roots(2 * n, false),
45 roots_2n_inverted: fft_get_roots(2 * n, true),
46 roots_n: fft_get_roots(n, false),
47 roots_n_inverted: fft_get_roots(n, true),
48 coeffs: vec![F::zero(); 2 * n],
49 fft_memory: PolyFFTTempMemory::new(2 * n),
50 }
51 }
52 }
53
54 fn fft_recurse<F: FftFriendlyFieldElement>(
55 out: &mut [F],
56 n: usize,
57 roots: &[F],
58 ys: &[F],
59 tmp: &mut [F],
60 y_sub: &mut [F],
61 roots_sub: &mut [F],
62 ) {
63 if n == 1 {
64 out[0] = ys[0];
65 return;
66 }
67
68 let half_n = n / 2;
69
70 let (tmp_first, tmp_second) = tmp.split_at_mut(half_n);
71 let (y_sub_first, y_sub_second) = y_sub.split_at_mut(half_n);
72 let (roots_sub_first, roots_sub_second) = roots_sub.split_at_mut(half_n);
73
74 // Recurse on the first half
75 for i in 0..half_n {
76 y_sub_first[i] = ys[i] + ys[i + half_n];
77 roots_sub_first[i] = roots[2 * i];
78 }
79 fft_recurse(
80 tmp_first,
81 half_n,
82 roots_sub_first,
83 y_sub_first,
84 tmp_second,
85 y_sub_second,
86 roots_sub_second,
87 );
88 for i in 0..half_n {
89 out[2 * i] = tmp_first[i];
90 }
91
92 // Recurse on the second half
93 for i in 0..half_n {
94 y_sub_first[i] = ys[i] - ys[i + half_n];
95 y_sub_first[i] *= roots[i];
96 }
97 fft_recurse(
98 tmp_first,
99 half_n,
100 roots_sub_first,
101 y_sub_first,
102 tmp_second,
103 y_sub_second,
104 roots_sub_second,
105 );
106 for i in 0..half_n {
107 out[2 * i + 1] = tmp[i];
108 }
109 }
110
111 /// Calculate `count` number of roots of unity of order `count`
112 fn fft_get_roots<F: FftFriendlyFieldElement>(count: usize, invert: bool) -> Vec<F> {
113 let mut roots = vec![F::zero(); count];
114 let mut gen = F::generator();
115 if invert {
116 gen = gen.inv();
117 }
118
119 roots[0] = F::one();
120 let step_size = F::generator_order() / F::Integer::try_from(count).unwrap();
121 // generator for subgroup of order count
122 gen = gen.pow(step_size);
123
124 roots[1] = gen;
125
126 for i in 2..count {
127 roots[i] = gen * roots[i - 1];
128 }
129
130 roots
131 }
132
133 fn fft_interpolate_raw<F: FftFriendlyFieldElement>(
134 out: &mut [F],
135 ys: &[F],
136 n_points: usize,
137 roots: &[F],
138 invert: bool,
139 mem: &mut PolyFFTTempMemory<F>,
140 ) {
141 fft_recurse(
142 out,
143 n_points,
144 roots,
145 ys,
146 &mut mem.fft_tmp,
147 &mut mem.fft_y_sub,
148 &mut mem.fft_roots_sub,
149 );
150 if invert {
151 let n_inverse = F::from(F::Integer::try_from(n_points).unwrap()).inv();
152 for out_val in out[0..n_points].iter_mut() {
153 *out_val *= n_inverse;
154 }
155 }
156 }
157
158 pub fn poly_fft<F: FftFriendlyFieldElement>(
159 points_out: &mut [F],
160 points_in: &[F],
161 scaled_roots: &[F],
162 n_points: usize,
163 invert: bool,
164 mem: &mut PolyFFTTempMemory<F>,
165 ) {
166 fft_interpolate_raw(points_out, points_in, n_points, scaled_roots, invert, mem)
167 }
168
169 // Evaluate a polynomial using Horner's method.
170 pub fn poly_eval<F: FftFriendlyFieldElement>(poly: &[F], eval_at: F) -> F {
171 if poly.is_empty() {
172 return F::zero();
173 }
174
175 let mut result = poly[poly.len() - 1];
176 for i in (0..poly.len() - 1).rev() {
177 result *= eval_at;
178 result += poly[i];
179 }
180
181 result
182 }
183
184 // Returns the degree of polynomial `p`.
185 pub fn poly_deg<F: FftFriendlyFieldElement>(p: &[F]) -> usize {
186 let mut d = p.len();
187 while d > 0 && p[d - 1] == F::zero() {
188 d -= 1;
189 }
190 d.saturating_sub(1)
191 }
192
193 // Multiplies polynomials `p` and `q` and returns the result.
194 pub fn poly_mul<F: FftFriendlyFieldElement>(p: &[F], q: &[F]) -> Vec<F> {
195 let p_size = poly_deg(p) + 1;
196 let q_size = poly_deg(q) + 1;
197 let mut out = vec![F::zero(); p_size + q_size];
198 for i in 0..p_size {
199 for j in 0..q_size {
200 out[i + j] += p[i] * q[j];
201 }
202 }
203 out.truncate(poly_deg(&out) + 1);
204 out
205 }
206
207 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
208 #[inline]
209 pub fn poly_interpret_eval<F: FftFriendlyFieldElement>(
210 points: &[F],
211 eval_at: F,
212 tmp_coeffs: &mut [F],
213 ) -> F {
214 let size_inv = F::from(F::Integer::try_from(points.len()).unwrap()).inv();
215 discrete_fourier_transform(tmp_coeffs, points, points.len()).unwrap();
216 discrete_fourier_transform_inv_finish(tmp_coeffs, points.len(), size_inv);
217 poly_eval(&tmp_coeffs[..points.len()], eval_at)
218 }
219
220 // Returns a polynomial that evaluates to `0` if the input is in range `[start, end)`. Otherwise,
221 // the output is not `0`.
222 pub(crate) fn poly_range_check<F: FftFriendlyFieldElement>(start: usize, end: usize) -> Vec<F> {
223 let mut p = vec![F::one()];
224 let mut q = [F::zero(), F::one()];
225 for i in start..end {
226 q[0] = -F::from(F::Integer::try_from(i).unwrap());
227 p = poly_mul(&p, &q);
228 }
229 p
230 }
231
232 #[cfg(test)]
233 mod tests {
234 use crate::{
235 field::{
236 FftFriendlyFieldElement, Field64, FieldElement, FieldElementWithInteger, FieldPrio2,
237 },
238 polynomial::{
239 fft_get_roots, poly_deg, poly_eval, poly_fft, poly_mul, poly_range_check, PolyAuxMemory,
240 },
241 };
242 use rand::prelude::*;
243 use std::convert::TryFrom;
244
245 #[test]
246 fn test_roots() {
247 let count = 128;
248 let roots = fft_get_roots::<FieldPrio2>(count, false);
249 let roots_inv = fft_get_roots::<FieldPrio2>(count, true);
250
251 for i in 0..count {
252 assert_eq!(roots[i] * roots_inv[i], 1);
253 assert_eq!(roots[i].pow(u32::try_from(count).unwrap()), 1);
254 assert_eq!(roots_inv[i].pow(u32::try_from(count).unwrap()), 1);
255 }
256 }
257
258 #[test]
259 fn test_eval() {
260 let mut poly = [FieldPrio2::from(0); 4];
261 poly[0] = 2.into();
262 poly[1] = 1.into();
263 poly[2] = 5.into();
264 // 5*3^2 + 3 + 2 = 50
265 assert_eq!(poly_eval(&poly[..3], 3.into()), 50);
266 poly[3] = 4.into();
267 // 4*3^3 + 5*3^2 + 3 + 2 = 158
268 assert_eq!(poly_eval(&poly[..4], 3.into()), 158);
269 }
270
271 #[test]
272 fn test_poly_deg() {
273 let zero = FieldPrio2::zero();
274 let one = FieldPrio2::root(0).unwrap();
275 assert_eq!(poly_deg(&[zero]), 0);
276 assert_eq!(poly_deg(&[one]), 0);
277 assert_eq!(poly_deg(&[zero, one]), 1);
278 assert_eq!(poly_deg(&[zero, zero, one]), 2);
279 assert_eq!(poly_deg(&[zero, one, one]), 2);
280 assert_eq!(poly_deg(&[zero, one, one, one]), 3);
281 assert_eq!(poly_deg(&[zero, one, one, one, zero]), 3);
282 assert_eq!(poly_deg(&[zero, one, one, one, zero, zero]), 3);
283 }
284
285 #[test]
286 fn test_poly_mul() {
287 let p = [
288 Field64::from(u64::try_from(2).unwrap()),
289 Field64::from(u64::try_from(3).unwrap()),
290 ];
291
292 let q = [
293 Field64::one(),
294 Field64::zero(),
295 Field64::from(u64::try_from(5).unwrap()),
296 ];
297
298 let want = [
299 Field64::from(u64::try_from(2).unwrap()),
300 Field64::from(u64::try_from(3).unwrap()),
301 Field64::from(u64::try_from(10).unwrap()),
302 Field64::from(u64::try_from(15).unwrap()),
303 ];
304
305 let got = poly_mul(&p, &q);
306 assert_eq!(&got, &want);
307 }
308
309 #[test]
310 fn test_poly_range_check() {
311 let start = 74;
312 let end = 112;
313 let p = poly_range_check(start, end);
314
315 // Check each number in the range.
316 for i in start..end {
317 let x = Field64::from(i as u64);
318 let y = poly_eval(&p, x);
319 assert_eq!(y, Field64::zero(), "range check failed for {i}");
320 }
321
322 // Check the number below the range.
323 let x = Field64::from((start - 1) as u64);
324 let y = poly_eval(&p, x);
325 assert_ne!(y, Field64::zero());
326
327 // Check a number above the range.
328 let x = Field64::from(end as u64);
329 let y = poly_eval(&p, x);
330 assert_ne!(y, Field64::zero());
331 }
332
333 #[test]
334 fn test_fft() {
335 let count = 128;
336 let mut mem = PolyAuxMemory::new(count / 2);
337
338 let mut poly = vec![FieldPrio2::from(0); count];
339 let mut points2 = vec![FieldPrio2::from(0); count];
340
341 let points = (0..count)
342 .map(|_| FieldPrio2::from(random::<u32>()))
343 .collect::<Vec<FieldPrio2>>();
344
345 // From points to coeffs and back
346 poly_fft(
347 &mut poly,
348 &points,
349 &mem.roots_2n,
350 count,
351 false,
352 &mut mem.fft_memory,
353 );
354 poly_fft(
355 &mut points2,
356 &poly,
357 &mem.roots_2n_inverted,
358 count,
359 true,
360 &mut mem.fft_memory,
361 );
362
363 assert_eq!(points, points2);
364
365 // interpolation
366 poly_fft(
367 &mut poly,
368 &points,
369 &mem.roots_2n,
370 count,
371 false,
372 &mut mem.fft_memory,
373 );
374
375 for (poly_coeff, root) in poly[..count].iter().zip(mem.roots_2n[..count].iter()) {
376 let mut should_be = FieldPrio2::from(0);
377 for (j, point_j) in points[..count].iter().enumerate() {
378 should_be = root.pow(u32::try_from(j).unwrap()) * *point_j + should_be;
379 }
380 assert_eq!(should_be, *poly_coeff);
381 }
382 }
383 }