Address new rustc warnings around unused variables
[dnssec-prover] / src / crypto / bigint.rs
1 //! Simple variable-time big integer implementation
2
3 use alloc::vec::Vec;
4 use core::marker::PhantomData;
5
6 // **************************************
7 // * Implementations of math primitives *
8 // **************************************
9
10 macro_rules! debug_unwrap { ($v: expr) => { {
11         let v = $v;
12         debug_assert!(v.is_ok());
13         match v {
14                 Ok(r) => r,
15                 Err(e) => return Err(e),
16         }
17 } } }
18
19 // Various const versions of existing slice utilities
20 /// Const version of `&a[start..end]`
21 const fn const_subslice<'a, T>(a: &'a [T], start: usize, end: usize) -> &'a [T] {
22         assert!(start <= a.len());
23         assert!(end <= a.len());
24         assert!(end >= start);
25         let mut startptr = a.as_ptr();
26         startptr = unsafe { startptr.add(start) };
27         let len = end - start;
28         // The docs for from_raw_parts do not mention any requirements that the pointer be valid if the
29         // length is zero, aside from requiring proper alignment (which is met here). Thus,
30         // one-past-the-end should be an acceptable pointer for a 0-length slice.
31         unsafe { alloc::slice::from_raw_parts(startptr, len) }
32 }
33
34 /// Const version of `dest[dest_start..dest_end].copy_from_slice(source)`
35 ///
36 /// Once `const_mut_refs` is stable we can convert this to a function
37 macro_rules! copy_from_slice {
38         ($dest: ident, $dest_start: expr, $dest_end: expr, $source: ident) => { {
39                 let dest_start = $dest_start;
40                 let dest_end = $dest_end;
41                 assert!(dest_start <= $dest.len());
42                 assert!(dest_end <= $dest.len());
43                 assert!(dest_end >= dest_start);
44                 assert!(dest_end - dest_start == $source.len());
45                 let mut i = 0;
46                 while i < $source.len() {
47                         $dest[i + dest_start] = $source[i];
48                         i += 1;
49                 }
50         } }
51 }
52
53 /// Const version of a > b
54 const fn slice_greater_than(a: &[u64], b: &[u64]) -> bool {
55         debug_assert!(a.len() == b.len());
56         let len = if a.len() <= b.len() { a.len() } else { b.len() };
57         let mut i = 0;
58         while i < len {
59                 if a[i] > b[i] { return true; }
60                 else if a[i] < b[i] { return false; }
61                 i += 1;
62         }
63         false // Equal
64 }
65
66 /// Const version of a == b
67 const fn slice_equal(a: &[u64], b: &[u64]) -> bool {
68         debug_assert!(a.len() == b.len());
69         let len = if a.len() <= b.len() { a.len() } else { b.len() };
70         let mut i = 0;
71         while i < len {
72                 if a[i] != b[i] { return false; }
73                 i += 1;
74         }
75         true
76 }
77
78 /// Adds a single u64 valuein-place, returning an overflow flag, in which case one out-of-bounds
79 /// high bit is implicitly included in the result.
80 ///
81 /// Once `const_mut_refs` is stable we can convert this to a function
82 macro_rules! add_u64 { ($a: ident, $b: expr) => { {
83         let len = $a.len();
84         let mut i = len - 1;
85         let mut add = $b;
86         loop {
87                 let (v, carry) = $a[i].overflowing_add(add);
88                 $a[i] = v;
89                 add = carry as u64;
90                 if add == 0 { break; }
91
92                 if i == 0 { break; }
93                 i -= 1;
94         }
95         add != 0
96 } } }
97
98 /// Negates the given u64 slice.
99 ///
100 /// Once `const_mut_refs` is stable we can convert this to a function
101 macro_rules! negate { ($v: ident) => { {
102         let mut i = 0;
103         while i < $v.len() {
104                 $v[i] ^= 0xffff_ffff_ffff_ffff;
105                 i += 1;
106         }
107         let _ = add_u64!($v, 1);
108 } } }
109
110 /// Doubles in-place, returning an overflow flag, in which case one out-of-bounds high bit is
111 /// implicitly included in the result.
112 ///
113 /// Once `const_mut_refs` is stable we can convert this to a function
114 macro_rules! double { ($a: ident) => { {
115         { let _: &[u64] = &$a; } // Force type resolution
116         let len = $a.len();
117         let mut carry = false;
118         let mut i = len - 1;
119         loop {
120                 let next_carry = ($a[i] & (1 << 63)) != 0;
121                 let (v, _next_carry_2) = ($a[i] << 1).overflowing_add(carry as u64);
122                 if !next_carry {
123                         debug_assert!(!_next_carry_2, "Adding one to 0x7ffff..*2 is only 0xffff..");
124                 }
125                 // Note that we can ignore _next_carry_2 here as we never need it - it cannot be set if
126                 // next_carry is not set and at max 0xffff..*2 + 1 is only 0x1ffff.. (i.e. we can not need
127                 // a double-carry).
128                 $a[i] = v;
129                 carry = next_carry;
130
131                 if i == 0 { break; }
132                 i -= 1;
133         }
134         carry
135 } } }
136
137 macro_rules! define_add { ($name: ident, $len: expr) => {
138         /// Adds two $len-64-bit integers together, returning a new $len-64-bit integer and an overflow
139         /// bit, with the same semantics as the std [`u64::overflowing_add`] method.
140         const fn $name(a: &[u64], b: &[u64]) -> ([u64; $len], bool) {
141                 debug_assert!(a.len() == $len);
142                 debug_assert!(b.len() == $len);
143                 let mut r = [0; $len];
144                 let mut carry = false;
145                 let mut i = $len - 1;
146                 loop {
147                         let (v, mut new_carry) = a[i].overflowing_add(b[i]);
148                         let (v2, new_new_carry) = v.overflowing_add(carry as u64);
149                         new_carry |= new_new_carry;
150                         r[i] = v2;
151                         carry = new_carry;
152
153                         if i == 0 { break; }
154                         i -= 1;
155                 }
156                 (r, carry)
157         }
158 } }
159
160 define_add!(add_2, 2);
161 define_add!(add_3, 3);
162 define_add!(add_4, 4);
163 define_add!(add_6, 6);
164 define_add!(add_8, 8);
165 define_add!(add_12, 12);
166 define_add!(add_16, 16);
167 define_add!(add_32, 32);
168 define_add!(add_64, 64);
169 define_add!(add_128, 128);
170
171 macro_rules! define_sub { ($name: ident, $name_abs: ident, $len: expr) => {
172         /// Subtracts the `b` $len-64-bit integer from the `a` $len-64-bit integer, returning a new
173         /// $len-64-bit integer and an overflow bit, with the same semantics as the std
174         /// [`u64::overflowing_sub`] method.
175         const fn $name(a: &[u64], b: &[u64]) -> ([u64; $len], bool) {
176                 debug_assert!(a.len() == $len);
177                 debug_assert!(b.len() == $len);
178                 let mut r = [0; $len];
179                 let mut carry = false;
180                 let mut i = $len - 1;
181                 loop {
182                         let (v, mut new_carry) = a[i].overflowing_sub(b[i]);
183                         let (v2, new_new_carry) = v.overflowing_sub(carry as u64);
184                         new_carry |= new_new_carry;
185                         r[i] = v2;
186                         carry = new_carry;
187
188                         if i == 0 { break; }
189                         i -= 1;
190                 }
191                 (r, carry)
192         }
193
194         /// Subtracts the `b` $len-64-bit integer from the `a` $len-64-bit integer, returning a new
195         /// $len-64-bit integer representing the absolute value of the result, as well as a sign bit.
196         #[allow(unused)]
197         const fn $name_abs(a: &[u64], b: &[u64]) -> ([u64; $len], bool) {
198                 let (mut res, neg) = $name(a, b);
199                 if neg {
200                         negate!(res);
201                 }
202                 (res, neg)
203         }
204 } }
205
206 define_sub!(sub_2, sub_abs_2, 2);
207 define_sub!(sub_3, sub_abs_3, 3);
208 define_sub!(sub_4, sub_abs_4, 4);
209 define_sub!(sub_6, sub_abs_6, 6);
210 define_sub!(sub_8, sub_abs_8, 8);
211 define_sub!(sub_12, sub_abs_12, 12);
212 define_sub!(sub_16, sub_abs_16, 16);
213 define_sub!(sub_32, sub_abs_32, 32);
214 define_sub!(sub_64, sub_abs_64, 64);
215 define_sub!(sub_128, sub_abs_128, 128);
216
217 /// Multiplies two 128-bit integers together, returning a new 256-bit integer.
218 ///
219 /// This is the base case for our multiplication, taking advantage of Rust's native 128-bit int
220 /// types to do multiplication (potentially) natively.
221 const fn mul_2(a: &[u64], b: &[u64]) -> [u64; 4] {
222         debug_assert!(a.len() == 2);
223         debug_assert!(b.len() == 2);
224
225         // Gradeschool multiplication is way faster here.
226         let (a0, a1) = (a[0] as u128, a[1] as u128);
227         let (b0, b1) = (b[0] as u128, b[1] as u128);
228         let z2 = a0 * b0;
229         let z1i = a0 * b1;
230         let z1j = b0 * a1;
231         let (z1, i_carry_a) = z1i.overflowing_add(z1j);
232         let z0 = a1 * b1;
233
234         add_mul_2_parts(z2, z1, z0, i_carry_a)
235 }
236
237 /// Adds the gradeschool multiplication intermediate parts to a final 256-bit result
238 const fn add_mul_2_parts(z2: u128, z1: u128, z0: u128, i_carry_a: bool) -> [u64; 4] {
239         let z2a = ((z2 >> 64) & 0xffff_ffff_ffff_ffff) as u64;
240         let z1a = ((z1 >> 64) & 0xffff_ffff_ffff_ffff) as u64;
241         let z0a = ((z0 >> 64) & 0xffff_ffff_ffff_ffff) as u64;
242         let z2b = (z2 & 0xffff_ffff_ffff_ffff) as u64;
243         let z1b = (z1 & 0xffff_ffff_ffff_ffff) as u64;
244         let z0b = (z0 & 0xffff_ffff_ffff_ffff) as u64;
245
246         let l = z0b;
247
248         let (k, j_carry) = z0a.overflowing_add(z1b);
249
250         let (mut j, i_carry_b) = z1a.overflowing_add(z2b);
251         let i_carry_c;
252         (j, i_carry_c) = j.overflowing_add(j_carry as u64);
253
254         let i_carry = i_carry_a as u64 + i_carry_b as u64 + i_carry_c as u64;
255         let (i, must_not_overflow) = z2a.overflowing_add(i_carry);
256         debug_assert!(!must_not_overflow, "Two 2*64 bit numbers, multiplied, will not use more than 4*64 bits");
257
258         [i, j, k, l]
259 }
260
261 const fn mul_3(a: &[u64], b: &[u64]) -> [u64; 6] {
262         debug_assert!(a.len() == 3);
263         debug_assert!(b.len() == 3);
264
265         let (a0, a1, a2) = (a[0] as u128, a[1] as u128, a[2] as u128);
266         let (b0, b1, b2) = (b[0] as u128, b[1] as u128, b[2] as u128);
267
268         let m4 = a2 * b2;
269         let m3a = a2 * b1;
270         let m3b = a1 * b2;
271         let m2a = a2 * b0;
272         let m2b = a1 * b1;
273         let m2c = a0 * b2;
274         let m1a = a1 * b0;
275         let m1b = a0 * b1;
276         let m0 = a0 * b0;
277
278         let r5 = ((m4 >> 0) & 0xffff_ffff_ffff_ffff) as u64;
279
280         let r4a = ((m4 >> 64) & 0xffff_ffff_ffff_ffff) as u64;
281         let r4b = ((m3a >> 0) & 0xffff_ffff_ffff_ffff) as u64;
282         let r4c = ((m3b >> 0) & 0xffff_ffff_ffff_ffff) as u64;
283
284         let r3a = ((m3a >> 64) & 0xffff_ffff_ffff_ffff) as u64;
285         let r3b = ((m3b >> 64) & 0xffff_ffff_ffff_ffff) as u64;
286         let r3c = ((m2a >> 0 ) & 0xffff_ffff_ffff_ffff) as u64;
287         let r3d = ((m2b >> 0 ) & 0xffff_ffff_ffff_ffff) as u64;
288         let r3e = ((m2c >> 0 ) & 0xffff_ffff_ffff_ffff) as u64;
289
290         let r2a = ((m2a >> 64) & 0xffff_ffff_ffff_ffff) as u64;
291         let r2b = ((m2b >> 64) & 0xffff_ffff_ffff_ffff) as u64;
292         let r2c = ((m2c >> 64) & 0xffff_ffff_ffff_ffff) as u64;
293         let r2d = ((m1a >> 0 ) & 0xffff_ffff_ffff_ffff) as u64;
294         let r2e = ((m1b >> 0 ) & 0xffff_ffff_ffff_ffff) as u64;
295
296         let r1a = ((m1a >> 64) & 0xffff_ffff_ffff_ffff) as u64;
297         let r1b = ((m1b >> 64) & 0xffff_ffff_ffff_ffff) as u64;
298         let r1c = ((m0  >> 0 ) & 0xffff_ffff_ffff_ffff) as u64;
299
300         let r0a = ((m0  >> 64) & 0xffff_ffff_ffff_ffff) as u64;
301
302         let (r4, r3_ca) = r4a.overflowing_add(r4b);
303         let (r4, r3_cb) = r4.overflowing_add(r4c);
304         let r3_c = r3_ca as u64 + r3_cb as u64;
305
306         let (r3, r2_ca) = r3a.overflowing_add(r3b);
307         let (r3, r2_cb) = r3.overflowing_add(r3c);
308         let (r3, r2_cc) = r3.overflowing_add(r3d);
309         let (r3, r2_cd) = r3.overflowing_add(r3e);
310         let (r3, r2_ce) = r3.overflowing_add(r3_c);
311         let r2_c = r2_ca as u64 + r2_cb as u64 + r2_cc as u64 + r2_cd as u64 + r2_ce as u64;
312
313         let (r2, r1_ca) = r2a.overflowing_add(r2b);
314         let (r2, r1_cb) = r2.overflowing_add(r2c);
315         let (r2, r1_cc) = r2.overflowing_add(r2d);
316         let (r2, r1_cd) = r2.overflowing_add(r2e);
317         let (r2, r1_ce) = r2.overflowing_add(r2_c);
318         let r1_c = r1_ca as u64 + r1_cb as u64 + r1_cc as u64 + r1_cd as u64 + r1_ce as u64;
319
320         let (r1, r0_ca) = r1a.overflowing_add(r1b);
321         let (r1, r0_cb) = r1.overflowing_add(r1c);
322         let (r1, r0_cc) = r1.overflowing_add(r1_c);
323         let r0_c = r0_ca as u64 + r0_cb as u64 + r0_cc as u64;
324
325         let (r0, must_not_overflow) = r0a.overflowing_add(r0_c);
326         debug_assert!(!must_not_overflow, "Two 3*64 bit numbers, multiplied, will not use more than 6*64 bits");
327
328         [r0, r1, r2, r3, r4, r5]
329 }
330
331 macro_rules! define_mul { ($name: ident, $len: expr, $submul: ident, $add: ident, $subadd: ident, $sub: ident, $subsub: ident) => {
332         /// Multiplies two $len-64-bit integers together, returning a new $len*2-64-bit integer.
333         const fn $name(a: &[u64], b: &[u64]) -> [u64; $len * 2] {
334                 // We could probably get a bit faster doing gradeschool multiplication for some smaller
335                 // sizes, but its easier to just have one variable-length multiplication, so we do
336                 // Karatsuba always here.
337                 debug_assert!(a.len() == $len);
338                 debug_assert!(b.len() == $len);
339
340                 let a0 = const_subslice(a, 0, $len / 2);
341                 let a1 = const_subslice(a, $len / 2, $len);
342                 let b0 = const_subslice(b, 0, $len / 2);
343                 let b1 = const_subslice(b, $len / 2, $len);
344
345                 let z2 = $submul(a0, b0);
346                 let z0 = $submul(a1, b1);
347
348                 let (z1a_max, z1a_min, z1a_sign) =
349                         if slice_greater_than(&a1, &a0) { (a1, a0, true) } else { (a0, a1, false) };
350                 let (z1b_max, z1b_min, z1b_sign) =
351                         if slice_greater_than(&b1, &b0) { (b1, b0, true) } else { (b0, b1, false) };
352
353                 let z1a = $subsub(z1a_max, z1a_min);
354                 debug_assert!(!z1a.1, "z1a_max was selected to be greater than z1a_min");
355                 let z1b = $subsub(z1b_max, z1b_min);
356                 debug_assert!(!z1b.1, "z1b_max was selected to be greater than z1b_min");
357                 let z1m_sign = z1a_sign == z1b_sign;
358
359                 let z1m = $submul(&z1a.0, &z1b.0);
360                 let z1n = $add(&z0, &z2);
361                 let mut z1_carry = z1n.1;
362                 let z1 = if z1m_sign {
363                         let r = $sub(&z1n.0, &z1m);
364                         if r.1 { z1_carry ^= true; }
365                         r.0
366                 } else {
367                         let r = $add(&z1n.0, &z1m);
368                         if r.1 { z1_carry = true; }
369                         r.0
370                 };
371
372                 let l = const_subslice(&z0, $len / 2, $len);
373                 let (k, j_carry) = $subadd(const_subslice(&z0, 0, $len / 2), const_subslice(&z1, $len / 2, $len));
374                 let (mut j, i_carry_a) = $subadd(const_subslice(&z1, 0, $len / 2), const_subslice(&z2, $len / 2, $len));
375                 let mut i_carry_b = false;
376                 if j_carry {
377                         i_carry_b = add_u64!(j, 1);
378                 }
379                 let mut i = [0; $len / 2];
380                 let i_source = const_subslice(&z2, 0, $len / 2);
381                 copy_from_slice!(i, 0, $len / 2, i_source);
382                 let i_carry = i_carry_a as u64 + i_carry_b as u64 + z1_carry as u64;
383                 if i_carry != 0 {
384                         let must_not_overflow = add_u64!(i, i_carry);
385                         debug_assert!(!must_not_overflow, "Two N*64 bit numbers, multiplied, will not use more than 2*N*64 bits");
386                 }
387
388                 let mut res = [0; $len * 2];
389                 copy_from_slice!(res, $len * 2 * 0 / 4, $len * 2 * 1 / 4, i);
390                 copy_from_slice!(res, $len * 2 * 1 / 4, $len * 2 * 2 / 4, j);
391                 copy_from_slice!(res, $len * 2 * 2 / 4, $len * 2 * 3 / 4, k);
392                 copy_from_slice!(res, $len * 2 * 3 / 4, $len * 2 * 4 / 4, l);
393                 res
394         }
395 } }
396
397 define_mul!(mul_4, 4, mul_2, add_4, add_2, sub_4, sub_2);
398 define_mul!(mul_6, 6, mul_3, add_6, add_3, sub_6, sub_3);
399 define_mul!(mul_8, 8, mul_4, add_8, add_4, sub_8, sub_4);
400 define_mul!(mul_16, 16, mul_8, add_16, add_8, sub_16, sub_8);
401 define_mul!(mul_32, 32, mul_16, add_32, add_16, sub_32, sub_16);
402 define_mul!(mul_64, 64, mul_32, add_64, add_32, sub_64, sub_32);
403
404
405 /// Squares a 128-bit integer, returning a new 256-bit integer.
406 ///
407 /// This is the base case for our squaring, taking advantage of Rust's native 128-bit int
408 /// types to do multiplication (potentially) natively.
409 const fn sqr_2(a: &[u64]) -> [u64; 4] {
410         debug_assert!(a.len() == 2);
411
412         let (a0, a1) = (a[0] as u128, a[1] as u128);
413         let z2 = a0 * a0;
414         let mut z1 = a0 * a1;
415         let i_carry_a = z1 & (1u128 << 127) != 0;
416         z1 <<= 1;
417         let z0 = a1 * a1;
418
419         add_mul_2_parts(z2, z1, z0, i_carry_a)
420 }
421
422 macro_rules! define_sqr { ($name: ident, $len: expr, $submul: ident, $subsqr: ident, $subadd: ident) => {
423         /// Squares a $len-64-bit integers, returning a new $len*2-64-bit integer.
424         const fn $name(a: &[u64]) -> [u64; $len * 2] {
425                 // Squaring is only 3 half-length multiplies/squares in gradeschool math, so use that.
426                 debug_assert!(a.len() == $len);
427
428                 let hi = const_subslice(a, 0, $len / 2);
429                 let lo = const_subslice(a, $len / 2, $len);
430
431                 let v0 = $subsqr(lo);
432                 let mut v1 = $submul(hi, lo);
433                 let i_carry_a  = double!(v1);
434                 let v2 = $subsqr(hi);
435
436                 let l = const_subslice(&v0, $len / 2, $len);
437                 let (k, j_carry) = $subadd(const_subslice(&v0, 0, $len / 2), const_subslice(&v1, $len / 2, $len));
438                 let (mut j, i_carry_b) = $subadd(const_subslice(&v1, 0, $len / 2), const_subslice(&v2, $len / 2, $len));
439
440                 let mut i = [0; $len / 2];
441                 let i_source = const_subslice(&v2, 0, $len / 2);
442                 copy_from_slice!(i, 0, $len / 2, i_source);
443
444                 let mut i_carry_c = false;
445                 if j_carry {
446                         i_carry_c = add_u64!(j, 1);
447                 }
448                 let i_carry = i_carry_a as u64 + i_carry_b as u64 + i_carry_c as u64;
449                 if i_carry != 0 {
450                         let must_not_overflow = add_u64!(i, i_carry);
451                         debug_assert!(!must_not_overflow, "Two N*64 bit numbers, multiplied, will not use more than 2*N*64 bits");
452                 }
453
454                 let mut res = [0; $len * 2];
455                 copy_from_slice!(res, $len * 2 * 0 / 4, $len * 2 * 1 / 4, i);
456                 copy_from_slice!(res, $len * 2 * 1 / 4, $len * 2 * 2 / 4, j);
457                 copy_from_slice!(res, $len * 2 * 2 / 4, $len * 2 * 3 / 4, k);
458                 copy_from_slice!(res, $len * 2 * 3 / 4, $len * 2 * 4 / 4, l);
459                 res
460         }
461 } }
462
463 // TODO: Write an optimized sqr_3 (though secp384r1 is barely used)
464 const fn sqr_3(a: &[u64]) -> [u64; 6] { mul_3(a, a) }
465
466 define_sqr!(sqr_4, 4, mul_2, sqr_2, add_2);
467 define_sqr!(sqr_6, 6, mul_3, sqr_3, add_3);
468 define_sqr!(sqr_8, 8, mul_4, sqr_4, add_4);
469 define_sqr!(sqr_16, 16, mul_8, sqr_8, add_8);
470 define_sqr!(sqr_32, 32, mul_16, sqr_16, add_16);
471 define_sqr!(sqr_64, 64, mul_32, sqr_32, add_32);
472
473 macro_rules! dummy_pre_push { ($name: ident, $len: expr) => {} }
474 macro_rules! vec_pre_push { ($name: ident, $len: expr) => { $name.push([0; $len]); } }
475
476 macro_rules! define_div_rem { ($name: ident, $len: expr, $sub: ident, $heap_init: expr, $pre_push: ident $(, $const_opt: tt)?) => {
477         /// Divides two $len-64-bit integers, `a` by `b`, returning the quotient and remainder
478         ///
479         /// Fails iff `b` is zero.
480         $($const_opt)? fn $name(a: &[u64; $len], b: &[u64; $len]) -> Result<([u64; $len], [u64; $len]), ()> {
481                 if slice_equal(b, &[0; $len]) { return Err(()); }
482
483                 // Very naively divide `a` by `b` by calculating all the powers of two times `b` up to `a`,
484                 // then subtracting the powers of two in decreasing order. What's left is the remainder.
485                 //
486                 // This requires storing all the multiples of `b` in `pow2s`, which may be a vec or an
487                 // array. `$pre_push!()` sets up the next element with zeros and then we can overwrite it.
488                 let mut b_pow = *b;
489                 let mut pow2s = $heap_init;
490                 let mut pow2s_count = 0;
491                 while slice_greater_than(a, &b_pow) {
492                         $pre_push!(pow2s, $len);
493                         pow2s[pow2s_count] = b_pow;
494                         pow2s_count += 1;
495                         let double_overflow = double!(b_pow);
496                         if double_overflow { break; }
497                 }
498                 let mut quot = [0; $len];
499                 let mut rem = *a;
500                 let mut pow2 = pow2s_count as isize - 1;
501                 while pow2 >= 0 {
502                         let b_pow = pow2s[pow2 as usize];
503                         let overflow = double!(quot);
504                         debug_assert!(!overflow, "quotient should be expressible in $len*64 bits");
505                         if slice_greater_than(&rem, &b_pow) {
506                                 let (r, underflow) = $sub(&rem, &b_pow);
507                                 debug_assert!(!underflow, "rem was just checked to be > b_pow, so sub cannot underflow");
508                                 rem = r;
509                                 quot[$len - 1] |= 1;
510                         }
511                         pow2 -= 1;
512                 }
513                 if slice_equal(&rem, b) {
514                         let overflow = add_u64!(quot, 1);
515                         debug_assert!(!overflow, "quotient should be expressible in $len*64 bits");
516                         Ok((quot, [0; $len]))
517                 } else {
518                         Ok((quot, rem))
519                 }
520         }
521 } }
522
523 #[cfg(fuzzing)]
524 define_div_rem!(div_rem_2, 2, sub_2, [[0; 2]; 2 * 64], dummy_pre_push, const);
525 define_div_rem!(div_rem_4, 4, sub_4, [[0; 4]; 4 * 64], dummy_pre_push, const); // Uses 8 KiB of stack
526 define_div_rem!(div_rem_6, 6, sub_6, [[0; 6]; 6 * 64], dummy_pre_push, const); // Uses 18 KiB of stack!
527 #[cfg(debug_assertions)]
528 define_div_rem!(div_rem_8, 8, sub_8, [[0; 8]; 8 * 64], dummy_pre_push, const); // Uses 32 KiB of stack!
529 #[cfg(debug_assertions)]
530 define_div_rem!(div_rem_12, 12, sub_12, [[0; 12]; 12 * 64], dummy_pre_push, const); // Uses 72 KiB of stack!
531 define_div_rem!(div_rem_64, 64, sub_64, Vec::new(), vec_pre_push); // Uses up to 2 MiB of heap
532 #[cfg(debug_assertions)]
533 define_div_rem!(div_rem_128, 128, sub_128, Vec::new(), vec_pre_push); // Uses up to 8 MiB of heap
534
535 macro_rules! define_mod_inv { ($name: ident, $len: expr, $div: ident, $add: ident, $sub_abs: ident, $mul: ident) => {
536         /// Calculates the modular inverse of a $len-64-bit number with respect to the given modulus,
537         /// if one exists.
538         const fn $name(a: &[u64; $len], m: &[u64; $len]) -> Result<[u64; $len], ()> {
539                 if slice_equal(a, &[0; $len]) || slice_equal(m, &[0; $len]) { return Err(()); }
540
541                 let (mut s, mut old_s) = ([0; $len], [0; $len]);
542                 old_s[$len - 1] = 1;
543                 let mut r = *m;
544                 let mut old_r = *a;
545
546                 let (mut old_s_neg, mut s_neg) = (false, false);
547
548                 while !slice_equal(&r, &[0; $len]) {
549                         let (quot, new_r) = debug_unwrap!($div(&old_r, &r));
550
551                         let new_sa = $mul(&quot, &s);
552                         debug_assert!(slice_equal(const_subslice(&new_sa, 0, $len), &[0; $len]), "S overflowed");
553                         let (new_s, new_s_neg) = match (old_s_neg, s_neg) {
554                                 (true, true) => {
555                                         let (new_s, overflow) = $add(&old_s, const_subslice(&new_sa, $len, new_sa.len()));
556                                         debug_assert!(!overflow);
557                                         (new_s, true)
558                                 }
559                                 (false, true) => {
560                                         let (new_s, overflow) = $add(&old_s, const_subslice(&new_sa, $len, new_sa.len()));
561                                         debug_assert!(!overflow);
562                                         (new_s, false)
563                                 },
564                                 (true, false) => {
565                                         let (new_s, overflow) = $add(&old_s, const_subslice(&new_sa, $len, new_sa.len()));
566                                         debug_assert!(!overflow);
567                                         (new_s, true)
568                                 },
569                                 (false, false) => $sub_abs(&old_s, const_subslice(&new_sa, $len, new_sa.len())),
570                         };
571
572                         old_r = r;
573                         r = new_r;
574
575                         old_s = s;
576                         old_s_neg = s_neg;
577                         s = new_s;
578                         s_neg = new_s_neg;
579                 }
580
581                 // At this point old_r contains our GCD and old_s our first Bézout's identity coefficient.
582                 if !slice_equal(const_subslice(&old_r, 0, $len - 1), &[0; $len - 1]) || old_r[$len - 1] != 1 {
583                         Err(())
584                 } else {
585                         debug_assert!(slice_greater_than(m, &old_s));
586                         if old_s_neg {
587                                 let (modinv, underflow) = $sub_abs(m, &old_s);
588                                 debug_assert!(!underflow);
589                                 debug_assert!(slice_greater_than(m, &modinv));
590                                 Ok(modinv)
591                         } else {
592                                 Ok(old_s)
593                         }
594                 }
595         }
596 } }
597 #[cfg(fuzzing)]
598 define_mod_inv!(mod_inv_2, 2, div_rem_2, add_2, sub_abs_2, mul_2);
599 define_mod_inv!(mod_inv_4, 4, div_rem_4, add_4, sub_abs_4, mul_4);
600 define_mod_inv!(mod_inv_6, 6, div_rem_6, add_6, sub_abs_6, mul_6);
601 #[cfg(fuzzing)]
602 define_mod_inv!(mod_inv_8, 8, div_rem_8, add_8, sub_abs_8, mul_8);
603
604 // ******************
605 // * The public API *
606 // ******************
607
608 const WORD_COUNT_4096: usize = 4096 / 64;
609 const WORD_COUNT_256: usize = 256 / 64;
610 const WORD_COUNT_384: usize = 384 / 64;
611
612 // RFC 5702 indicates RSA keys can be up to 4096 bits, so we always use 4096-bit integers
613 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
614 pub(super) struct U4096([u64; WORD_COUNT_4096]);
615
616 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
617 pub(super) struct U256([u64; WORD_COUNT_256]);
618
619 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
620 pub(super) struct U384([u64; WORD_COUNT_384]);
621
622 pub(super) trait Int: Clone + Ord + Sized {
623         const ZERO: Self;
624         const BYTES: usize;
625         fn from_be_bytes(b: &[u8]) -> Result<Self, ()>;
626         fn limbs(&self) -> &[u64];
627 }
628 impl Int for U256 {
629         const ZERO: U256 = U256([0; 4]);
630         const BYTES: usize = 32;
631         fn from_be_bytes(b: &[u8]) -> Result<Self, ()> { Self::from_be_bytes(b) }
632         fn limbs(&self) -> &[u64] { &self.0 }
633 }
634 impl Int for U384 {
635         const ZERO: U384 = U384([0; 6]);
636         const BYTES: usize = 48;
637         fn from_be_bytes(b: &[u8]) -> Result<Self, ()> { Self::from_be_bytes(b) }
638         fn limbs(&self) -> &[u64] { &self.0 }
639 }
640
641 /// Defines a *PRIME* Modulus
642 pub(super) trait PrimeModulus<I: Int> {
643         const PRIME: I;
644         const R_SQUARED_MOD_PRIME: I;
645         const NEGATIVE_PRIME_INV_MOD_R: I;
646 }
647
648 #[derive(Clone, Debug, PartialEq, Eq)] // Ord doesn't make sense cause we have an R factor
649 pub(super) struct U256Mod<M: PrimeModulus<U256>>(U256, PhantomData<M>);
650
651 #[derive(Clone, Debug, PartialEq, Eq)] // Ord doesn't make sense cause we have an R factor
652 pub(super) struct U384Mod<M: PrimeModulus<U384>>(U384, PhantomData<M>);
653
654 impl U4096 {
655         /// Constructs a new [`U4096`] from a variable number of big-endian bytes.
656         pub(super) fn from_be_bytes(bytes: &[u8]) -> Result<U4096, ()> {
657                 if bytes.len() > 4096/8 { return Err(()); }
658                 let u64s = (bytes.len() + 7) / 8;
659                 let mut res = [0; WORD_COUNT_4096];
660                 for i in 0..u64s {
661                         let mut b = [0; 8];
662                         let pos = (u64s - i) * 8;
663                         let start = bytes.len().saturating_sub(pos);
664                         let end = bytes.len() + 8 - pos;
665                         b[8 + start - end..].copy_from_slice(&bytes[start..end]);
666                         res[i + WORD_COUNT_4096 - u64s] = u64::from_be_bytes(b);
667                 }
668                 Ok(U4096(res))
669         }
670
671         /// Naively multiplies `self` * `b` mod `m`, returning a new [`U4096`].
672         ///
673         /// Fails iff m is 0 or self or b are greater than m.
674         #[cfg(debug_assertions)]
675         fn mulmod_naive(&self, b: &U4096, m: &U4096) -> Result<U4096, ()> {
676                 if m.0 == [0; WORD_COUNT_4096] { return Err(()); }
677                 if self > m || b > m { return Err(()); }
678
679                 let mul = mul_64(&self.0, &b.0);
680
681                 let mut m_zeros = [0; 128];
682                 m_zeros[WORD_COUNT_4096..].copy_from_slice(&m.0);
683                 let (_, rem) = div_rem_128(&mul, &m_zeros)?;
684                 let mut res = [0; WORD_COUNT_4096];
685                 debug_assert_eq!(&rem[..WORD_COUNT_4096], &[0; WORD_COUNT_4096]);
686                 res.copy_from_slice(&rem[WORD_COUNT_4096..]);
687                 Ok(U4096(res))
688         }
689
690         /// Calculates `self` ^ `exp` mod `m`, returning a new [`U4096`].
691         ///
692         /// Fails iff m is 0, even, or self or b are greater than m.
693         pub(super) fn expmod_odd_mod(&self, mut exp: u32, m: &U4096) -> Result<U4096, ()> {
694                 #![allow(non_camel_case_types)]
695
696                 if m.0 == [0; WORD_COUNT_4096] { return Err(()); }
697                 if m.0[WORD_COUNT_4096 - 1] & 1 == 0 { return Err(()); }
698                 if self > m { return Err(()); }
699
700                 let mut t = [0; WORD_COUNT_4096];
701                 if &m.0[..WORD_COUNT_4096 - 1] == &[0; WORD_COUNT_4096 - 1] && m.0[WORD_COUNT_4096 - 1] == 1 {
702                         return Ok(U4096(t));
703                 }
704                 t[WORD_COUNT_4096 - 1] = 1;
705                 if exp == 0 { return Ok(U4096(t)); }
706
707                 // Because m is not even, using 2^4096 as the Montgomery R value is always safe - it is
708                 // guaranteed to be co-prime with any non-even integer.
709
710                 // We use a single 4096-bit integer type for all our RSA operations, though in most cases
711                 // we're actually dealing with 1024-bit or 2048-bit ints. Thus, we define sub-array math
712                 // here which debug_assert's the required bits are 0s and then uses faster math primitives.
713
714                 type mul_ty = fn(&[u64], &[u64]) -> [u64; WORD_COUNT_4096 * 2];
715                 type sqr_ty = fn(&[u64]) -> [u64; WORD_COUNT_4096 * 2];
716                 type add_double_ty = fn(&[u64], &[u64]) -> ([u64; WORD_COUNT_4096 * 2], bool);
717                 type sub_ty = fn(&[u64], &[u64]) -> ([u64; WORD_COUNT_4096], bool);
718                 let (word_count, log_bits, mul, sqr, add_double, sub) =
719                         if m.0[..WORD_COUNT_4096 / 2] == [0; WORD_COUNT_4096 / 2] {
720                                 if m.0[..WORD_COUNT_4096 * 3 / 4] == [0; WORD_COUNT_4096 * 3 / 4] {
721                                         fn mul_16_subarr(a: &[u64], b: &[u64]) -> [u64; WORD_COUNT_4096 * 2] {
722                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096);
723                                                 debug_assert_eq!(b.len(), WORD_COUNT_4096);
724                                                 debug_assert_eq!(&a[..WORD_COUNT_4096 * 3 / 4], &[0; WORD_COUNT_4096 * 3 / 4]);
725                                                 debug_assert_eq!(&b[..WORD_COUNT_4096 * 3 / 4], &[0; WORD_COUNT_4096 * 3 / 4]);
726                                                 let mut res = [0; WORD_COUNT_4096 * 2];
727                                                 res[WORD_COUNT_4096 + WORD_COUNT_4096 / 2..].copy_from_slice(
728                                                         &mul_16(&a[WORD_COUNT_4096 * 3 / 4..], &b[WORD_COUNT_4096 * 3 / 4..]));
729                                                 res
730                                         }
731                                         fn sqr_16_subarr(a: &[u64]) -> [u64; WORD_COUNT_4096 * 2] {
732                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096);
733                                                 debug_assert_eq!(&a[..WORD_COUNT_4096 * 3 / 4], &[0; WORD_COUNT_4096 * 3 / 4]);
734                                                 let mut res = [0; WORD_COUNT_4096 * 2];
735                                                 res[WORD_COUNT_4096 + WORD_COUNT_4096 / 2..].copy_from_slice(
736                                                         &sqr_16(&a[WORD_COUNT_4096 * 3 / 4..]));
737                                                 res
738                                         }
739                                         fn add_32_subarr(a: &[u64], b: &[u64]) -> ([u64; WORD_COUNT_4096 * 2], bool) {
740                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096 * 2);
741                                                 debug_assert_eq!(b.len(), WORD_COUNT_4096 * 2);
742                                                 debug_assert_eq!(&a[..WORD_COUNT_4096 * 3 / 2], &[0; WORD_COUNT_4096 * 3 / 2]);
743                                                 debug_assert_eq!(&b[..WORD_COUNT_4096 * 3 / 2], &[0; WORD_COUNT_4096 * 3 / 2]);
744                                                 let (add, overflow) = add_32(&a[WORD_COUNT_4096 * 3 / 2..], &b[WORD_COUNT_4096 * 3 / 2..]);
745                                                 let mut res = [0; WORD_COUNT_4096 * 2];
746                                                 res[WORD_COUNT_4096 * 3 / 2..].copy_from_slice(&add);
747                                                 (res, overflow)
748                                         }
749                                         fn sub_16_subarr(a: &[u64], b: &[u64]) -> ([u64; WORD_COUNT_4096], bool) {
750                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096);
751                                                 debug_assert_eq!(b.len(), WORD_COUNT_4096);
752                                                 debug_assert_eq!(&a[..WORD_COUNT_4096 * 3 / 4], &[0; WORD_COUNT_4096 * 3 / 4]);
753                                                 debug_assert_eq!(&b[..WORD_COUNT_4096 * 3 / 4], &[0; WORD_COUNT_4096 * 3 / 4]);
754                                                 let (sub, underflow) = sub_16(&a[WORD_COUNT_4096 * 3 / 4..], &b[WORD_COUNT_4096 * 3 / 4..]);
755                                                 let mut res = [0; WORD_COUNT_4096];
756                                                 res[WORD_COUNT_4096 * 3 / 4..].copy_from_slice(&sub);
757                                                 (res, underflow)
758                                         }
759                                         (16, 10, mul_16_subarr as mul_ty, sqr_16_subarr as sqr_ty, add_32_subarr as add_double_ty, sub_16_subarr as sub_ty)
760                                 } else {
761                                         fn mul_32_subarr(a: &[u64], b: &[u64]) -> [u64; WORD_COUNT_4096 * 2] {
762                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096);
763                                                 debug_assert_eq!(b.len(), WORD_COUNT_4096);
764                                                 debug_assert_eq!(&a[..WORD_COUNT_4096 / 2], &[0; WORD_COUNT_4096 / 2]);
765                                                 debug_assert_eq!(&b[..WORD_COUNT_4096 / 2], &[0; WORD_COUNT_4096 / 2]);
766                                                 let mut res = [0; WORD_COUNT_4096 * 2];
767                                                 res[WORD_COUNT_4096..].copy_from_slice(
768                                                         &mul_32(&a[WORD_COUNT_4096 / 2..], &b[WORD_COUNT_4096 / 2..]));
769                                                 res
770                                         }
771                                         fn sqr_32_subarr(a: &[u64]) -> [u64; WORD_COUNT_4096 * 2] {
772                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096);
773                                                 debug_assert_eq!(&a[..WORD_COUNT_4096 / 2], &[0; WORD_COUNT_4096 / 2]);
774                                                 let mut res = [0; WORD_COUNT_4096 * 2];
775                                                 res[WORD_COUNT_4096..].copy_from_slice(
776                                                         &sqr_32(&a[WORD_COUNT_4096 / 2..]));
777                                                 res
778                                         }
779                                         fn add_64_subarr(a: &[u64], b: &[u64]) -> ([u64; WORD_COUNT_4096 * 2], bool) {
780                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096 * 2);
781                                                 debug_assert_eq!(b.len(), WORD_COUNT_4096 * 2);
782                                                 debug_assert_eq!(&a[..WORD_COUNT_4096], &[0; WORD_COUNT_4096]);
783                                                 debug_assert_eq!(&b[..WORD_COUNT_4096], &[0; WORD_COUNT_4096]);
784                                                 let (add, overflow) = add_64(&a[WORD_COUNT_4096..], &b[WORD_COUNT_4096..]);
785                                                 let mut res = [0; WORD_COUNT_4096 * 2];
786                                                 res[WORD_COUNT_4096..].copy_from_slice(&add);
787                                                 (res, overflow)
788                                         }
789                                         fn sub_32_subarr(a: &[u64], b: &[u64]) -> ([u64; WORD_COUNT_4096], bool) {
790                                                 debug_assert_eq!(a.len(), WORD_COUNT_4096);
791                                                 debug_assert_eq!(b.len(), WORD_COUNT_4096);
792                                                 debug_assert_eq!(&a[..WORD_COUNT_4096 / 2], &[0; WORD_COUNT_4096 / 2]);
793                                                 debug_assert_eq!(&b[..WORD_COUNT_4096 / 2], &[0; WORD_COUNT_4096 / 2]);
794                                                 let (sub, underflow) = sub_32(&a[WORD_COUNT_4096 / 2..], &b[WORD_COUNT_4096 / 2..]);
795                                                 let mut res = [0; WORD_COUNT_4096];
796                                                 res[WORD_COUNT_4096 / 2..].copy_from_slice(&sub);
797                                                 (res, underflow)
798                                         }
799                                         (32, 11, mul_32_subarr as mul_ty, sqr_32_subarr as sqr_ty, add_64_subarr as add_double_ty, sub_32_subarr as sub_ty)
800                                 }
801                         } else {
802                                 (64, 12, mul_64 as mul_ty, sqr_64 as sqr_ty, add_128 as add_double_ty, sub_64 as sub_ty)
803                         };
804
805                 // r is always the even value with one bit set above the word count we're using.
806                 let mut r = [0; WORD_COUNT_4096 * 2];
807                 r[WORD_COUNT_4096 * 2 - word_count - 1] = 1;
808
809                 let mut m_inv_pos = [0; WORD_COUNT_4096];
810                 m_inv_pos[WORD_COUNT_4096 - 1] = 1;
811                 let mut two = [0; WORD_COUNT_4096];
812                 two[WORD_COUNT_4096 - 1] = 2;
813                 for _ in 0..log_bits {
814                         let mut m_m_inv = mul(&m_inv_pos, &m.0);
815                         m_m_inv[..WORD_COUNT_4096 * 2 - word_count].fill(0);
816                         let m_inv = mul(&sub(&two, &m_m_inv[WORD_COUNT_4096..]).0, &m_inv_pos);
817                         m_inv_pos[WORD_COUNT_4096 - word_count..].copy_from_slice(&m_inv[WORD_COUNT_4096 * 2 - word_count..]);
818                 }
819                 m_inv_pos[..WORD_COUNT_4096 - word_count].fill(0);
820
821                 // `m_inv` is the negative modular inverse of m mod R, so subtract m_inv from R.
822                 let mut m_inv = m_inv_pos;
823                 negate!(m_inv);
824                 m_inv[..WORD_COUNT_4096 - word_count].fill(0);
825                 debug_assert_eq!(&mul(&m_inv, &m.0)[WORD_COUNT_4096 * 2 - word_count..],
826                         // R - 1 == -1 % R
827                         &[0xffff_ffff_ffff_ffff; WORD_COUNT_4096][WORD_COUNT_4096 - word_count..]);
828
829                 let mont_reduction = |mu: [u64; WORD_COUNT_4096 * 2]| -> [u64; WORD_COUNT_4096] {
830                         debug_assert_eq!(&mu[..WORD_COUNT_4096 * 2 - word_count * 2],
831                                 &[0; WORD_COUNT_4096 * 2][..WORD_COUNT_4096 * 2 - word_count * 2]);
832                         // Do a montgomery reduction of `mu`
833
834                         // mu % R is just the bottom word_count bytes of mu
835                         let mut mu_mod_r = [0; WORD_COUNT_4096];
836                         mu_mod_r[WORD_COUNT_4096 - word_count..].copy_from_slice(&mu[WORD_COUNT_4096 * 2 - word_count..]);
837
838                         // v = ((mu % R) * negative_modulus_inverse) % R
839                         let mut v = mul(&mu_mod_r, &m_inv);
840                         v[..WORD_COUNT_4096 * 2 - word_count].fill(0); // mod R
841
842                         // t_on_r = (mu + v*modulus) / R
843                         let t0 = mul(&v[WORD_COUNT_4096..], &m.0);
844                         let (t1, t1_extra_bit) = add_double(&t0, &mu);
845
846                         // Note that dividing t1 by R is simply a matter of shifting right by word_count bytes
847                         // We only need to maintain word_count bytes (plus `t1_extra_bit` which is implicitly
848                         // an extra bit) because t_on_r is guarantee to be, at max, 2*m - 1.
849                         let mut t1_on_r = [0; WORD_COUNT_4096];
850                         debug_assert_eq!(&t1[WORD_COUNT_4096 * 2 - word_count..], &[0; WORD_COUNT_4096][WORD_COUNT_4096 - word_count..],
851                                 "t1 should be divisible by r");
852                         t1_on_r[WORD_COUNT_4096 - word_count..].copy_from_slice(&t1[WORD_COUNT_4096 * 2 - word_count * 2..WORD_COUNT_4096 * 2 - word_count]);
853
854                         // The modulus has only word_count bytes, so if t1_extra_bit is set we are definitely
855                         // larger than the modulus.
856                         if t1_extra_bit || t1_on_r >= m.0 {
857                                 let underflow;
858                                 (t1_on_r, underflow) = sub(&t1_on_r, &m.0);
859                                 debug_assert_eq!(t1_extra_bit, underflow,
860                                         "The number (t1_extra_bit, t1_on_r) is at most 2m-1, so underflowing t1_on_r - m should happen iff t1_extra_bit is set.");
861                         }
862                         t1_on_r
863                 };
864
865                 // Calculate R^2 mod m as ((2^DOUBLES * R) mod m)^(log_bits - LOG2_DOUBLES) mod R
866                 let mut r_minus_one = [0xffff_ffff_ffff_ffffu64; WORD_COUNT_4096];
867                 r_minus_one[..WORD_COUNT_4096 - word_count].fill(0);
868                 // While we do a full div here, in general R should be less than 2x m (assuming the RSA
869                 // modulus used its full bit range and is 1024, 2048, or 4096 bits), so it should be cheap.
870                 // In cases with a nonstandard RSA modulus we may end up being pretty slow here, but we'll
871                 // survive.
872                 // If we ever find a problem with this we should reduce R to be tigher on m, as we're
873                 // wasting extra bits of calculation if R is too far from m.
874                 let (_, mut r_mod_m) = debug_unwrap!(div_rem_64(&r_minus_one, &m.0));
875                 let r_mod_m_overflow = add_u64!(r_mod_m, 1);
876                 if r_mod_m_overflow || r_mod_m >= m.0 {
877                         (r_mod_m, _) = sub_64(&r_mod_m, &m.0);
878                 }
879
880                 let mut r2_mod_m: [u64; 64] = r_mod_m;
881                 const DOUBLES: usize = 32;
882                 const LOG2_DOUBLES: usize = 5;
883
884                 for _ in 0..DOUBLES {
885                         let overflow = double!(r2_mod_m);
886                         if overflow || r2_mod_m > m.0 {
887                                 (r2_mod_m, _) = sub_64(&r2_mod_m, &m.0);
888                         }
889                 }
890                 for _ in 0..log_bits - LOG2_DOUBLES {
891                         r2_mod_m = mont_reduction(sqr(&r2_mod_m));
892                 }
893                 // Clear excess high bits
894                 for (m_limb, r2_limb) in m.0.iter().zip(r2_mod_m.iter_mut()) {
895                         let clear_bits = m_limb.leading_zeros();
896                         if clear_bits == 0 { break; }
897                         *r2_limb &= !(0xffff_ffff_ffff_ffffu64 << (64 - clear_bits));
898                         if *m_limb != 0 { break; }
899                 }
900                 debug_assert!(r2_mod_m < m.0);
901
902                 // Finally, actually do the exponentiation...
903
904                 // Calculate t * R and a * R as mont multiplications by R^2 mod m
905                 let mut tr = mont_reduction(mul(&r2_mod_m, &t));
906                 let mut ar = mont_reduction(mul(&r2_mod_m, &self.0));
907
908                 #[cfg(debug_assertions)] {
909                         debug_assert_eq!(r2_mod_m, U4096(r_mod_m).mulmod_naive(&U4096(r_mod_m), &m).unwrap().0);
910                         debug_assert_eq!(&tr, &U4096(t).mulmod_naive(&U4096(r_mod_m), &m).unwrap().0);
911                         debug_assert_eq!(&ar, &self.mulmod_naive(&U4096(r_mod_m), &m).unwrap().0);
912                 }
913
914                 while exp != 1 {
915                         if exp % 2 == 1 {
916                                 tr = mont_reduction(mul(&tr, &ar));
917                                 exp -= 1;
918                         }
919                         ar = mont_reduction(sqr(&ar));
920                         exp /= 2;
921                 }
922                 ar = mont_reduction(mul(&ar, &tr));
923                 let mut resr = [0; WORD_COUNT_4096 * 2];
924                 resr[WORD_COUNT_4096..].copy_from_slice(&ar);
925                 Ok(U4096(mont_reduction(resr)))
926         }
927 }
928
929 // In a const context we can't subslice a slice, so instead we pick the eight bytes we want and
930 // pass them here to build u64s from arrays.
931 const fn eight_bytes_to_u64_be(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8, h: u8) -> u64 {
932         let b = [a, b, c, d, e, f, g, h];
933         u64::from_be_bytes(b)
934 }
935
936 impl U256 {
937         /// Constructs a new [`U256`] from a variable number of big-endian bytes.
938         pub(super) fn from_be_bytes(bytes: &[u8]) -> Result<U256, ()> {
939                 if bytes.len() > 256/8 { return Err(()); }
940                 let u64s = (bytes.len() + 7) / 8;
941                 let mut res = [0; WORD_COUNT_256];
942                 for i in 0..u64s {
943                         let mut b = [0; 8];
944                         let pos = (u64s - i) * 8;
945                         let start = bytes.len().saturating_sub(pos);
946                         let end = bytes.len() + 8 - pos;
947                         b[8 + start - end..].copy_from_slice(&bytes[start..end]);
948                         res[i + WORD_COUNT_256 - u64s] = u64::from_be_bytes(b);
949                 }
950                 Ok(U256(res))
951         }
952
953         /// Constructs a new [`U256`] from a fixed number of big-endian bytes.
954         pub(super) const fn from_32_be_bytes_panicking(bytes: &[u8; 32]) -> U256 {
955                 let res = [
956                         eight_bytes_to_u64_be(bytes[0*8 + 0], bytes[0*8 + 1], bytes[0*8 + 2], bytes[0*8 + 3],
957                                               bytes[0*8 + 4], bytes[0*8 + 5], bytes[0*8 + 6], bytes[0*8 + 7]),
958                         eight_bytes_to_u64_be(bytes[1*8 + 0], bytes[1*8 + 1], bytes[1*8 + 2], bytes[1*8 + 3],
959                                               bytes[1*8 + 4], bytes[1*8 + 5], bytes[1*8 + 6], bytes[1*8 + 7]),
960                         eight_bytes_to_u64_be(bytes[2*8 + 0], bytes[2*8 + 1], bytes[2*8 + 2], bytes[2*8 + 3],
961                                               bytes[2*8 + 4], bytes[2*8 + 5], bytes[2*8 + 6], bytes[2*8 + 7]),
962                         eight_bytes_to_u64_be(bytes[3*8 + 0], bytes[3*8 + 1], bytes[3*8 + 2], bytes[3*8 + 3],
963                                               bytes[3*8 + 4], bytes[3*8 + 5], bytes[3*8 + 6], bytes[3*8 + 7]),
964                 ];
965                 U256(res)
966         }
967
968         pub(super) const fn zero() -> U256 { U256([0, 0, 0, 0]) }
969         pub(super) const fn one() -> U256 { U256([0, 0, 0, 1]) }
970         pub(super) const fn three() -> U256 { U256([0, 0, 0, 3]) }
971 }
972
973 // Values modulus M::PRIME.0, stored in montgomery form.
974 impl<M: PrimeModulus<U256>> U256Mod<M> {
975         const fn mont_reduction(mu: [u64; 8]) -> Self {
976                 #[cfg(debug_assertions)] {
977                         // Check NEGATIVE_PRIME_INV_MOD_R is correct. Since this is all const, the compiler
978                         // should be able to do it at compile time alone.
979                         let minus_one_mod_r = mul_4(&M::PRIME.0, &M::NEGATIVE_PRIME_INV_MOD_R.0);
980                         assert!(slice_equal(const_subslice(&minus_one_mod_r, 4, 8), &[0xffff_ffff_ffff_ffff; 4]));
981                 }
982
983                 #[cfg(debug_assertions)] {
984                         // Check R_SQUARED_MOD_PRIME is correct. Since this is all const, the compiler
985                         // should be able to do it at compile time alone.
986                         let r_minus_one = [0xffff_ffff_ffff_ffff; 4];
987                         let (mut r_mod_prime, _) = sub_4(&r_minus_one, &M::PRIME.0);
988                         let r_mod_prime_overflow = add_u64!(r_mod_prime, 1);
989                         assert!(!r_mod_prime_overflow);
990                         let r_squared = sqr_4(&r_mod_prime);
991                         let mut prime_extended = [0; 8];
992                         let prime = M::PRIME.0;
993                         copy_from_slice!(prime_extended, 4, 8, prime);
994                         let (_, r_squared_mod_prime) = if let Ok(v) = div_rem_8(&r_squared, &prime_extended) { v } else { panic!() };
995                         assert!(slice_greater_than(&prime_extended, &r_squared_mod_prime));
996                         assert!(slice_equal(const_subslice(&r_squared_mod_prime, 4, 8), &M::R_SQUARED_MOD_PRIME.0));
997                 }
998
999                 // mu % R is just the bottom 4 bytes of mu
1000                 let mu_mod_r = const_subslice(&mu, 4, 8);
1001                 // v = ((mu % R) * negative_modulus_inverse) % R
1002                 let mut v = mul_4(&mu_mod_r, &M::NEGATIVE_PRIME_INV_MOD_R.0);
1003                 const ZEROS: &[u64; 4] = &[0; 4];
1004                 copy_from_slice!(v, 0, 4, ZEROS); // mod R
1005
1006                 // t_on_r = (mu + v*modulus) / R
1007                 let t0 = mul_4(const_subslice(&v, 4, 8), &M::PRIME.0);
1008                 let (t1, t1_extra_bit) = add_8(&t0, &mu);
1009
1010                 // Note that dividing t1 by R is simply a matter of shifting right by 4 bytes.
1011                 // We only need to maintain 4 bytes (plus `t1_extra_bit` which is implicitly an extra bit)
1012                 // because t_on_r is guarantee to be, at max, 2*m - 1.
1013                 let t1_on_r = const_subslice(&t1, 0, 4);
1014
1015                 let mut res = [0; 4];
1016                 // The modulus is only 4 bytes, so t1_extra_bit implies we're definitely larger than the
1017                 // modulus.
1018                 if t1_extra_bit || slice_greater_than(&t1_on_r, &M::PRIME.0) {
1019                         let underflow;
1020                         (res, underflow) = sub_4(&t1_on_r, &M::PRIME.0);
1021                         debug_assert!(t1_extra_bit == underflow,
1022                                 "The number (t1_extra_bit, t1_on_r) is at most 2m-1, so underflowing t1_on_r - m should happen iff t1_extra_bit is set.");
1023                 } else {
1024                         copy_from_slice!(res, 0, 4, t1_on_r);
1025                 }
1026                 Self(U256(res), PhantomData)
1027         }
1028
1029         pub(super) const fn from_u256_panicking(v: U256) -> Self {
1030                 assert!(v.0[0] <= M::PRIME.0[0]);
1031                 if v.0[0] == M::PRIME.0[0] {
1032                         assert!(v.0[1] <= M::PRIME.0[1]);
1033                         if v.0[1] == M::PRIME.0[1] {
1034                                 assert!(v.0[2] <= M::PRIME.0[2]);
1035                                 if v.0[2] == M::PRIME.0[2] {
1036                                         assert!(v.0[3] < M::PRIME.0[3]);
1037                                 }
1038                         }
1039                 }
1040                 assert!(M::PRIME.0[0] != 0 || M::PRIME.0[1] != 0 || M::PRIME.0[2] != 0 || M::PRIME.0[3] != 0);
1041                 Self::mont_reduction(mul_4(&M::R_SQUARED_MOD_PRIME.0, &v.0))
1042         }
1043
1044         pub(super) fn from_u256(mut v: U256) -> Self {
1045                 debug_assert!(M::PRIME.0 != [0; 4]);
1046                 debug_assert!(M::PRIME.0[0] > (1 << 63), "PRIME should have the top bit set");
1047                 while v >= M::PRIME {
1048                         let (new_v, spurious_underflow) = sub_4(&v.0, &M::PRIME.0);
1049                         debug_assert!(!spurious_underflow, "v was > M::PRIME.0");
1050                         v = U256(new_v);
1051                 }
1052                 Self::mont_reduction(mul_4(&M::R_SQUARED_MOD_PRIME.0, &v.0))
1053         }
1054
1055         pub(super) fn from_modinv_of(v: U256) -> Result<Self, ()> {
1056                 Ok(Self::from_u256(U256(mod_inv_4(&v.0, &M::PRIME.0)?)))
1057         }
1058
1059         /// Multiplies `self` * `b` mod `m`.
1060         ///
1061         /// Panics if `self`'s modulus is not equal to `b`'s
1062         pub(super) fn mul(&self, b: &Self) -> Self {
1063                 Self::mont_reduction(mul_4(&self.0.0, &b.0.0))
1064         }
1065
1066         /// Doubles `self` mod `m`.
1067         pub(super) fn double(&self) -> Self {
1068                 let mut res = self.0.0;
1069                 let overflow = double!(res);
1070                 if overflow || !slice_greater_than(&M::PRIME.0, &res) {
1071                         let underflow;
1072                         (res, underflow) = sub_4(&res, &M::PRIME.0);
1073                         debug_assert_eq!(overflow, underflow);
1074                 }
1075                 Self(U256(res), PhantomData)
1076         }
1077
1078         /// Multiplies `self` by 3 mod `m`.
1079         pub(super) fn times_three(&self) -> Self {
1080                 // TODO: Optimize this a lot
1081                 self.mul(&U256Mod::from_u256(U256::three()))
1082         }
1083
1084         /// Multiplies `self` by 4 mod `m`.
1085         pub(super) fn times_four(&self) -> Self {
1086                 // TODO: Optimize this somewhat?
1087                 self.double().double()
1088         }
1089
1090         /// Multiplies `self` by 8 mod `m`.
1091         pub(super) fn times_eight(&self) -> Self {
1092                 // TODO: Optimize this somewhat?
1093                 self.double().double().double()
1094         }
1095
1096         /// Multiplies `self` by 8 mod `m`.
1097         pub(super) fn square(&self) -> Self {
1098                 Self::mont_reduction(sqr_4(&self.0.0))
1099         }
1100
1101         /// Subtracts `b` from `self` % `m`.
1102         pub(super) fn sub(&self, b: &Self) -> Self {
1103                 let (mut val, underflow) = sub_4(&self.0.0, &b.0.0);
1104                 if underflow {
1105                         let overflow;
1106                         (val, overflow) = add_4(&val, &M::PRIME.0);
1107                         debug_assert_eq!(overflow, underflow);
1108                 }
1109                 Self(U256(val), PhantomData)
1110         }
1111
1112         /// Adds `b` to `self` % `m`.
1113         pub(super) fn add(&self, b: &Self) -> Self {
1114                 let (mut val, overflow) = add_4(&self.0.0, &b.0.0);
1115                 if overflow || !slice_greater_than(&M::PRIME.0, &val) {
1116                         let underflow;
1117                         (val, underflow) = sub_4(&val, &M::PRIME.0);
1118                         debug_assert_eq!(overflow, underflow);
1119                 }
1120                 Self(U256(val), PhantomData)
1121         }
1122
1123         /// Returns the underlying [`U256`].
1124         pub(super) fn into_u256(self) -> U256 {
1125                 let mut expanded_self = [0; 8];
1126                 expanded_self[4..].copy_from_slice(&self.0.0);
1127                 Self::mont_reduction(expanded_self).0
1128         }
1129 }
1130
1131 // Values modulus M::PRIME.0, stored in montgomery form.
1132 impl U384 {
1133         /// Constructs a new [`U384`] from a variable number of big-endian bytes.
1134         pub(super) fn from_be_bytes(bytes: &[u8]) -> Result<U384, ()> {
1135                 if bytes.len() > 384/8 { return Err(()); }
1136                 let u64s = (bytes.len() + 7) / 8;
1137                 let mut res = [0; WORD_COUNT_384];
1138                 for i in 0..u64s {
1139                         let mut b = [0; 8];
1140                         let pos = (u64s - i) * 8;
1141                         let start = bytes.len().saturating_sub(pos);
1142                         let end = bytes.len() + 8 - pos;
1143                         b[8 + start - end..].copy_from_slice(&bytes[start..end]);
1144                         res[i + WORD_COUNT_384 - u64s] = u64::from_be_bytes(b);
1145                 }
1146                 Ok(U384(res))
1147         }
1148
1149         /// Constructs a new [`U384`] from a fixed number of big-endian bytes.
1150         pub(super) const fn from_48_be_bytes_panicking(bytes: &[u8; 48]) -> U384 {
1151                 let res = [
1152                         eight_bytes_to_u64_be(bytes[0*8 + 0], bytes[0*8 + 1], bytes[0*8 + 2], bytes[0*8 + 3],
1153                                               bytes[0*8 + 4], bytes[0*8 + 5], bytes[0*8 + 6], bytes[0*8 + 7]),
1154                         eight_bytes_to_u64_be(bytes[1*8 + 0], bytes[1*8 + 1], bytes[1*8 + 2], bytes[1*8 + 3],
1155                                               bytes[1*8 + 4], bytes[1*8 + 5], bytes[1*8 + 6], bytes[1*8 + 7]),
1156                         eight_bytes_to_u64_be(bytes[2*8 + 0], bytes[2*8 + 1], bytes[2*8 + 2], bytes[2*8 + 3],
1157                                               bytes[2*8 + 4], bytes[2*8 + 5], bytes[2*8 + 6], bytes[2*8 + 7]),
1158                         eight_bytes_to_u64_be(bytes[3*8 + 0], bytes[3*8 + 1], bytes[3*8 + 2], bytes[3*8 + 3],
1159                                               bytes[3*8 + 4], bytes[3*8 + 5], bytes[3*8 + 6], bytes[3*8 + 7]),
1160                         eight_bytes_to_u64_be(bytes[4*8 + 0], bytes[4*8 + 1], bytes[4*8 + 2], bytes[4*8 + 3],
1161                                               bytes[4*8 + 4], bytes[4*8 + 5], bytes[4*8 + 6], bytes[4*8 + 7]),
1162                         eight_bytes_to_u64_be(bytes[5*8 + 0], bytes[5*8 + 1], bytes[5*8 + 2], bytes[5*8 + 3],
1163                                               bytes[5*8 + 4], bytes[5*8 + 5], bytes[5*8 + 6], bytes[5*8 + 7]),
1164                 ];
1165                 U384(res)
1166         }
1167
1168         pub(super) const fn zero() -> U384 { U384([0, 0, 0, 0, 0, 0]) }
1169         pub(super) const fn one() -> U384 { U384([0, 0, 0, 0, 0, 1]) }
1170         pub(super) const fn three() -> U384 { U384([0, 0, 0, 0, 0, 3]) }
1171 }
1172
1173 impl<M: PrimeModulus<U384>> U384Mod<M> {
1174         const fn mont_reduction(mu: [u64; 12]) -> Self {
1175                 #[cfg(debug_assertions)] {
1176                         // Check NEGATIVE_PRIME_INV_MOD_R is correct. Since this is all const, the compiler
1177                         // should be able to do it at compile time alone.
1178                         let minus_one_mod_r = mul_6(&M::PRIME.0, &M::NEGATIVE_PRIME_INV_MOD_R.0);
1179                         assert!(slice_equal(const_subslice(&minus_one_mod_r, 6, 12), &[0xffff_ffff_ffff_ffff; 6]));
1180                 }
1181
1182                 #[cfg(debug_assertions)] {
1183                         // Check R_SQUARED_MOD_PRIME is correct. Since this is all const, the compiler
1184                         // should be able to do it at compile time alone.
1185                         let r_minus_one = [0xffff_ffff_ffff_ffff; 6];
1186                         let (mut r_mod_prime, _) = sub_6(&r_minus_one, &M::PRIME.0);
1187                         let r_mod_prime_overflow = add_u64!(r_mod_prime, 1);
1188                         assert!(!r_mod_prime_overflow);
1189                         let r_squared = sqr_6(&r_mod_prime);
1190                         let mut prime_extended = [0; 12];
1191                         let prime = M::PRIME.0;
1192                         copy_from_slice!(prime_extended, 6, 12, prime);
1193                         let (_, r_squared_mod_prime) = if let Ok(v) = div_rem_12(&r_squared, &prime_extended) { v } else { panic!() };
1194                         assert!(slice_greater_than(&prime_extended, &r_squared_mod_prime));
1195                         assert!(slice_equal(const_subslice(&r_squared_mod_prime, 6, 12), &M::R_SQUARED_MOD_PRIME.0));
1196                 }
1197
1198                 // mu % R is just the bottom 4 bytes of mu
1199                 let mu_mod_r = const_subslice(&mu, 6, 12);
1200                 // v = ((mu % R) * negative_modulus_inverse) % R
1201                 let mut v = mul_6(&mu_mod_r, &M::NEGATIVE_PRIME_INV_MOD_R.0);
1202                 const ZEROS: &[u64; 6] = &[0; 6];
1203                 copy_from_slice!(v, 0, 6, ZEROS); // mod R
1204
1205                 // t_on_r = (mu + v*modulus) / R
1206                 let t0 = mul_6(const_subslice(&v, 6, 12), &M::PRIME.0);
1207                 let (t1, t1_extra_bit) = add_12(&t0, &mu);
1208
1209                 // Note that dividing t1 by R is simply a matter of shifting right by 4 bytes.
1210                 // We only need to maintain 4 bytes (plus `t1_extra_bit` which is implicitly an extra bit)
1211                 // because t_on_r is guarantee to be, at max, 2*m - 1.
1212                 let t1_on_r = const_subslice(&t1, 0, 6);
1213
1214                 let mut res = [0; 6];
1215                 // The modulus is only 4 bytes, so t1_extra_bit implies we're definitely larger than the
1216                 // modulus.
1217                 if t1_extra_bit || slice_greater_than(&t1_on_r, &M::PRIME.0) {
1218                         let underflow;
1219                         (res, underflow) = sub_6(&t1_on_r, &M::PRIME.0);
1220                         debug_assert!(t1_extra_bit == underflow);
1221                 } else {
1222                         copy_from_slice!(res, 0, 6, t1_on_r);
1223                 }
1224                 Self(U384(res), PhantomData)
1225         }
1226
1227         pub(super) const fn from_u384_panicking(v: U384) -> Self {
1228                 assert!(v.0[0] <= M::PRIME.0[0]);
1229                 if v.0[0] == M::PRIME.0[0] {
1230                         assert!(v.0[1] <= M::PRIME.0[1]);
1231                         if v.0[1] == M::PRIME.0[1] {
1232                                 assert!(v.0[2] <= M::PRIME.0[2]);
1233                                 if v.0[2] == M::PRIME.0[2] {
1234                                         assert!(v.0[3] <= M::PRIME.0[3]);
1235                                         if v.0[3] == M::PRIME.0[3] {
1236                                                 assert!(v.0[4] <= M::PRIME.0[4]);
1237                                                 if v.0[4] == M::PRIME.0[4] {
1238                                                         assert!(v.0[5] < M::PRIME.0[5]);
1239                                                 }
1240                                         }
1241                                 }
1242                         }
1243                 }
1244                 assert!(M::PRIME.0[0] != 0 || M::PRIME.0[1] != 0 || M::PRIME.0[2] != 0
1245                         || M::PRIME.0[3] != 0|| M::PRIME.0[4] != 0|| M::PRIME.0[5] != 0);
1246                 Self::mont_reduction(mul_6(&M::R_SQUARED_MOD_PRIME.0, &v.0))
1247         }
1248
1249         pub(super) fn from_u384(mut v: U384) -> Self {
1250                 debug_assert!(M::PRIME.0 != [0; 6]);
1251                 debug_assert!(M::PRIME.0[0] > (1 << 63), "PRIME should have the top bit set");
1252                 while v >= M::PRIME {
1253                         let (new_v, spurious_underflow) = sub_6(&v.0, &M::PRIME.0);
1254                         debug_assert!(!spurious_underflow);
1255                         v = U384(new_v);
1256                 }
1257                 Self::mont_reduction(mul_6(&M::R_SQUARED_MOD_PRIME.0, &v.0))
1258         }
1259
1260         pub(super) fn from_modinv_of(v: U384) -> Result<Self, ()> {
1261                 Ok(Self::from_u384(U384(mod_inv_6(&v.0, &M::PRIME.0)?)))
1262         }
1263
1264         /// Multiplies `self` * `b` mod `m`.
1265         ///
1266         /// Panics if `self`'s modulus is not equal to `b`'s
1267         pub(super) fn mul(&self, b: &Self) -> Self {
1268                 Self::mont_reduction(mul_6(&self.0.0, &b.0.0))
1269         }
1270
1271         /// Doubles `self` mod `m`.
1272         pub(super) fn double(&self) -> Self {
1273                 let mut res = self.0.0;
1274                 let overflow = double!(res);
1275                 if overflow || !slice_greater_than(&M::PRIME.0, &res) {
1276                         let underflow;
1277                         (res, underflow) = sub_6(&res, &M::PRIME.0);
1278                         debug_assert_eq!(overflow, underflow);
1279                 }
1280                 Self(U384(res), PhantomData)
1281         }
1282
1283         /// Multiplies `self` by 3 mod `m`.
1284         pub(super) fn times_three(&self) -> Self {
1285                 // TODO: Optimize this a lot
1286                 self.mul(&U384Mod::from_u384(U384::three()))
1287         }
1288
1289         /// Multiplies `self` by 4 mod `m`.
1290         pub(super) fn times_four(&self) -> Self {
1291                 // TODO: Optimize this somewhat?
1292                 self.double().double()
1293         }
1294
1295         /// Multiplies `self` by 8 mod `m`.
1296         pub(super) fn times_eight(&self) -> Self {
1297                 // TODO: Optimize this somewhat?
1298                 self.double().double().double()
1299         }
1300
1301         /// Multiplies `self` by 8 mod `m`.
1302         pub(super) fn square(&self) -> Self {
1303                 Self::mont_reduction(sqr_6(&self.0.0))
1304         }
1305
1306         /// Subtracts `b` from `self` % `m`.
1307         pub(super) fn sub(&self, b: &Self) -> Self {
1308                 let (mut val, underflow) = sub_6(&self.0.0, &b.0.0);
1309                 if underflow {
1310                         let overflow;
1311                         (val, overflow) = add_6(&val, &M::PRIME.0);
1312                         debug_assert_eq!(overflow, underflow);
1313                 }
1314                 Self(U384(val), PhantomData)
1315         }
1316
1317         /// Adds `b` to `self` % `m`.
1318         pub(super) fn add(&self, b: &Self) -> Self {
1319                 let (mut val, overflow) = add_6(&self.0.0, &b.0.0);
1320                 if overflow || !slice_greater_than(&M::PRIME.0, &val) {
1321                         let underflow;
1322                         (val, underflow) = sub_6(&val, &M::PRIME.0);
1323                         debug_assert_eq!(overflow, underflow);
1324                 }
1325                 Self(U384(val), PhantomData)
1326         }
1327
1328         /// Returns the underlying [`U384`].
1329         pub(super) fn into_u384(self) -> U384 {
1330                 let mut expanded_self = [0; 12];
1331                 expanded_self[6..].copy_from_slice(&self.0.0);
1332                 Self::mont_reduction(expanded_self).0
1333         }
1334 }
1335
1336 #[cfg(fuzzing)]
1337 mod fuzz_moduli {
1338         use super::*;
1339
1340         pub struct P256();
1341         impl PrimeModulus<U256> for P256 {
1342                 const PRIME: U256 = U256::from_32_be_bytes_panicking(&hex_lit::hex!(
1343                         "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"));
1344                 const R_SQUARED_MOD_PRIME: U256 = U256::from_32_be_bytes_panicking(&hex_lit::hex!(
1345                         "00000004fffffffdfffffffffffffffefffffffbffffffff0000000000000003"));
1346                 const NEGATIVE_PRIME_INV_MOD_R: U256 = U256::from_32_be_bytes_panicking(&hex_lit::hex!(
1347                         "ffffffff00000002000000000000000000000001000000000000000000000001"));
1348         }
1349
1350         pub struct P384();
1351         impl PrimeModulus<U384> for P384 {
1352                 const PRIME: U384 = U384::from_48_be_bytes_panicking(&hex_lit::hex!(
1353                         "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"));
1354                 const R_SQUARED_MOD_PRIME: U384 = U384::from_48_be_bytes_panicking(&hex_lit::hex!(
1355                         "000000000000000000000000000000010000000200000000fffffffe000000000000000200000000fffffffe00000001"));
1356                 const NEGATIVE_PRIME_INV_MOD_R: U384 = U384::from_48_be_bytes_panicking(&hex_lit::hex!(
1357                         "00000014000000140000000c00000002fffffffcfffffffafffffffbfffffffe00000000000000010000000100000001"));
1358         }
1359 }
1360
1361 #[cfg(fuzzing)]
1362 extern crate ibig;
1363 #[cfg(fuzzing)]
1364 /// Read some bytes and use them to test bigint math by comparing results against the `ibig` crate.
1365 pub fn fuzz_math(input: &[u8]) {
1366         if input.len() < 32 || input.len() % 16 != 0 { return; }
1367         let split = core::cmp::min(input.len() / 2, 512);
1368         let (a, b) = input.split_at(core::cmp::min(input.len() / 2, 512));
1369         let b = &b[..split];
1370
1371         let ai = ibig::UBig::from_be_bytes(&a);
1372         let bi = ibig::UBig::from_be_bytes(&b);
1373
1374         let mut a_u64s = Vec::with_capacity(split / 8);
1375         for chunk in a.chunks(8) {
1376                 a_u64s.push(u64::from_be_bytes(chunk.try_into().unwrap()));
1377         }
1378         let mut b_u64s = Vec::with_capacity(split / 8);
1379         for chunk in b.chunks(8) {
1380                 b_u64s.push(u64::from_be_bytes(chunk.try_into().unwrap()));
1381         }
1382
1383         macro_rules! test { ($mul: ident, $sqr: ident, $add: ident, $sub: ident, $div_rem: ident, $mod_inv: ident) => {
1384                 let res = $mul(&a_u64s, &b_u64s);
1385                 let mut res_bytes = Vec::with_capacity(input.len() / 2);
1386                 for i in res {
1387                         res_bytes.extend_from_slice(&i.to_be_bytes());
1388                 }
1389                 assert_eq!(ibig::UBig::from_be_bytes(&res_bytes), ai.clone() * bi.clone());
1390
1391                 debug_assert_eq!($mul(&a_u64s, &a_u64s), $sqr(&a_u64s));
1392                 debug_assert_eq!($mul(&b_u64s, &b_u64s), $sqr(&b_u64s));
1393
1394                 let (res, carry) = $add(&a_u64s, &b_u64s);
1395                 let mut res_bytes = Vec::with_capacity(input.len() / 2 + 1);
1396                 if carry { res_bytes.push(1); } else { res_bytes.push(0); }
1397                 for i in res {
1398                         res_bytes.extend_from_slice(&i.to_be_bytes());
1399                 }
1400                 assert_eq!(ibig::UBig::from_be_bytes(&res_bytes), ai.clone() + bi.clone());
1401
1402                 let mut add_u64s = a_u64s.clone();
1403                 let carry = add_u64!(add_u64s, 1);
1404                 let mut res_bytes = Vec::with_capacity(input.len() / 2 + 1);
1405                 if carry { res_bytes.push(1); } else { res_bytes.push(0); }
1406                 for i in &add_u64s {
1407                         res_bytes.extend_from_slice(&i.to_be_bytes());
1408                 }
1409                 assert_eq!(ibig::UBig::from_be_bytes(&res_bytes), ai.clone() + 1);
1410
1411                 let mut double_u64s = b_u64s.clone();
1412                 let carry = double!(double_u64s);
1413                 let mut res_bytes = Vec::with_capacity(input.len() / 2 + 1);
1414                 if carry { res_bytes.push(1); } else { res_bytes.push(0); }
1415                 for i in &double_u64s {
1416                         res_bytes.extend_from_slice(&i.to_be_bytes());
1417                 }
1418                 assert_eq!(ibig::UBig::from_be_bytes(&res_bytes), bi.clone() * 2);
1419
1420                 let (quot, rem) = if let Ok(res) =
1421                         $div_rem(&a_u64s[..].try_into().unwrap(), &b_u64s[..].try_into().unwrap()) {
1422                                 res
1423                         } else { return };
1424                 let mut quot_bytes = Vec::with_capacity(input.len() / 2);
1425                 for i in quot {
1426                         quot_bytes.extend_from_slice(&i.to_be_bytes());
1427                 }
1428                 let mut rem_bytes = Vec::with_capacity(input.len() / 2);
1429                 for i in rem {
1430                         rem_bytes.extend_from_slice(&i.to_be_bytes());
1431                 }
1432                 let (quoti, remi) = ibig::ops::DivRem::div_rem(ai.clone(), &bi);
1433                 assert_eq!(ibig::UBig::from_be_bytes(&quot_bytes), quoti);
1434                 assert_eq!(ibig::UBig::from_be_bytes(&rem_bytes), remi);
1435
1436                 if ai != ibig::UBig::from(0u32) { // ibig provides a spurious modular inverse for 0
1437                         let ring = ibig::modular::ModuloRing::new(&bi);
1438                         let ar = ring.from(ai.clone());
1439                         let invi = ar.inverse().map(|i| i.residue());
1440
1441                         if let Ok(modinv) = $mod_inv(&a_u64s[..].try_into().unwrap(), &b_u64s[..].try_into().unwrap()) {
1442                                 let mut modinv_bytes = Vec::with_capacity(input.len() / 2);
1443                                 for i in modinv {
1444                                         modinv_bytes.extend_from_slice(&i.to_be_bytes());
1445                                 }
1446                                 assert_eq!(invi.unwrap(), ibig::UBig::from_be_bytes(&modinv_bytes));
1447                         } else {
1448                                 assert!(invi.is_none());
1449                         }
1450                 }
1451         } }
1452
1453         macro_rules! test_mod { ($amodp: expr, $bmodp: expr, $PRIME: expr, $len: expr, $into: ident, $div_rem_double: ident, $div_rem: ident, $mul: ident, $add: ident, $sub: ident) => {
1454                 // Test the U256/U384Mod wrapper, which operates in Montgomery representation
1455                 let mut p_extended = [0; $len * 2];
1456                 p_extended[$len..].copy_from_slice(&$PRIME);
1457
1458                 let amodp_squared = $div_rem_double(&$mul(&a_u64s, &a_u64s), &p_extended).unwrap().1;
1459                 assert_eq!(&amodp_squared[..$len], &[0; $len]);
1460                 assert_eq!(&$amodp.square().$into().0, &amodp_squared[$len..]);
1461
1462                 let abmodp = $div_rem_double(&$mul(&a_u64s, &b_u64s), &p_extended).unwrap().1;
1463                 assert_eq!(&abmodp[..$len], &[0; $len]);
1464                 assert_eq!(&$amodp.mul(&$bmodp).$into().0, &abmodp[$len..]);
1465
1466                 let (aplusb, aplusb_overflow) = $add(&a_u64s, &b_u64s);
1467                 let mut aplusb_extended = [0; $len * 2];
1468                 aplusb_extended[$len..].copy_from_slice(&aplusb);
1469                 if aplusb_overflow { aplusb_extended[$len - 1] = 1; }
1470                 let aplusbmodp = $div_rem_double(&aplusb_extended, &p_extended).unwrap().1;
1471                 assert_eq!(&aplusbmodp[..$len], &[0; $len]);
1472                 assert_eq!(&$amodp.add(&$bmodp).$into().0, &aplusbmodp[$len..]);
1473
1474                 let (mut aminusb, aminusb_underflow) = $sub(&a_u64s, &b_u64s);
1475                 if aminusb_underflow {
1476                         let mut overflow;
1477                         (aminusb, overflow) = $add(&aminusb, &$PRIME);
1478                         if !overflow {
1479                                 (aminusb, overflow) = $add(&aminusb, &$PRIME);
1480                         }
1481                         assert!(overflow);
1482                 }
1483                 let aminusbmodp = $div_rem(&aminusb, &$PRIME).unwrap().1;
1484                 assert_eq!(&$amodp.sub(&$bmodp).$into().0, &aminusbmodp);
1485         } }
1486
1487         if a_u64s.len() == 2 {
1488                 test!(mul_2, sqr_2, add_2, sub_2, div_rem_2, mod_inv_2);
1489         } else if a_u64s.len() == 4 {
1490                 test!(mul_4, sqr_4, add_4, sub_4, div_rem_4, mod_inv_4);
1491                 let amodp = U256Mod::<fuzz_moduli::P256>::from_u256(U256(a_u64s[..].try_into().unwrap()));
1492                 let bmodp = U256Mod::<fuzz_moduli::P256>::from_u256(U256(b_u64s[..].try_into().unwrap()));
1493                 test_mod!(amodp, bmodp, fuzz_moduli::P256::PRIME.0, 4, into_u256, div_rem_8, div_rem_4, mul_4, add_4, sub_4);
1494         } else if a_u64s.len() == 6 {
1495                 test!(mul_6, sqr_6, add_6, sub_6, div_rem_6, mod_inv_6);
1496                 let amodp = U384Mod::<fuzz_moduli::P384>::from_u384(U384(a_u64s[..].try_into().unwrap()));
1497                 let bmodp = U384Mod::<fuzz_moduli::P384>::from_u384(U384(b_u64s[..].try_into().unwrap()));
1498                 test_mod!(amodp, bmodp, fuzz_moduli::P384::PRIME.0, 6, into_u384, div_rem_12, div_rem_6, mul_6, add_6, sub_6);
1499         } else if a_u64s.len() == 8 {
1500                 test!(mul_8, sqr_8, add_8, sub_8, div_rem_8, mod_inv_8);
1501         } else if input.len() == 512*2 + 4 {
1502                 let mut e_bytes = [0; 4];
1503                 e_bytes.copy_from_slice(&input[512 * 2..512 * 2 + 4]);
1504                 let e = u32::from_le_bytes(e_bytes);
1505                 let a = U4096::from_be_bytes(&a).unwrap();
1506                 let b = U4096::from_be_bytes(&b).unwrap();
1507
1508                 let res = if let Ok(r) = a.expmod_odd_mod(e, &b) { r } else { return };
1509                 let mut res_bytes = Vec::with_capacity(512);
1510                 for i in res.0 {
1511                         res_bytes.extend_from_slice(&i.to_be_bytes());
1512                 }
1513
1514                 let ring = ibig::modular::ModuloRing::new(&bi);
1515                 let ar = ring.from(ai.clone());
1516                 assert_eq!(ar.pow(&e.into()).residue(), ibig::UBig::from_be_bytes(&res_bytes));
1517         }
1518 }
1519
1520 #[cfg(test)]
1521 mod tests {
1522         use super::*;
1523
1524         fn u64s_to_u128(v: [u64; 2]) -> u128 {
1525                 let mut r = 0;
1526                 r |= v[1] as u128;
1527                 r |= (v[0] as u128) << 64;
1528                 r
1529         }
1530
1531         fn u64s_to_i128(v: [u64; 2]) -> i128 {
1532                 let mut r = 0;
1533                 r |= v[1] as i128;
1534                 r |= (v[0] as i128) << 64;
1535                 r
1536         }
1537
1538         #[test]
1539         fn test_negate() {
1540                 let mut zero = [0u64; 2];
1541                 negate!(zero);
1542                 assert_eq!(zero, [0; 2]);
1543
1544                 let mut one = [0u64, 1u64];
1545                 negate!(one);
1546                 assert_eq!(u64s_to_i128(one), -1);
1547
1548                 let mut minus_one: [u64; 2] = [u64::MAX, u64::MAX];
1549                 negate!(minus_one);
1550                 assert_eq!(minus_one, [0, 1]);
1551         }
1552
1553         #[test]
1554         fn test_double() {
1555                 let mut zero = [0u64; 2];
1556                 assert!(!double!(zero));
1557                 assert_eq!(zero, [0; 2]);
1558
1559                 let mut one = [0u64, 1u64];
1560                 assert!(!double!(one));
1561                 assert_eq!(one, [0, 2]);
1562
1563                 let mut u64_max = [0, u64::MAX];
1564                 assert!(!double!(u64_max));
1565                 assert_eq!(u64_max, [1, u64::MAX - 1]);
1566
1567                 let mut u64_carry_overflow = [0x7fff_ffff_ffff_ffffu64, 0x8000_0000_0000_0000];
1568                 assert!(!double!(u64_carry_overflow));
1569                 assert_eq!(u64_carry_overflow, [u64::MAX, 0]);
1570
1571                 let mut max = [u64::MAX; 4];
1572                 assert!(double!(max));
1573                 assert_eq!(max, [u64::MAX, u64::MAX, u64::MAX, u64::MAX - 1]);
1574         }
1575
1576         #[test]
1577         fn mul_min_simple_tests() {
1578                 let a = [1, 2];
1579                 let b = [3, 4];
1580                 let res = mul_2(&a, &b);
1581                 assert_eq!(res, [0, 3, 10, 8]);
1582
1583                 let a = [0x1bad_cafe_dead_beef, 2424];
1584                 let b = [0x2bad_beef_dead_cafe, 4242];
1585                 let res = mul_2(&a, &b);
1586                 assert_eq!(res, [340296855556511776, 15015369169016130186, 4248480538569992542, 10282608]);
1587
1588                 let a = [0xf6d9_f8eb_8b60_7a6d, 0x4b93_833e_2194_fc2e];
1589                 let b = [0xfdab_0000_6952_8ab4, 0xd302_0000_8282_0000];
1590                 let res = mul_2(&a, &b);
1591                 assert_eq!(res, [17625486516939878681, 18390748118453258282, 2695286104209847530, 1510594524414214144]);
1592
1593                 let a = [0x8b8b_8b8b_8b8b_8b8b, 0x8b8b_8b8b_8b8b_8b8b];
1594                 let b = [0x8b8b_8b8b_8b8b_8b8b, 0x8b8b_8b8b_8b8b_8b8b];
1595                 let res = mul_2(&a, &b);
1596                 assert_eq!(res, [5481115605507762349, 8230042173354675923, 16737530186064798, 15714555036048702841]);
1597
1598                 let a = [0x0000_0000_0000_0020, 0x002d_362c_005b_7753];
1599                 let b = [0x0900_0000_0030_0003, 0xb708_00fe_0000_00cd];
1600                 let res = mul_2(&a, &b);
1601                 assert_eq!(res, [1, 2306290405521702946, 17647397529888728169, 10271802099389861239]);
1602
1603                 let a = [0x0000_0000_7fff_ffff, 0xffff_ffff_0000_0000];
1604                 let b = [0x0000_0800_0000_0000, 0x0000_1000_0000_00e1];
1605                 let res = mul_2(&a, &b);
1606                 assert_eq!(res, [1024, 0, 483183816703, 18446743107341910016]);
1607
1608                 let a = [0xf6d9_f8eb_ebeb_eb6d, 0x4b93_83a0_bb35_0680];
1609                 let b = [0xfd02_b9b9_b9b9_b9b9, 0xb9b9_b9b9_b9b9_b9b9];
1610                 let res = mul_2(&a, &b);
1611                 assert_eq!(res, [17579814114991930107, 15033987447865175985, 488855932380801351, 5453318140933190272]);
1612
1613                 let a = [u64::MAX; 2];
1614                 let b = [u64::MAX; 2];
1615                 let res = mul_2(&a, &b);
1616                 assert_eq!(res, [18446744073709551615, 18446744073709551614, 0, 1]);
1617         }
1618
1619         #[test]
1620         fn test_add_sub() {
1621                 fn test(a: [u64; 2], b: [u64; 2]) {
1622                         let a_int = u64s_to_u128(a);
1623                         let b_int = u64s_to_u128(b);
1624
1625                         let res = add_2(&a, &b);
1626                         assert_eq!((u64s_to_u128(res.0), res.1), a_int.overflowing_add(b_int));
1627
1628                         let res = sub_2(&a, &b);
1629                         assert_eq!((u64s_to_u128(res.0), res.1), a_int.overflowing_sub(b_int));
1630                 }
1631
1632                 test([0; 2], [0; 2]);
1633                 test([0x1bad_cafe_dead_beef, 2424], [0x2bad_cafe_dead_cafe, 4242]);
1634                 test([u64::MAX; 2], [u64::MAX; 2]);
1635                 test([u64::MAX, 0x8000_0000_0000_0000], [0, 0x7fff_ffff_ffff_ffff]);
1636                 test([0, 0x7fff_ffff_ffff_ffff], [u64::MAX, 0x8000_0000_0000_0000]);
1637                 test([u64::MAX, 0], [0, u64::MAX]);
1638                 test([0, u64::MAX], [u64::MAX, 0]);
1639                 test([u64::MAX; 2], [0; 2]);
1640                 test([0; 2], [u64::MAX; 2]);
1641         }
1642
1643         #[test]
1644         fn mul_4_simple_tests() {
1645                 let a = [1; 4];
1646                 let b = [2; 4];
1647                 assert_eq!(mul_4(&a, &b),
1648                         [0, 2, 4, 6, 8, 6, 4, 2]);
1649
1650                 let a = [0x1bad_cafe_dead_beef, 2424, 0x1bad_cafe_dead_beef, 2424];
1651                 let b = [0x2bad_beef_dead_cafe, 4242, 0x2bad_beef_dead_cafe, 4242];
1652                 assert_eq!(mul_4(&a, &b),
1653                         [340296855556511776, 15015369169016130186, 4929074249683016095, 11583994264332991364,
1654                          8837257932696496860, 15015369169036695402, 4248480538569992542, 10282608]);
1655
1656                 let a = [u64::MAX; 4];
1657                 let b = [u64::MAX; 4];
1658                 assert_eq!(mul_4(&a, &b),
1659                         [18446744073709551615, 18446744073709551615, 18446744073709551615,
1660                          18446744073709551614, 0, 0, 0, 1]);
1661         }
1662
1663         #[test]
1664         fn double_simple_tests() {
1665                 let mut a = [0xfff5_b32d_01ff_0000, 0x00e7_e7e7_e7e7_e7e7];
1666                 assert!(double!(a));
1667                 assert_eq!(a, [18440945635998695424, 130551405668716494]);
1668
1669                 let mut a = [u64::MAX, u64::MAX];
1670                 assert!(double!(a));
1671                 assert_eq!(a, [18446744073709551615, 18446744073709551614]);
1672         }
1673 }