Debian Codegraph @

third_party/rust/prio/src/fp.rs

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 //! Finite field arithmetic for any field GF(p) for which p < 2^128.
4
5 #[cfg(test)]
6 use rand::{prelude::*, Rng};
7
8 /// For each set of field parameters we pre-compute the 1st, 2nd, 4th, ..., 2^20-th principal roots
9 /// of unity. The largest of these is used to run the FFT algorithm on an input of size 2^20. This
10 /// is the largest input size we would ever need for the cryptographic applications in this crate.
11 pub(crate) const MAX_ROOTS: usize = 20;
12
13 /// This structure represents the parameters of a finite field GF(p) for which p < 2^128.
14 #[derive(Debug, PartialEq, Eq)]
15 pub(crate) struct FieldParameters {
16 /// The prime modulus `p`.
17 pub p: u128,
18 /// `mu = -p^(-1) mod 2^64`.
19 pub mu: u64,
20 /// `r2 = (2^128)^2 mod p`.
21 pub r2: u128,
22 /// The `2^num_roots`-th -principal root of unity. This element is used to generate the
23 /// elements of `roots`.
24 pub g: u128,
25 /// The number of principal roots of unity in `roots`.
26 pub num_roots: usize,
27 /// Equal to `2^b - 1`, where `b` is the length of `p` in bits.
28 pub bit_mask: u128,
29 /// `roots[l]` is the `2^l`-th principal root of unity, i.e., `roots[l]` has order `2^l` in the
30 /// multiplicative group. `roots[0]` is equal to one by definition.
31 pub roots: [u128; MAX_ROOTS + 1],
32 }
33
34 impl FieldParameters {
35 /// Addition. The result will be in [0, p), so long as both x and y are as well.
36 #[inline(always)]
37 pub fn add(&self, x: u128, y: u128) -> u128 {
38 // 0,x
39 // + 0,y
40 // =====
41 // c,z
42 let (z, carry) = x.overflowing_add(y);
43 // c, z
44 // - 0, p
45 // ========
46 // b1,s1,s0
47 let (s0, b0) = z.overflowing_sub(self.p);
48 let (_s1, b1) = (carry as u128).overflowing_sub(b0 as u128);
49 // if b1 == 1: return z
50 // else: return s0
51 let m = 0u128.wrapping_sub(b1 as u128);
52 (z & m) | (s0 & !m)
53 }
54
55 /// Subtraction. The result will be in [0, p), so long as both x and y are as well.
56 #[inline(always)]
57 pub fn sub(&self, x: u128, y: u128) -> u128 {
58 // 0, x
59 // - 0, y
60 // ========
61 // b1,z1,z0
62 let (z0, b0) = x.overflowing_sub(y);
63 let (_z1, b1) = 0u128.overflowing_sub(b0 as u128);
64 let m = 0u128.wrapping_sub(b1 as u128);
65 // z1,z0
66 // + 0, p
67 // ========
68 // s1,s0
69 z0.wrapping_add(m & self.p)
70 // if b1 == 1: return s0
71 // else: return z0
72 }
73
74 /// Multiplication of field elements in the Montgomery domain. This uses the REDC algorithm
75 /// described
76 /// [here](https://www.ams.org/journals/mcom/1985-44-170/S0025-5718-1985-0777282-X/S0025-5718-1985-0777282-X.pdf).
77 /// The result will be in [0, p).
78 ///
79 /// # Example usage
80 /// ```text
81 /// assert_eq!(fp.residue(fp.mul(fp.montgomery(23), fp.montgomery(2))), 46);
82 /// ```
83 #[inline(always)]
84 pub fn mul(&self, x: u128, y: u128) -> u128 {
85 let x = [lo64(x), hi64(x)];
86 let y = [lo64(y), hi64(y)];
87 let p = [lo64(self.p), hi64(self.p)];
88 let mut zz = [0; 4];
89
90 // Integer multiplication
91 // z = x * y
92
93 // x1,x0
94 // * y1,y0
95 // ===========
96 // z3,z2,z1,z0
97 let mut result = x[0] * y[0];
98 let mut carry = hi64(result);
99 zz[0] = lo64(result);
100 result = x[0] * y[1];
101 let mut hi = hi64(result);
102 let mut lo = lo64(result);
103 result = lo + carry;
104 zz[1] = lo64(result);
105 let mut cc = hi64(result);
106 result = hi + cc;
107 zz[2] = lo64(result);
108
109 result = x[1] * y[0];
110 hi = hi64(result);
111 lo = lo64(result);
112 result = zz[1] + lo;
113 zz[1] = lo64(result);
114 cc = hi64(result);
115 result = hi + cc;
116 carry = lo64(result);
117
118 result = x[1] * y[1];
119 hi = hi64(result);
120 lo = lo64(result);
121 result = lo + carry;
122 lo = lo64(result);
123 cc = hi64(result);
124 result = hi + cc;
125 hi = lo64(result);
126 result = zz[2] + lo;
127 zz[2] = lo64(result);
128 cc = hi64(result);
129 result = hi + cc;
130 zz[3] = lo64(result);
131
132 // Montgomery Reduction
133 // z = z + p * mu*(z mod 2^64), where mu = (-p)^(-1) mod 2^64.
134
135 // z3,z2,z1,z0
136 // + p1,p0
137 // * w = mu*z0
138 // ===========
139 // z3,z2,z1, 0
140 let w = self.mu.wrapping_mul(zz[0] as u64);
141 result = p[0] * (w as u128);
142 hi = hi64(result);
143 lo = lo64(result);
144 result = zz[0] + lo;
145 zz[0] = lo64(result);
146 cc = hi64(result);
147 result = hi + cc;
148 carry = lo64(result);
149
150 result = p[1] * (w as u128);
151 hi = hi64(result);
152 lo = lo64(result);
153 result = lo + carry;
154 lo = lo64(result);
155 cc = hi64(result);
156 result = hi + cc;
157 hi = lo64(result);
158 result = zz[1] + lo;
159 zz[1] = lo64(result);
160 cc = hi64(result);
161 result = zz[2] + hi + cc;
162 zz[2] = lo64(result);
163 cc = hi64(result);
164 result = zz[3] + cc;
165 zz[3] = lo64(result);
166
167 // z3,z2,z1
168 // + p1,p0
169 // * w = mu*z1
170 // ===========
171 // z3,z2, 0
172 let w = self.mu.wrapping_mul(zz[1] as u64);
173 result = p[0] * (w as u128);
174 hi = hi64(result);
175 lo = lo64(result);
176 result = zz[1] + lo;
177 zz[1] = lo64(result);
178 cc = hi64(result);
179 result = hi + cc;
180 carry = lo64(result);
181
182 result = p[1] * (w as u128);
183 hi = hi64(result);
184 lo = lo64(result);
185 result = lo + carry;
186 lo = lo64(result);
187 cc = hi64(result);
188 result = hi + cc;
189 hi = lo64(result);
190 result = zz[2] + lo;
191 zz[2] = lo64(result);
192 cc = hi64(result);
193 result = zz[3] + hi + cc;
194 zz[3] = lo64(result);
195 cc = hi64(result);
196
197 // z = (z3,z2)
198 let prod = zz[2] | (zz[3] << 64);
199
200 // Final subtraction
201 // If z >= p, then z = z - p
202
203 // 0, z
204 // - 0, p
205 // ========
206 // b1,s1,s0
207 let (s0, b0) = prod.overflowing_sub(self.p);
208 let (_s1, b1) = cc.overflowing_sub(b0 as u128);
209 // if b1 == 1: return z
210 // else: return s0
211 let mask = 0u128.wrapping_sub(b1 as u128);
212 (prod & mask) | (s0 & !mask)
213 }
214
215 /// Modular exponentiation, i.e., `x^exp (mod p)` where `p` is the modulus. Note that the
216 /// runtime of this algorithm is linear in the bit length of `exp`.
217 pub fn pow(&self, x: u128, exp: u128) -> u128 {
218 let mut t = self.montgomery(1);
219 for i in (0..128 - exp.leading_zeros()).rev() {
220 t = self.mul(t, t);
221 if (exp >> i) & 1 != 0 {
222 t = self.mul(t, x);
223 }
224 }
225 t
226 }
227
228 /// Modular inversion, i.e., x^-1 (mod p) where `p` is the modulus. Note that the runtime of
229 /// this algorithm is linear in the bit length of `p`.
230 #[inline(always)]
231 pub fn inv(&self, x: u128) -> u128 {
232 self.pow(x, self.p - 2)
233 }
234
235 /// Negation, i.e., `-x (mod p)` where `p` is the modulus.
236 #[inline(always)]
237 pub fn neg(&self, x: u128) -> u128 {
238 self.sub(0, x)
239 }
240
241 /// Maps an integer to its internal representation. Field elements are mapped to the Montgomery
242 /// domain in order to carry out field arithmetic. The result will be in [0, p).
243 ///
244 /// # Example usage
245 /// ```text
246 /// let integer = 1; // Standard integer representation
247 /// let elem = fp.montgomery(integer); // Internal representation in the Montgomery domain
248 /// assert_eq!(elem, 2564090464);
249 /// ```
250 #[inline(always)]
251 pub fn montgomery(&self, x: u128) -> u128 {
252 modp(self.mul(x, self.r2), self.p)
253 }
254
255 /// Returns a random field element mapped.
256 #[cfg(test)]
257 pub fn rand_elem<R: Rng + ?Sized>(&self, rng: &mut R) -> u128 {
258 let uniform = rand::distributions::Uniform::from(0..self.p);
259 self.montgomery(uniform.sample(rng))
260 }
261
262 /// Maps a field element to its representation as an integer. The result will be in [0, p).
263 ///
264 /// #Example usage
265 /// ```text
266 /// let elem = 2564090464; // Internal representation in the Montgomery domain
267 /// let integer = fp.residue(elem); // Standard integer representation
268 /// assert_eq!(integer, 1);
269 /// ```
270 #[inline(always)]
271 pub fn residue(&self, x: u128) -> u128 {
272 modp(self.mul(x, 1), self.p)
273 }
274
275 #[cfg(test)]
276 pub fn check(&self, p: u128, g: u128, order: u128) {
277 use modinverse::modinverse;
278 use num_bigint::{BigInt, ToBigInt};
279 use std::cmp::max;
280
281 assert_eq!(self.p, p, "p mismatch");
282
283 let mu = match modinverse((-(p as i128)).rem_euclid(1 << 64), 1 << 64) {
284 Some(mu) => mu as u64,
285 None => panic!("inverse of -p (mod 2^64) is undefined"),
286 };
287 assert_eq!(self.mu, mu, "mu mismatch");
288
289 let big_p = &p.to_bigint().unwrap();
290 let big_r: &BigInt = &(&(BigInt::from(1) << 128) % big_p);
291 let big_r2: &BigInt = &(&(big_r * big_r) % big_p);
292 let mut it = big_r2.iter_u64_digits();
293 let mut r2 = 0;
294 r2 |= it.next().unwrap() as u128;
295 if let Some(x) = it.next() {
296 r2 |= (x as u128) << 64;
297 }
298 assert_eq!(self.r2, r2, "r2 mismatch");
299
300 assert_eq!(self.g, self.montgomery(g), "g mismatch");
301 assert_eq!(
302 self.residue(self.pow(self.g, order)),
303 1,
304 "g order incorrect"
305 );
306
307 let num_roots = log2(order) as usize;
308 assert_eq!(order, 1 << num_roots, "order not a power of 2");
309 assert_eq!(self.num_roots, num_roots, "num_roots mismatch");
310
311 let mut roots = vec![0; max(num_roots, MAX_ROOTS) + 1];
312 roots[num_roots] = self.montgomery(g);
313 for i in (0..num_roots).rev() {
314 roots[i] = self.mul(roots[i + 1], roots[i + 1]);
315 }
316 assert_eq!(&self.roots, &roots[..MAX_ROOTS + 1], "roots mismatch");
317 assert_eq!(self.residue(self.roots[0]), 1, "first root is not one");
318
319 let bit_mask = (BigInt::from(1) << big_p.bits()) - BigInt::from(1);
320 assert_eq!(
321 self.bit_mask.to_bigint().unwrap(),
322 bit_mask,
323 "bit_mask mismatch"
324 );
325 }
326 }
327
328 #[inline(always)]
329 fn lo64(x: u128) -> u128 {
330 x & ((1 << 64) - 1)
331 }
332
333 #[inline(always)]
334 fn hi64(x: u128) -> u128 {
335 x >> 64
336 }
337
338 #[inline(always)]
339 fn modp(x: u128, p: u128) -> u128 {
340 let (z, carry) = x.overflowing_sub(p);
341 let m = 0u128.wrapping_sub(carry as u128);
342 z.wrapping_add(m & p)
343 }
344
345 pub(crate) const FP32: FieldParameters = FieldParameters {
346 p: 4293918721, // 32-bit prime
347 mu: 17302828673139736575,
348 r2: 1676699750,
349 g: 1074114499,
350 num_roots: 20,
351 bit_mask: 4294967295,
352 roots: [
353 2564090464, 1729828257, 306605458, 2294308040, 1648889905, 57098624, 2788941825,
354 2779858277, 368200145, 2760217336, 594450960, 4255832533, 1372848488, 721329415,
355 3873251478, 1134002069, 7138597, 2004587313, 2989350643, 725214187, 1074114499,
356 ],
357 };
358
359 pub(crate) const FP64: FieldParameters = FieldParameters {
360 p: 18446744069414584321, // 64-bit prime
361 mu: 18446744069414584319,
362 r2: 4294967295,
363 g: 959634606461954525,
364 num_roots: 32,
365 bit_mask: 18446744073709551615,
366 roots: [
367 18446744065119617025,
368 4294967296,
369 18446462594437939201,
370 72057594037927936,
371 1152921504338411520,
372 16384,
373 18446743519658770561,
374 18446735273187346433,
375 6519596376689022014,
376 9996039020351967275,
377 15452408553935940313,
378 15855629130643256449,
379 8619522106083987867,
380 13036116919365988132,
381 1033106119984023956,
382 16593078884869787648,
383 16980581328500004402,
384 12245796497946355434,
385 8709441440702798460,
386 8611358103550827629,
387 8120528636261052110,
388 ],
389 };
390
391 pub(crate) const FP128: FieldParameters = FieldParameters {
392 p: 340282366920938462946865773367900766209, // 128-bit prime
393 mu: 18446744073709551615,
394 r2: 403909908237944342183153,
395 g: 107630958476043550189608038630704257141,
396 num_roots: 66,
397 bit_mask: 340282366920938463463374607431768211455,
398 roots: [
399 516508834063867445247,
400 340282366920938462430356939304033320962,
401 129526470195413442198896969089616959958,
402 169031622068548287099117778531474117974,
403 81612939378432101163303892927894236156,
404 122401220764524715189382260548353967708,
405 199453575871863981432000940507837456190,
406 272368408887745135168960576051472383806,
407 24863773656265022616993900367764287617,
408 257882853788779266319541142124730662203,
409 323732363244658673145040701829006542956,
410 57532865270871759635014308631881743007,
411 149571414409418047452773959687184934208,
412 177018931070866797456844925926211239962,
413 268896136799800963964749917185333891349,
414 244556960591856046954834420512544511831,
415 118945432085812380213390062516065622346,
416 202007153998709986841225284843501908420,
417 332677126194796691532164818746739771387,
418 258279638927684931537542082169183965856,
419 148221243758794364405224645520862378432,
420 ],
421 };
422
423 // Compute the ceiling of the base-2 logarithm of `x`.
424 pub(crate) fn log2(x: u128) -> u128 {
425 let y = (127 - x.leading_zeros()) as u128;
426 y + ((x > 1 << y) as u128)
427 }
428
429 #[cfg(test)]
430 mod tests {
431 use super::*;
432 use num_bigint::ToBigInt;
433
434 #[test]
435 fn test_log2() {
436 assert_eq!(log2(1), 0);
437 assert_eq!(log2(2), 1);
438 assert_eq!(log2(3), 2);
439 assert_eq!(log2(4), 2);
440 assert_eq!(log2(15), 4);
441 assert_eq!(log2(16), 4);
442 assert_eq!(log2(30), 5);
443 assert_eq!(log2(32), 5);
444 assert_eq!(log2(1 << 127), 127);
445 assert_eq!(log2((1 << 127) + 13), 128);
446 }
447
448 struct TestFieldParametersData {
449 fp: FieldParameters, // The paramters being tested
450 expected_p: u128, // Expected fp.p
451 expected_g: u128, // Expected fp.residue(fp.g)
452 expected_order: u128, // Expect fp.residue(fp.pow(fp.g, expected_order)) == 1
453 }
454
455 #[test]
456 fn test_fp() {
457 let test_fps = vec![
458 TestFieldParametersData {
459 fp: FP32,
460 expected_p: 4293918721,
461 expected_g: 3925978153,
462 expected_order: 1 << 20,
463 },
464 TestFieldParametersData {
465 fp: FP64,
466 expected_p: 18446744069414584321,
467 expected_g: 1753635133440165772,
468 expected_order: 1 << 32,
469 },
470 TestFieldParametersData {
471 fp: FP128,
472 expected_p: 340282366920938462946865773367900766209,
473 expected_g: 145091266659756586618791329697897684742,
474 expected_order: 1 << 66,
475 },
476 ];
477
478 for t in test_fps.into_iter() {
479 // Check that the field parameters have been constructed properly.
480 t.fp.check(t.expected_p, t.expected_g, t.expected_order);
481
482 // Check that the generator has the correct order.
483 assert_eq!(t.fp.residue(t.fp.pow(t.fp.g, t.expected_order)), 1);
484 assert_ne!(t.fp.residue(t.fp.pow(t.fp.g, t.expected_order / 2)), 1);
485
486 // Test arithmetic using the field parameters.
487 arithmetic_test(&t.fp);
488 }
489 }
490
491 fn arithmetic_test(fp: &FieldParameters) {
492 let mut rng = rand::thread_rng();
493 let big_p = &fp.p.to_bigint().unwrap();
494
495 for _ in 0..100 {
496 let x = fp.rand_elem(&mut rng);
497 let y = fp.rand_elem(&mut rng);
498 let big_x = &fp.residue(x).to_bigint().unwrap();
499 let big_y = &fp.residue(y).to_bigint().unwrap();
500
501 // Test addition.
502 let got = fp.add(x, y);
503 let want = (big_x + big_y) % big_p;
504 assert_eq!(fp.residue(got).to_bigint().unwrap(), want);
505
506 // Test subtraction.
507 let got = fp.sub(x, y);
508 let want = if big_x >= big_y {
509 big_x - big_y
510 } else {
511 big_p - big_y + big_x
512 };
513 assert_eq!(fp.residue(got).to_bigint().unwrap(), want);
514
515 // Test multiplication.
516 let got = fp.mul(x, y);
517 let want = (big_x * big_y) % big_p;
518 assert_eq!(fp.residue(got).to_bigint().unwrap(), want);
519
520 // Test inversion.
521 let got = fp.inv(x);
522 let want = big_x.modpow(&(big_p - 2u128), big_p);
523 assert_eq!(fp.residue(got).to_bigint().unwrap(), want);
524 assert_eq!(fp.residue(fp.mul(got, x)), 1);
525
526 // Test negation.
527 let got = fp.neg(x);
528 let want = (big_p - big_x) % big_p;
529 assert_eq!(fp.residue(got).to_bigint().unwrap(), want);
530 assert_eq!(fp.residue(fp.add(got, x)), 0);
531 }
532 }
533 }