zksync_ff/
lib.rs

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
23/// This trait represents an element of a field.
24pub trait Field: Sized + Eq + Copy + Clone + Send + Sync + fmt::Debug + fmt::Display + 'static + rand::Rand + hash::Hash + Default + serde::Serialize + serde::de::DeserializeOwned {
25    /// Returns the zero element of the field, the additive identity.
26    fn zero() -> Self;
27
28    /// Returns the one element of the field, the multiplicative identity.
29    fn one() -> Self;
30
31    /// Returns true iff this element is zero.
32    fn is_zero(&self) -> bool;
33
34    /// Squares this element.
35    fn square(&mut self);
36
37    /// Doubles this element.
38    fn double(&mut self);
39
40    /// Negates this element.
41    fn negate(&mut self);
42
43    /// Adds another element to this element.
44    fn add_assign(&mut self, other: &Self);
45
46    /// Subtracts another element from this element.
47    fn sub_assign(&mut self, other: &Self);
48
49    /// Multiplies another element by this element.
50    fn mul_assign(&mut self, other: &Self);
51
52    /// Computes the multiplicative inverse of this element, if nonzero.
53    fn inverse(&self) -> Option<Self>;
54
55    /// Exponentiates this element by a power of the base prime modulus via
56    /// the Frobenius automorphism.
57    fn frobenius_map(&mut self, power: usize);
58
59    /// Exponentiates this element by a number represented with `u64` limbs,
60    /// least significant digit first.
61    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
82/// This trait represents an element of a field that has a square root operation described for it.
83pub trait SqrtField: Field {
84    /// Returns the Legendre symbol of the field element.
85    fn legendre(&self) -> LegendreSymbol;
86
87    /// Returns the square root of the field element, if it is
88    /// quadratic residue.
89    fn sqrt(&self) -> Option<Self>;
90}
91
92/// This trait represents a wrapper around a biginteger which can encode any element of a particular
93/// prime field. It is a smart wrapper around a sequence of `u64` limbs, least-significant digit
94/// first.
95pub 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    /// Subtract another represetation from this one.
116    fn sub_noborrow(&mut self, other: &Self);
117
118    /// Add another representation to this one.
119    fn add_nocarry(&mut self, other: &Self);
120
121    /// Compute the number of bits needed to encode this number. Always a
122    /// multiple of 64.
123    fn num_bits(&self) -> u32;
124
125    /// Returns true iff this number is zero.
126    fn is_zero(&self) -> bool;
127
128    /// Returns true iff this number is odd.
129    fn is_odd(&self) -> bool;
130
131    /// Returns true iff this number is even.
132    fn is_even(&self) -> bool;
133
134    /// Performs a rightwise bitshift of this number, effectively dividing
135    /// it by 2.
136    fn div2(&mut self);
137
138    /// Performs a rightwise bitshift of this number by some amount.
139    fn shr(&mut self, amt: u32);
140
141    /// Performs a leftwise bitshift of this number, effectively multiplying
142    /// it by 2. Overflow is ignored.
143    fn mul2(&mut self);
144
145    /// Performs a leftwise bitshift of this number by some amount.
146    fn shl(&mut self, amt: u32);
147
148    /// Writes this `PrimeFieldRepr` as a big endian integer.
149    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    /// Reads a big endian integer into this representation.
160    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    /// Writes this `PrimeFieldRepr` as a little endian integer.
171    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    /// Reads a little endian integer into this representation.
182    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/// An error that may occur when trying to interpret a `PrimeFieldRepr` as a
201/// `PrimeField` element.
202#[derive(Debug)]
203pub enum PrimeFieldDecodingError {
204    /// The encoded value is not in the field
205    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
226/// This represents an element of a prime field.
227pub trait PrimeField: Field {
228    /// The prime field can be converted back and forth into this biginteger
229    /// representation.
230    type Repr: PrimeFieldRepr + From<Self>;
231
232    /// Interpret a string of numbers as a (congruent) prime field element.
233    /// Does not accept unnecessary leading zeroes or a blank string.
234    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    /// Convert this prime field element into a biginteger representation.
273    fn from_repr(repr: Self::Repr) -> Result<Self, PrimeFieldDecodingError>;
274
275    /// Creates an element from raw representation in Montgommery form.
276    fn from_raw_repr(repr: Self::Repr) -> Result<Self, PrimeFieldDecodingError>;
277
278    /// Convert a biginteger representation into a prime field element, if
279    /// the number is an element of the field.
280    fn into_repr(&self) -> Self::Repr;
281
282    /// Expose Montgommery represendation.
283    fn into_raw_repr(&self) -> Self::Repr;
284
285    /// Returns the field characteristic; the modulus.
286    fn char() -> Self::Repr;
287
288    /// How many bits are needed to represent an element of this field.
289    const NUM_BITS: u32;
290
291    /// How many bits of information can be reliably stored in the field element.
292    const CAPACITY: u32;
293
294    /// Returns the multiplicative generator of `char()` - 1 order. This element
295    /// must also be quadratic nonresidue.
296    fn multiplicative_generator() -> Self;
297
298    /// 2^s * t = `char()` - 1 with t odd.
299    const S: u32;
300
301    /// Returns the 2^s root of unity computed by exponentiating the `multiplicative_generator()`
302    /// by t.
303    fn root_of_unity() -> Self;
304}
305
306/// An "engine" is a collection of types (fields, elliptic curve groups, etc.)
307/// with well-defined relationships. Specific relationships (for example, a
308/// pairing-friendly curve) can be defined in a subtrait.
309pub trait ScalarEngine: Sized + 'static + Clone + Copy + Send + Sync + fmt::Debug {
310    /// This is the scalar field of the engine's groups.
311    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    /// Calculate a - b - borrow, returning the result and modifying
398    /// the borrow value.
399    #[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    /// Calculate a + b + carry, returning the sum and modifying the
411    /// carry value.
412    #[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    /// Calculate a + (b * c) + carry, returning the least significant digit
424    /// and setting carry to the most significant digit.
425    #[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        // multiply
467        let tmp = (b as u128) * (c as u128);
468        // doulbe
469        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        // add
475        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        // multiply
483        let tmp = (b as u128) * (c as u128);
484        // doulbe
485        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        // add
491        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        // multiply
499        let tmp = (b as u128) * (c as u128);
500        // doulbe
501        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        // add
506        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        // multiply
514        let tmp = (b as u128) * (c as u128);
515        // doulbe
516        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        // add
522        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        // multiply
530        let tmp = (b as u128) * (c as u128);
531        // doulbe
532        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        // add
537        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        // multiply
545        let tmp = (b as u128) * (c as u128);
546        // doulbe
547        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        // add
553        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        // multiply
561        let tmp = (b as u128) * (c as u128);
562        // doulbe
563        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        // add
568        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}