1#![deny(intra_doc_link_resolution_failure)]
5#![allow(unused_imports)]
6
7#[cfg(feature = "derive")]
8#[macro_use]
9extern crate ff_derive_zeroize as ff_derive;
10
11#[cfg(feature = "derive")]
12pub use ff_derive::*;
13
14#[macro_use]
15extern crate zeroize;
16
17use rand_core::RngCore;
18use std::error::Error;
19use std::fmt;
20use std::io::{self, Read, Write};
21
22pub trait Field:
24 Sized + Eq + Copy + Clone + Send + Sync + fmt::Debug + fmt::Display + 'static
25{
26 fn random<R: RngCore + ?std::marker::Sized>(rng: &mut R) -> Self;
28
29 fn zero() -> Self;
31
32 fn one() -> Self;
34
35 fn is_zero(&self) -> bool;
37
38 fn square(&mut self);
40
41 fn double(&mut self);
43
44 fn negate(&mut self);
46
47 fn add_assign(&mut self, other: &Self);
49
50 fn sub_assign(&mut self, other: &Self);
52
53 fn mul_assign(&mut self, other: &Self);
55
56 fn inverse(&self) -> Option<Self>;
58
59 fn frobenius_map(&mut self, power: usize);
62
63 fn pow<S: AsRef<[u64]>>(&self, exp: S) -> Self {
66 let mut res = Self::one();
67
68 let mut found_one = false;
69
70 for i in BitIterator::new(exp) {
71 if found_one {
72 res.square();
73 } else {
74 found_one = i;
75 }
76
77 if i {
78 res.mul_assign(self);
79 }
80 }
81
82 res
83 }
84}
85
86pub trait SqrtField: Field {
88 fn legendre(&self) -> LegendreSymbol;
90
91 fn sqrt(&self) -> Option<Self>;
94}
95
96pub trait PrimeFieldRepr:
100 Sized
101 + Copy
102 + Clone
103 + Eq
104 + Ord
105 + Send
106 + Sync
107 + Default
108 + fmt::Debug
109 + fmt::Display
110 + 'static
111 + AsRef<[u64]>
112 + AsMut<[u64]>
113 + From<u64>
114 + zeroize::Zeroize
115{
116 fn sub_noborrow(&mut self, other: &Self);
118
119 fn add_nocarry(&mut self, other: &Self);
121
122 fn num_bits(&self) -> u32;
125
126 fn is_zero(&self) -> bool;
128
129 fn is_odd(&self) -> bool;
131
132 fn is_even(&self) -> bool;
134
135 fn div2(&mut self);
138
139 fn shr(&mut self, amt: u32);
141
142 fn mul2(&mut self);
145
146 fn shl(&mut self, amt: u32);
148
149 fn write_be<W: Write>(&self, mut writer: W) -> io::Result<()> {
151 use byteorder::{BigEndian, WriteBytesExt};
152
153 for digit in self.as_ref().iter().rev() {
154 writer.write_u64::<BigEndian>(*digit)?;
155 }
156
157 Ok(())
158 }
159
160 fn read_be<R: Read>(&mut self, mut reader: R) -> io::Result<()> {
162 use byteorder::{BigEndian, ReadBytesExt};
163
164 for digit in self.as_mut().iter_mut().rev() {
165 *digit = reader.read_u64::<BigEndian>()?;
166 }
167
168 Ok(())
169 }
170
171 fn write_le<W: Write>(&self, mut writer: W) -> io::Result<()> {
173 use byteorder::{LittleEndian, WriteBytesExt};
174
175 for digit in self.as_ref().iter() {
176 writer.write_u64::<LittleEndian>(*digit)?;
177 }
178
179 Ok(())
180 }
181
182 fn read_le<R: Read>(&mut self, mut reader: R) -> io::Result<()> {
184 use byteorder::{LittleEndian, ReadBytesExt};
185
186 for digit in self.as_mut().iter_mut() {
187 *digit = reader.read_u64::<LittleEndian>()?;
188 }
189
190 Ok(())
191 }
192}
193
194#[derive(Debug, PartialEq)]
195pub enum LegendreSymbol {
196 Zero = 0,
197 QuadraticResidue = 1,
198 QuadraticNonResidue = -1,
199}
200
201#[derive(Debug)]
204pub enum PrimeFieldDecodingError {
205 NotInField(String),
207}
208
209impl Error for PrimeFieldDecodingError {
210 fn description(&self) -> &str {
211 match *self {
212 PrimeFieldDecodingError::NotInField(..) => "not an element of the field",
213 }
214 }
215}
216
217impl fmt::Display for PrimeFieldDecodingError {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
219 match *self {
220 PrimeFieldDecodingError::NotInField(ref repr) => {
221 write!(f, "{} is not an element of the field", repr)
222 }
223 }
224 }
225}
226
227pub trait PrimeField: Field {
229 type Repr: PrimeFieldRepr + From<Self>;
232
233 fn from_str(s: &str) -> Option<Self> {
236 if s.is_empty() {
237 return None;
238 }
239
240 if s == "0" {
241 return Some(Self::zero());
242 }
243
244 let mut res = Self::zero();
245
246 let ten = Self::from_repr(Self::Repr::from(10)).unwrap();
247
248 let mut first_digit = true;
249
250 for c in s.chars() {
251 match c.to_digit(10) {
252 Some(c) => {
253 if first_digit {
254 if c == 0 {
255 return None;
256 }
257
258 first_digit = false;
259 }
260
261 res.mul_assign(&ten);
262 res.add_assign(&Self::from_repr(Self::Repr::from(u64::from(c))).unwrap());
263 }
264 None => {
265 return None;
266 }
267 }
268 }
269
270 Some(res)
271 }
272
273 fn from_repr(_: Self::Repr) -> Result<Self, PrimeFieldDecodingError>;
275
276 fn into_repr(&self) -> Self::Repr;
279
280 fn char() -> Self::Repr;
282
283 const NUM_BITS: u32;
285
286 const CAPACITY: u32;
288
289 fn multiplicative_generator() -> Self;
292
293 const S: u32;
295
296 fn root_of_unity() -> Self;
299}
300
301pub trait ScalarEngine: Sized + 'static + Clone {
305 type Fr: PrimeField + SqrtField;
307}
308
309#[derive(Debug)]
310pub struct BitIterator<E> {
311 t: E,
312 n: usize,
313}
314
315impl<E: AsRef<[u64]>> BitIterator<E> {
316 pub fn new(t: E) -> Self {
317 let n = t.as_ref().len() * 64;
318
319 BitIterator { t, n }
320 }
321}
322
323impl<E: AsRef<[u64]>> Iterator for BitIterator<E> {
324 type Item = bool;
325
326 fn next(&mut self) -> Option<bool> {
327 if self.n == 0 {
328 None
329 } else {
330 self.n -= 1;
331 let part = self.n / 64;
332 let bit = self.n - (64 * part);
333
334 Some(self.t.as_ref()[part] & (1 << bit) > 0)
335 }
336 }
337}
338
339#[test]
340fn test_bit_iterator() {
341 let mut a = BitIterator::new([0xa953d79b83f6ab59, 0x6dea2059e200bd39]);
342 let expected = "01101101111010100010000001011001111000100000000010111101001110011010100101010011110101111001101110000011111101101010101101011001";
343
344 for e in expected.chars() {
345 assert!(a.next().unwrap() == (e == '1'));
346 }
347
348 assert!(a.next().is_none());
349
350 let expected = "1010010101111110101010000101101011101000011101110101001000011001100100100011011010001011011011010001011011101100110100111011010010110001000011110100110001100110011101101000101100011100100100100100001010011101010111110011101011000011101000111011011101011001";
351
352 let mut a = BitIterator::new([
353 0x429d5f3ac3a3b759,
354 0xb10f4c66768b1c92,
355 0x92368b6d16ecd3b4,
356 0xa57ea85ae8775219,
357 ]);
358
359 for e in expected.chars() {
360 assert!(a.next().unwrap() == (e == '1'));
361 }
362
363 assert!(a.next().is_none());
364}
365
366pub use self::arith_impl::*;
367
368mod arith_impl {
369 #[inline(always)]
372 pub fn sbb(a: u64, b: u64, borrow: &mut u64) -> u64 {
373 let tmp = (1u128 << 64) + u128::from(a) - u128::from(b) - u128::from(*borrow);
374
375 *borrow = if tmp >> 64 == 0 { 1 } else { 0 };
376
377 tmp as u64
378 }
379
380 #[inline(always)]
383 pub fn adc(a: u64, b: u64, carry: &mut u64) -> u64 {
384 let tmp = u128::from(a) + u128::from(b) + u128::from(*carry);
385
386 *carry = (tmp >> 64) as u64;
387
388 tmp as u64
389 }
390
391 #[inline(always)]
394 pub fn mac_with_carry(a: u64, b: u64, c: u64, carry: &mut u64) -> u64 {
395 let tmp = (u128::from(a)) + u128::from(b) * u128::from(c) + u128::from(*carry);
396
397 *carry = (tmp >> 64) as u64;
398
399 tmp as u64
400 }
401}