1#![allow(unused_imports)]
2
3extern crate byteorder;
4extern crate hex as hex_ext;
5extern crate rand;
6extern crate serde;
7pub mod hex {
8 pub use hex_ext::*;
9}
10
11#[cfg(feature = "derive")]
12#[macro_use]
13extern crate ff_derive;
14
15#[cfg(feature = "derive")]
16pub use ff_derive::*;
17
18use std::error::Error;
19use std::fmt;
20use std::hash;
21use std::io::{self, Read, Write};
22
23pub trait Field: Sized + Eq + Copy + Clone + Send + Sync + fmt::Debug + fmt::Display + 'static + rand::Rand + hash::Hash + Default + serde::Serialize + serde::de::DeserializeOwned {
25 fn zero() -> Self;
27
28 fn one() -> Self;
30
31 fn is_zero(&self) -> bool;
33
34 fn square(&mut self);
36
37 fn double(&mut self);
39
40 fn negate(&mut self);
42
43 fn add_assign(&mut self, other: &Self);
45
46 fn sub_assign(&mut self, other: &Self);
48
49 fn mul_assign(&mut self, other: &Self);
51
52 fn inverse(&self) -> Option<Self>;
54
55 fn frobenius_map(&mut self, power: usize);
58
59 fn pow<S: AsRef<[u64]>>(&self, exp: S) -> Self {
62 let mut res = Self::one();
63
64 let mut found_one = false;
65
66 for i in BitIterator::new(exp) {
67 if found_one {
68 res.square();
69 } else {
70 found_one = i;
71 }
72
73 if i {
74 res.mul_assign(self);
75 }
76 }
77
78 res
79 }
80}
81
82pub trait SqrtField: Field {
84 fn legendre(&self) -> LegendreSymbol;
86
87 fn sqrt(&self) -> Option<Self>;
90}
91
92pub trait PrimeFieldRepr:
96 Sized
97 + Copy
98 + Clone
99 + Eq
100 + Ord
101 + Send
102 + Sync
103 + Default
104 + fmt::Debug
105 + fmt::Display
106 + 'static
107 + rand::Rand
108 + AsRef<[u64]>
109 + AsMut<[u64]>
110 + From<u64>
111 + hash::Hash
112 + serde::Serialize
113 + serde::de::DeserializeOwned
114{
115 fn sub_noborrow(&mut self, other: &Self);
117
118 fn add_nocarry(&mut self, other: &Self);
120
121 fn num_bits(&self) -> u32;
124
125 fn is_zero(&self) -> bool;
127
128 fn is_odd(&self) -> bool;
130
131 fn is_even(&self) -> bool;
133
134 fn div2(&mut self);
137
138 fn shr(&mut self, amt: u32);
140
141 fn mul2(&mut self);
144
145 fn shl(&mut self, amt: u32);
147
148 fn write_be<W: Write>(&self, mut writer: W) -> io::Result<()> {
150 use byteorder::{BigEndian, WriteBytesExt};
151
152 for digit in self.as_ref().iter().rev() {
153 writer.write_u64::<BigEndian>(*digit)?;
154 }
155
156 Ok(())
157 }
158
159 fn read_be<R: Read>(&mut self, mut reader: R) -> io::Result<()> {
161 use byteorder::{BigEndian, ReadBytesExt};
162
163 for digit in self.as_mut().iter_mut().rev() {
164 *digit = reader.read_u64::<BigEndian>()?;
165 }
166
167 Ok(())
168 }
169
170 fn write_le<W: Write>(&self, mut writer: W) -> io::Result<()> {
172 use byteorder::{LittleEndian, WriteBytesExt};
173
174 for digit in self.as_ref().iter() {
175 writer.write_u64::<LittleEndian>(*digit)?;
176 }
177
178 Ok(())
179 }
180
181 fn read_le<R: Read>(&mut self, mut reader: R) -> io::Result<()> {
183 use byteorder::{LittleEndian, ReadBytesExt};
184
185 for digit in self.as_mut().iter_mut() {
186 *digit = reader.read_u64::<LittleEndian>()?;
187 }
188
189 Ok(())
190 }
191}
192
193#[derive(Debug, PartialEq)]
194pub enum LegendreSymbol {
195 Zero = 0,
196 QuadraticResidue = 1,
197 QuadraticNonResidue = -1,
198}
199
200#[derive(Debug)]
203pub enum PrimeFieldDecodingError {
204 NotInField(String),
206}
207
208impl Error for PrimeFieldDecodingError {
209 fn description(&self) -> &str {
210 match *self {
211 PrimeFieldDecodingError::NotInField(..) => "not an element of the field",
212 }
213 }
214}
215
216impl fmt::Display for PrimeFieldDecodingError {
217 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
218 match *self {
219 PrimeFieldDecodingError::NotInField(ref repr) => {
220 write!(f, "{} is not an element of the field", repr)
221 }
222 }
223 }
224}
225
226pub trait PrimeField: Field {
228 type Repr: PrimeFieldRepr + From<Self>;
231
232 fn from_str(s: &str) -> Option<Self> {
235 if s.is_empty() {
236 return None;
237 }
238
239 if s == "0" {
240 return Some(Self::zero());
241 }
242
243 let mut res = Self::zero();
244
245 let ten = Self::from_repr(Self::Repr::from(10)).unwrap();
246
247 let mut first_digit = true;
248
249 for c in s.chars() {
250 match c.to_digit(10) {
251 Some(c) => {
252 if first_digit {
253 if c == 0 {
254 return None;
255 }
256
257 first_digit = false;
258 }
259
260 res.mul_assign(&ten);
261 res.add_assign(&Self::from_repr(Self::Repr::from(u64::from(c))).unwrap());
262 }
263 None => {
264 return None;
265 }
266 }
267 }
268
269 Some(res)
270 }
271
272 fn from_repr(repr: Self::Repr) -> Result<Self, PrimeFieldDecodingError>;
274
275 fn from_raw_repr(repr: Self::Repr) -> Result<Self, PrimeFieldDecodingError>;
277
278 fn into_repr(&self) -> Self::Repr;
281
282 fn into_raw_repr(&self) -> Self::Repr;
284
285 fn char() -> Self::Repr;
287
288 const NUM_BITS: u32;
290
291 const CAPACITY: u32;
293
294 fn multiplicative_generator() -> Self;
297
298 const S: u32;
300
301 fn root_of_unity() -> Self;
304}
305
306pub trait ScalarEngine: Sized + 'static + Clone + Copy + Send + Sync + fmt::Debug {
310 type Fr: PrimeField + SqrtField;
312}
313
314#[derive(Debug)]
315pub struct BitIterator<E> {
316 t: E,
317 n: usize,
318}
319
320impl<E: AsRef<[u64]>> BitIterator<E> {
321 pub fn new(t: E) -> Self {
322 let n = t.as_ref().len() * 64;
323
324 BitIterator { t, n }
325 }
326}
327
328impl<E: AsRef<[u64]>> Iterator for BitIterator<E> {
329 type Item = bool;
330
331 fn next(&mut self) -> Option<bool> {
332 if self.n == 0 {
333 None
334 } else {
335 self.n -= 1;
336 let part = self.n / 64;
337 let bit = self.n - (64 * part);
338
339 Some(self.t.as_ref()[part] & (1 << bit) > 0)
340 }
341 }
342
343 fn size_hint(&self) -> (usize, Option<usize>) {
344 (self.n, Some(self.n))
345 }
346}
347
348impl<E: AsRef<[u64]>> ExactSizeIterator for BitIterator<E> {
349 fn len(&self) -> usize {
350 self.n
351 }
352}
353
354#[test]
355fn test_bit_iterator() {
356 let mut a = BitIterator::new([0xa953d79b83f6ab59, 0x6dea2059e200bd39]);
357 let expected = "01101101111010100010000001011001111000100000000010111101001110011010100101010011110101111001101110000011111101101010101101011001";
358
359 for e in expected.chars() {
360 assert!(a.next().unwrap() == (e == '1'));
361 }
362
363 assert!(a.next().is_none());
364
365 let expected = "1010010101111110101010000101101011101000011101110101001000011001100100100011011010001011011011010001011011101100110100111011010010110001000011110100110001100110011101101000101100011100100100100100001010011101010111110011101011000011101000111011011101011001";
366
367 let mut a = BitIterator::new([0x429d5f3ac3a3b759, 0xb10f4c66768b1c92, 0x92368b6d16ecd3b4, 0xa57ea85ae8775219]);
368
369 for e in expected.chars() {
370 assert!(a.next().unwrap() == (e == '1'));
371 }
372
373 assert!(a.next().is_none());
374}
375
376#[test]
377fn test_bit_iterator_length() {
378 let a = BitIterator::new([0xa953d79b83f6ab59, 0x6dea2059e200bd39]);
379 let trusted_len = a.len();
380 let (lower, some_upper) = a.size_hint();
381 let upper = some_upper.unwrap();
382 assert_eq!(trusted_len, 128);
383 assert_eq!(lower, 128);
384 assert_eq!(upper, 128);
385
386 let mut i = 0;
387 for _ in a {
388 i += 1;
389 }
390
391 assert_eq!(trusted_len, i);
392}
393
394pub use self::arith_impl::*;
395
396mod arith_impl {
397 #[inline(always)]
400 pub fn sbb(a: u64, b: u64, borrow: &mut u64) -> u64 {
401 use std::num::Wrapping;
402
403 let tmp = (1u128 << 64).wrapping_add(u128::from(a)).wrapping_sub(u128::from(b)).wrapping_sub(u128::from(*borrow));
404
405 *borrow = if tmp >> 64 == 0 { 1 } else { 0 };
406
407 tmp as u64
408 }
409
410 #[inline(always)]
413 pub fn adc(a: u64, b: u64, carry: &mut u64) -> u64 {
414 use std::num::Wrapping;
415
416 let tmp = u128::from(a).wrapping_add(u128::from(b)).wrapping_add(u128::from(*carry));
417
418 *carry = (tmp >> 64) as u64;
419
420 tmp as u64
421 }
422
423 #[inline(always)]
426 pub fn mac_with_carry(a: u64, b: u64, c: u64, carry: &mut u64) -> u64 {
427 use std::num::Wrapping;
428
429 let tmp = (u128::from(a)).wrapping_add(u128::from(b).wrapping_mul(u128::from(c))).wrapping_add(u128::from(*carry));
430
431 *carry = (tmp >> 64) as u64;
432
433 tmp as u64
434 }
435
436 #[inline(always)]
437 pub fn full_width_mul(a: u64, b: u64) -> (u64, u64) {
438 let tmp = (a as u128) * (b as u128);
439
440 return (tmp as u64, (tmp >> 64) as u64);
441 }
442
443 #[inline(always)]
444 pub fn mac_by_value(a: u64, b: u64, c: u64) -> (u64, u64) {
445 let tmp = ((b as u128) * (c as u128)) + (a as u128);
446
447 (tmp as u64, (tmp >> 64) as u64)
448 }
449
450 #[inline(always)]
451 pub fn mac_by_value_return_carry_only(a: u64, b: u64, c: u64) -> u64 {
452 let tmp = ((b as u128) * (c as u128)) + (a as u128);
453
454 (tmp >> 64) as u64
455 }
456
457 #[inline(always)]
458 pub fn mac_with_carry_by_value(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) {
459 let tmp = ((b as u128) * (c as u128)) + (a as u128) + (carry as u128);
460
461 (tmp as u64, (tmp >> 64) as u64)
462 }
463
464 #[inline(always)]
465 pub fn mul_double_add_by_value(a: u64, b: u64, c: u64) -> (u64, u64, u64) {
466 let tmp = (b as u128) * (c as u128);
468 let lo = tmp as u64;
470 let hi = (tmp >> 64) as u64;
471 let superhi = hi >> 63;
472 let hi = hi << 1 | lo >> 63;
473 let lo = lo << 1;
474 let tmp = (lo as u128) + ((hi as u128) << 64) + (a as u128);
476
477 (tmp as u64, (tmp >> 64) as u64, superhi)
478 }
479
480 #[inline(always)]
481 pub fn mul_double_add_add_carry_by_value(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64, u64) {
482 let tmp = (b as u128) * (c as u128);
484 let lo = tmp as u64;
486 let hi = (tmp >> 64) as u64;
487 let superhi = hi >> 63;
488 let hi = hi << 1 | lo >> 63;
489 let lo = lo << 1;
490 let tmp = (lo as u128) + ((hi as u128) << 64) + (a as u128) + (carry as u128);
492
493 (tmp as u64, (tmp >> 64) as u64, superhi)
494 }
495
496 #[inline(always)]
497 pub fn mul_double_add_add_carry_by_value_ignore_superhi(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) {
498 let tmp = (b as u128) * (c as u128);
500 let lo = tmp as u64;
502 let hi = (tmp >> 64) as u64;
503 let hi = hi << 1 | lo >> 63;
504 let lo = lo << 1;
505 let tmp = (lo as u128) + ((hi as u128) << 64) + (a as u128) + (carry as u128);
507
508 (tmp as u64, (tmp >> 64) as u64)
509 }
510
511 #[inline(always)]
512 pub fn mul_double_add_low_and_high_carry_by_value(b: u64, c: u64, lo_carry: u64, hi_carry: u64) -> (u64, u64, u64) {
513 let tmp = (b as u128) * (c as u128);
515 let lo = tmp as u64;
517 let hi = (tmp >> 64) as u64;
518 let superhi = hi >> 63;
519 let hi = hi << 1 | lo >> 63;
520 let lo = lo << 1;
521 let tmp = (lo as u128) + ((hi as u128) << 64) + (lo_carry as u128) + ((hi_carry as u128) << 64);
523
524 (tmp as u64, (tmp >> 64) as u64, superhi)
525 }
526
527 #[inline(always)]
528 pub fn mul_double_add_low_and_high_carry_by_value_ignore_superhi(b: u64, c: u64, lo_carry: u64, hi_carry: u64) -> (u64, u64) {
529 let tmp = (b as u128) * (c as u128);
531 let lo = tmp as u64;
533 let hi = (tmp >> 64) as u64;
534 let hi = hi << 1 | lo >> 63;
535 let lo = lo << 1;
536 let tmp = (lo as u128) + ((hi as u128) << 64) + (lo_carry as u128) + ((hi_carry as u128) << 64);
538
539 (tmp as u64, (tmp >> 64) as u64)
540 }
541
542 #[inline(always)]
543 pub fn mul_double_add_add_low_and_high_carry_by_value(a: u64, b: u64, c: u64, lo_carry: u64, hi_carry: u64) -> (u64, u64, u64) {
544 let tmp = (b as u128) * (c as u128);
546 let lo = tmp as u64;
548 let hi = (tmp >> 64) as u64;
549 let superhi = hi >> 63;
550 let hi = hi << 1 | lo >> 63;
551 let lo = lo << 1;
552 let tmp = (lo as u128) + ((hi as u128) << 64) + (a as u128) + (lo_carry as u128) + ((hi_carry as u128) << 64);
554
555 (tmp as u64, (tmp >> 64) as u64, superhi)
556 }
557
558 #[inline(always)]
559 pub fn mul_double_add_add_low_and_high_carry_by_value_ignore_superhi(a: u64, b: u64, c: u64, lo_carry: u64, hi_carry: u64) -> (u64, u64) {
560 let tmp = (b as u128) * (c as u128);
562 let lo = tmp as u64;
564 let hi = (tmp >> 64) as u64;
565 let hi = hi << 1 | lo >> 63;
566 let lo = lo << 1;
567 let tmp = (lo as u128) + ((hi as u128) << 64) + (a as u128) + (lo_carry as u128) + ((hi_carry as u128) << 64);
569
570 (tmp as u64, (tmp >> 64) as u64)
571 }
572
573 #[inline(always)]
574 pub fn mac_with_low_and_high_carry_by_value(a: u64, b: u64, c: u64, lo_carry: u64, hi_carry: u64) -> (u64, u64) {
575 let tmp = ((b as u128) * (c as u128)) + (a as u128) + (lo_carry as u128) + ((hi_carry as u128) << 64);
576
577 (tmp as u64, (tmp >> 64) as u64)
578 }
579}
580
581pub use to_hex::{from_hex, to_hex};
582
583mod to_hex {
584 use super::{hex_ext, PrimeField, PrimeFieldRepr};
585
586 pub fn to_hex<F: PrimeField>(el: &F) -> String {
587 let repr = el.into_repr();
588 let required_length = repr.as_ref().len() * 8;
589 let mut buf: Vec<u8> = Vec::with_capacity(required_length);
590 repr.write_be(&mut buf).unwrap();
591
592 hex_ext::encode(&buf)
593 }
594
595 pub fn from_hex<F: PrimeField>(value: &str) -> Result<F, String> {
596 let value = if value.starts_with("0x") { &value[2..] } else { value };
597 if value.len() % 2 != 0 {
598 return Err(format!("hex length must be even for full byte encoding: {}", value));
599 }
600 let mut buf = hex_ext::decode(&value).map_err(|_| format!("could not decode hex: {}", value))?;
601 let mut repr = F::Repr::default();
602 let required_length = repr.as_ref().len() * 8;
603 buf.reverse();
604 buf.resize(required_length, 0);
605
606 repr.read_le(&buf[..]).map_err(|e| format!("could not read {}: {}", value, &e))?;
607
608 F::from_repr(repr).map_err(|e| format!("could not convert into prime field: {}: {}", value, &e))
609 }
610}