witnet_bn/
lib.rs

1#![no_std]
2
3extern crate alloc;
4extern crate byteorder;
5#[macro_use]
6extern crate crunchy;
7extern crate rand;
8#[cfg(feature = "rustc-serialize")]
9extern crate rustc_serialize;
10#[macro_use]
11extern crate lazy_static;
12
13pub mod arith;
14mod fields;
15mod groups;
16
17use fields::FieldElement;
18use groups::{G1Params, G2Params, GroupElement, GroupParams};
19
20use alloc::vec::Vec;
21use core::ops::{Add, Mul, Neg, Sub};
22use rand::Rng;
23
24#[derive(Copy, Clone, Debug, PartialEq, Eq)]
25#[cfg_attr(feature = "rustc-serialize", derive(RustcDecodable, RustcEncodable))]
26#[repr(C)]
27pub struct Fr(fields::Fr);
28
29impl Fr {
30    pub fn zero() -> Self {
31        Fr(fields::Fr::zero())
32    }
33    pub fn one() -> Self {
34        Fr(fields::Fr::one())
35    }
36    pub fn random<R: Rng>(rng: &mut R) -> Self {
37        Fr(fields::Fr::random(rng))
38    }
39    pub fn pow(&self, exp: Fr) -> Self {
40        Fr(self.0.pow(exp.0))
41    }
42    pub fn from_str(s: &str) -> Option<Self> {
43        fields::Fr::from_str(s).map(|e| Fr(e))
44    }
45    pub fn inverse(&self) -> Option<Self> {
46        self.0.inverse().map(|e| Fr(e))
47    }
48    pub fn is_zero(&self) -> bool {
49        self.0.is_zero()
50    }
51    pub fn interpret(buf: &[u8; 64]) -> Fr {
52        Fr(fields::Fr::interpret(buf))
53    }
54    pub fn from_slice(slice: &[u8]) -> Result<Self, FieldError> {
55        arith::U256::from_slice(slice)
56            .map_err(|_| FieldError::InvalidSliceLength) // todo: maybe more sensful error handling
57            .map(|x| Fr::new_mul_factor(x))
58    }
59    pub fn to_big_endian(&self, slice: &mut [u8]) -> Result<(), FieldError> {
60        self.0
61            .raw()
62            .to_big_endian(slice)
63            .map_err(|_| FieldError::InvalidSliceLength)
64    }
65    pub fn new(val: arith::U256) -> Option<Self> {
66        fields::Fr::new(val).map(|x| Fr(x))
67    }
68    pub fn new_mul_factor(val: arith::U256) -> Self {
69        Fr(fields::Fr::new_mul_factor(val))
70    }
71    pub fn into_u256(self) -> arith::U256 {
72        (self.0).into()
73    }
74    pub fn set_bit(&mut self, bit: usize, to: bool) {
75        self.0.set_bit(bit, to);
76    }
77}
78
79impl Add<Fr> for Fr {
80    type Output = Fr;
81
82    fn add(self, other: Fr) -> Fr {
83        Fr(self.0 + other.0)
84    }
85}
86
87impl Sub<Fr> for Fr {
88    type Output = Fr;
89
90    fn sub(self, other: Fr) -> Fr {
91        Fr(self.0 - other.0)
92    }
93}
94
95impl Neg for Fr {
96    type Output = Fr;
97
98    fn neg(self) -> Fr {
99        Fr(-self.0)
100    }
101}
102
103impl Mul for Fr {
104    type Output = Fr;
105
106    fn mul(self, other: Fr) -> Fr {
107        Fr(self.0 * other.0)
108    }
109}
110
111#[derive(Debug)]
112pub enum FieldError {
113    InvalidSliceLength,
114    InvalidU512Encoding,
115    NotMember,
116}
117
118#[derive(Debug)]
119pub enum CurveError {
120    InvalidEncoding,
121    NotMember,
122    Field(FieldError),
123    ToAffineConversion,
124}
125
126impl From<FieldError> for CurveError {
127    fn from(fe: FieldError) -> Self {
128        CurveError::Field(fe)
129    }
130}
131
132pub use groups::Error as GroupError;
133
134#[derive(Copy, Clone, Debug, PartialEq, Eq)]
135#[cfg_attr(feature = "rustc-serialize", derive(RustcDecodable, RustcEncodable))]
136#[repr(C)]
137pub struct Fq(fields::Fq);
138
139impl Fq {
140    pub fn zero() -> Self {
141        Fq(fields::Fq::zero())
142    }
143    pub fn one() -> Self {
144        Fq(fields::Fq::one())
145    }
146    pub fn random<R: Rng>(rng: &mut R) -> Self {
147        Fq(fields::Fq::random(rng))
148    }
149    pub fn pow(&self, exp: Fq) -> Self {
150        Fq(self.0.pow(exp.0))
151    }
152    pub fn from_str(s: &str) -> Option<Self> {
153        fields::Fq::from_str(s).map(|e| Fq(e))
154    }
155    pub fn inverse(&self) -> Option<Self> {
156        self.0.inverse().map(|e| Fq(e))
157    }
158    pub fn is_zero(&self) -> bool {
159        self.0.is_zero()
160    }
161    pub fn interpret(buf: &[u8; 64]) -> Fq {
162        Fq(fields::Fq::interpret(buf))
163    }
164    pub fn from_slice(slice: &[u8]) -> Result<Self, FieldError> {
165        arith::U256::from_slice(slice)
166            .map_err(|_| FieldError::InvalidSliceLength) // todo: maybe more sensful error handling
167            .and_then(|x| fields::Fq::new(x).ok_or(FieldError::NotMember))
168            .map(|x| Fq(x))
169    }
170    pub fn to_big_endian(&self, slice: &mut [u8]) -> Result<(), FieldError> {
171        let mut a: arith::U256 = self.0.into();
172        // convert from Montgomery representation
173        a.mul(
174            &fields::Fq::one().raw(),
175            &fields::Fq::modulus(),
176            self.0.inv(),
177        );
178        a.to_big_endian(slice)
179            .map_err(|_| FieldError::InvalidSliceLength)
180    }
181    pub fn from_u256(u256: arith::U256) -> Result<Self, FieldError> {
182        Ok(Fq(fields::Fq::new(u256).ok_or(FieldError::NotMember)?))
183    }
184    pub fn into_u256(self) -> arith::U256 {
185        (self.0).into()
186    }
187    pub fn modulus() -> arith::U256 {
188        fields::Fq::modulus()
189    }
190
191    pub fn sqrt(&self) -> Option<Self> {
192        self.0.sqrt().map(Fq)
193    }
194}
195
196impl Add<Fq> for Fq {
197    type Output = Fq;
198
199    fn add(self, other: Fq) -> Fq {
200        Fq(self.0 + other.0)
201    }
202}
203
204impl Sub<Fq> for Fq {
205    type Output = Fq;
206
207    fn sub(self, other: Fq) -> Fq {
208        Fq(self.0 - other.0)
209    }
210}
211
212impl Neg for Fq {
213    type Output = Fq;
214
215    fn neg(self) -> Fq {
216        Fq(-self.0)
217    }
218}
219
220impl Mul for Fq {
221    type Output = Fq;
222
223    fn mul(self, other: Fq) -> Fq {
224        Fq(self.0 * other.0)
225    }
226}
227
228#[derive(Copy, Clone, Debug, PartialEq, Eq)]
229#[repr(C)]
230pub struct Fq2(fields::Fq2);
231
232impl Fq2 {
233    pub fn one() -> Fq2 {
234        Fq2(fields::Fq2::one())
235    }
236
237    pub fn i() -> Fq2 {
238        Fq2(fields::Fq2::i())
239    }
240
241    pub fn zero() -> Fq2 {
242        Fq2(fields::Fq2::zero())
243    }
244
245    /// Initalizes new F_q2(a + bi, a is real coeff, b is imaginary)
246    pub fn new(a: Fq, b: Fq) -> Fq2 {
247        Fq2(fields::Fq2::new(a.0, b.0))
248    }
249
250    pub fn is_zero(&self) -> bool {
251        self.0.is_zero()
252    }
253
254    pub fn pow(&self, exp: arith::U256) -> Self {
255        Fq2(self.0.pow(exp))
256    }
257
258    pub fn real(&self) -> Fq {
259        Fq(*self.0.real())
260    }
261
262    pub fn imaginary(&self) -> Fq {
263        Fq(*self.0.imaginary())
264    }
265
266    pub fn sqrt(&self) -> Option<Self> {
267        self.0.sqrt().map(Fq2)
268    }
269
270    pub fn from_slice(bytes: &[u8]) -> Result<Self, FieldError> {
271        let u512 = arith::U512::from_slice(bytes).map_err(|_| FieldError::InvalidU512Encoding)?;
272        let (res, c0) = u512.divrem(&Fq::modulus());
273        Ok(Fq2::new(
274            Fq::from_u256(c0).map_err(|_| FieldError::NotMember)?,
275            Fq::from_u256(res.ok_or(FieldError::NotMember)?).map_err(|_| FieldError::NotMember)?,
276        ))
277    }
278}
279
280impl Add<Fq2> for Fq2 {
281    type Output = Self;
282
283    fn add(self, other: Self) -> Self {
284        Fq2(self.0 + other.0)
285    }
286}
287
288impl Sub<Fq2> for Fq2 {
289    type Output = Self;
290
291    fn sub(self, other: Self) -> Self {
292        Fq2(self.0 - other.0)
293    }
294}
295
296impl Neg for Fq2 {
297    type Output = Self;
298
299    fn neg(self) -> Self {
300        Fq2(-self.0)
301    }
302}
303
304impl Mul for Fq2 {
305    type Output = Self;
306
307    fn mul(self, other: Self) -> Self {
308        Fq2(self.0 * other.0)
309    }
310}
311
312pub trait Group:
313    Send
314    + Sync
315    + Copy
316    + Clone
317    + PartialEq
318    + Eq
319    + Sized
320    + Add<Self, Output = Self>
321    + Sub<Self, Output = Self>
322    + Neg<Output = Self>
323    + Mul<Fr, Output = Self>
324{
325    fn zero() -> Self;
326    fn one() -> Self;
327    fn random<R: Rng>(rng: &mut R) -> Self;
328    fn is_zero(&self) -> bool;
329    fn normalize(&mut self);
330}
331
332#[derive(Copy, Clone, Debug, PartialEq, Eq)]
333#[cfg_attr(feature = "rustc-serialize", derive(RustcDecodable, RustcEncodable))]
334#[repr(C)]
335pub struct G1(groups::G1);
336
337impl G1 {
338    pub fn new(x: Fq, y: Fq, z: Fq) -> Self {
339        G1(groups::G1::new(x.0, y.0, z.0))
340    }
341
342    pub fn x(&self) -> Fq {
343        Fq(self.0.x().clone())
344    }
345
346    pub fn set_x(&mut self, x: Fq) {
347        *self.0.x_mut() = x.0
348    }
349
350    pub fn y(&self) -> Fq {
351        Fq(self.0.y().clone())
352    }
353
354    pub fn set_y(&mut self, y: Fq) {
355        *self.0.y_mut() = y.0
356    }
357
358    pub fn z(&self) -> Fq {
359        Fq(self.0.z().clone())
360    }
361
362    pub fn set_z(&mut self, z: Fq) {
363        *self.0.z_mut() = z.0
364    }
365
366    pub fn b() -> Fq {
367        Fq(G1Params::coeff_b())
368    }
369
370    pub fn from_compressed(bytes: &[u8]) -> Result<Self, CurveError> {
371        if bytes.len() != 33 {
372            return Err(CurveError::InvalidEncoding);
373        }
374
375        let sign = bytes[0];
376        let fq = Fq::from_slice(&bytes[1..])?;
377        let x = fq;
378        let y_squared = (fq * fq * fq) + Self::b();
379
380        let mut y = y_squared.sqrt().ok_or(CurveError::NotMember)?;
381
382        if sign == 2 && y.into_u256().get_bit(0).expect("bit 0 always exist; qed") {
383            y = y.neg();
384        } else if sign == 3 && !y.into_u256().get_bit(0).expect("bit 0 always exist; qed") {
385            y = y.neg();
386        } else if sign != 3 && sign != 2 {
387            return Err(CurveError::InvalidEncoding);
388        }
389        AffineG1::new(x, y)
390            .map_err(|_| CurveError::NotMember)
391            .map(Into::into)
392    }
393}
394
395impl Group for G1 {
396    fn zero() -> Self {
397        G1(groups::G1::zero())
398    }
399    fn one() -> Self {
400        G1(groups::G1::one())
401    }
402    fn random<R: Rng>(rng: &mut R) -> Self {
403        G1(groups::G1::random(rng))
404    }
405    fn is_zero(&self) -> bool {
406        self.0.is_zero()
407    }
408    fn normalize(&mut self) {
409        let new = match self.0.to_affine() {
410            Some(a) => a,
411            None => return,
412        };
413
414        self.0 = new.to_jacobian();
415    }
416}
417
418impl Add<G1> for G1 {
419    type Output = G1;
420
421    fn add(self, other: G1) -> G1 {
422        G1(self.0 + other.0)
423    }
424}
425
426impl Sub<G1> for G1 {
427    type Output = G1;
428
429    fn sub(self, other: G1) -> G1 {
430        G1(self.0 - other.0)
431    }
432}
433
434impl Neg for G1 {
435    type Output = G1;
436
437    fn neg(self) -> G1 {
438        G1(-self.0)
439    }
440}
441
442impl Mul<Fr> for G1 {
443    type Output = G1;
444
445    fn mul(self, other: Fr) -> G1 {
446        G1(self.0 * other.0)
447    }
448}
449
450#[derive(Copy, Clone, Debug, PartialEq, Eq)]
451#[cfg_attr(feature = "rustc-serialize", derive(RustcDecodable, RustcEncodable))]
452#[repr(C)]
453pub struct AffineG1(groups::AffineG1);
454
455impl AffineG1 {
456    pub fn new(x: Fq, y: Fq) -> Result<Self, GroupError> {
457        Ok(AffineG1(groups::AffineG1::new(x.0, y.0)?))
458    }
459
460    pub fn x(&self) -> Fq {
461        Fq(self.0.x().clone())
462    }
463
464    pub fn set_x(&mut self, x: Fq) {
465        *self.0.x_mut() = x.0
466    }
467
468    pub fn y(&self) -> Fq {
469        Fq(self.0.y().clone())
470    }
471
472    pub fn set_y(&mut self, y: Fq) {
473        *self.0.y_mut() = y.0
474    }
475
476    pub fn from_jacobian(g1: G1) -> Option<Self> {
477        g1.0.to_affine().map(|x| AffineG1(x))
478    }
479}
480
481impl From<AffineG1> for G1 {
482    fn from(affine: AffineG1) -> Self {
483        G1(affine.0.to_jacobian())
484    }
485}
486
487#[derive(Copy, Clone, Debug, PartialEq, Eq)]
488#[cfg_attr(feature = "rustc-serialize", derive(RustcDecodable, RustcEncodable))]
489#[repr(C)]
490pub struct G2(groups::G2);
491
492impl G2 {
493    pub fn new(x: Fq2, y: Fq2, z: Fq2) -> Self {
494        G2(groups::G2::new(x.0, y.0, z.0))
495    }
496
497    pub fn x(&self) -> Fq2 {
498        Fq2(self.0.x().clone())
499    }
500
501    pub fn set_x(&mut self, x: Fq2) {
502        *self.0.x_mut() = x.0
503    }
504
505    pub fn y(&self) -> Fq2 {
506        Fq2(self.0.y().clone())
507    }
508
509    pub fn set_y(&mut self, y: Fq2) {
510        *self.0.y_mut() = y.0
511    }
512
513    pub fn z(&self) -> Fq2 {
514        Fq2(self.0.z().clone())
515    }
516
517    pub fn set_z(&mut self, z: Fq2) {
518        *self.0.z_mut() = z.0
519    }
520
521    pub fn b() -> Fq2 {
522        Fq2(G2Params::coeff_b())
523    }
524
525    pub fn from_compressed(bytes: &[u8]) -> Result<Self, CurveError> {
526        if bytes.len() != 65 {
527            return Err(CurveError::InvalidEncoding);
528        }
529
530        let sign = bytes[0];
531        let x = Fq2::from_slice(&bytes[1..])?;
532
533        let y_squared = (x * x * x) + G2::b();
534        let y = y_squared.sqrt().ok_or(CurveError::NotMember)?;
535        let y_neg = -y;
536
537        let y_gt = y.0.to_u512() > y_neg.0.to_u512();
538
539        let e_y = if sign == 10 {
540            if y_gt { y_neg } else { y }
541        } else if sign == 11 {
542            if y_gt { y } else { y_neg }
543        } else {
544            return Err(CurveError::InvalidEncoding);
545        };
546
547        AffineG2::new(x, e_y)
548            .map_err(|_| CurveError::NotMember)
549            .map(Into::into)
550    }
551}
552
553impl Group for G2 {
554    fn zero() -> Self {
555        G2(groups::G2::zero())
556    }
557    fn one() -> Self {
558        G2(groups::G2::one())
559    }
560    fn random<R: Rng>(rng: &mut R) -> Self {
561        G2(groups::G2::random(rng))
562    }
563    fn is_zero(&self) -> bool {
564        self.0.is_zero()
565    }
566    fn normalize(&mut self) {
567        let new = match self.0.to_affine() {
568            Some(a) => a,
569            None => return,
570        };
571
572        self.0 = new.to_jacobian();
573    }
574}
575
576impl Add<G2> for G2 {
577    type Output = G2;
578
579    fn add(self, other: G2) -> G2 {
580        G2(self.0 + other.0)
581    }
582}
583
584impl Sub<G2> for G2 {
585    type Output = G2;
586
587    fn sub(self, other: G2) -> G2 {
588        G2(self.0 - other.0)
589    }
590}
591
592impl Neg for G2 {
593    type Output = G2;
594
595    fn neg(self) -> G2 {
596        G2(-self.0)
597    }
598}
599
600impl Mul<Fr> for G2 {
601    type Output = G2;
602
603    fn mul(self, other: Fr) -> G2 {
604        G2(self.0 * other.0)
605    }
606}
607
608#[derive(Copy, Clone, PartialEq, Eq)]
609#[repr(C)]
610pub struct Gt(fields::Fq12);
611
612impl Gt {
613    pub fn one() -> Self {
614        Gt(fields::Fq12::one())
615    }
616    pub fn pow(&self, exp: Fr) -> Self {
617        Gt(self.0.pow(exp.0))
618    }
619    pub fn inverse(&self) -> Option<Self> {
620        self.0.inverse().map(Gt)
621    }
622    pub fn final_exponentiation(&self) -> Option<Self> {
623        self.0.final_exponentiation().map(Gt)
624    }
625}
626
627impl Mul<Gt> for Gt {
628    type Output = Gt;
629
630    fn mul(self, other: Gt) -> Gt {
631        Gt(self.0 * other.0)
632    }
633}
634
635pub fn pairing(p: G1, q: G2) -> Gt {
636    Gt(groups::pairing(&p.0, &q.0))
637}
638
639pub fn pairing_batch(pairs: &[(G1, G2)]) -> Gt {
640    let mut ps: Vec<groups::G1> = Vec::new();
641    let mut qs: Vec<groups::G2> = Vec::new();
642    for (p, q) in pairs {
643        ps.push(p.0);
644        qs.push(q.0);
645    }
646    Gt(groups::pairing_batch(&ps, &qs))
647}
648
649pub fn miller_loop_batch(pairs: &[(G2, G1)]) -> Result<Gt, CurveError> {
650    let mut ps: Vec<groups::G2Precomp> = Vec::new();
651    let mut qs: Vec<groups::AffineG<groups::G1Params>> = Vec::new();
652    for (p, q) in pairs {
653        ps.push(
654            p.0.to_affine()
655                .ok_or(CurveError::ToAffineConversion)?
656                .precompute(),
657        );
658        qs.push(q.0.to_affine().ok_or(CurveError::ToAffineConversion)?);
659    }
660    Ok(Gt(groups::miller_loop_batch(&ps, &qs)))
661}
662
663#[derive(Copy, Clone, PartialEq, Eq)]
664#[cfg_attr(feature = "rustc-serialize", derive(RustcDecodable, RustcEncodable))]
665#[repr(C)]
666pub struct AffineG2(groups::AffineG2);
667
668impl AffineG2 {
669    pub fn new(x: Fq2, y: Fq2) -> Result<Self, GroupError> {
670        Ok(AffineG2(groups::AffineG2::new(x.0, y.0)?))
671    }
672
673    pub fn x(&self) -> Fq2 {
674        Fq2(self.0.x().clone())
675    }
676
677    pub fn set_x(&mut self, x: Fq2) {
678        *self.0.x_mut() = x.0
679    }
680
681    pub fn y(&self) -> Fq2 {
682        Fq2(self.0.y().clone())
683    }
684
685    pub fn set_y(&mut self, y: Fq2) {
686        *self.0.y_mut() = y.0
687    }
688
689    pub fn from_jacobian(g2: G2) -> Option<Self> {
690        g2.0.to_affine().map(|x| AffineG2(x))
691    }
692}
693
694impl From<AffineG2> for G2 {
695    fn from(affine: AffineG2) -> Self {
696        G2(affine.0.to_jacobian())
697    }
698}
699
700#[cfg(test)]
701mod tests {
702    extern crate rustc_hex as hex;
703    use super::{Fq, Fq2, G1, G2};
704    use alloc::vec::Vec;
705
706    fn hex(s: &'static str) -> Vec<u8> {
707        use self::hex::FromHex;
708        s.from_hex().unwrap()
709    }
710
711    #[test]
712    fn g1_from_compressed() {
713        let g1 = G1::from_compressed(&hex(
714            "0230644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd46",
715        ))
716        .expect("Invalid g1 decompress result");
717        assert_eq!(
718            g1.x(),
719            Fq::from_str(
720                "21888242871839275222246405745257275088696311157297823662689037894645226208582"
721            )
722            .unwrap()
723        );
724        assert_eq!(
725            g1.y(),
726            Fq::from_str(
727                "3969792565221544645472939191694882283483352126195956956354061729942568608776"
728            )
729            .unwrap()
730        );
731        assert_eq!(g1.z(), Fq::one());
732    }
733
734    #[test]
735    fn g2_from_compressed() {
736        let g2 = G2::from_compressed(
737            &hex("0a023aed31b5a9e486366ea9988b05dba469c6206e58361d9c065bbea7d928204a761efc6e4fa08ed227650134b52c7f7dd0463963e8a4bf21f4899fe5da7f984a")
738        ).expect("Valid g2 point hex encoding");
739
740        assert_eq!(
741            g2.x(),
742            Fq2::new(
743                Fq::from_str(
744                    "5923585509243758863255447226263146374209884951848029582715967108651637186684"
745                )
746                .unwrap(),
747                Fq::from_str(
748                    "5336385337059958111259504403491065820971993066694750945459110579338490853570"
749                )
750                .unwrap(),
751            )
752        );
753
754        assert_eq!(
755            g2.y(),
756            Fq2::new(
757                Fq::from_str(
758                    "10374495865873200088116930399159835104695426846400310764827677226300185211748"
759                )
760                .unwrap(),
761                Fq::from_str(
762                    "5256529835065685814318509161957442385362539991735248614869838648137856366932"
763                )
764                .unwrap(),
765            )
766        );
767
768        // 0b prefix is point reflection on the curve
769        let g2 = -G2::from_compressed(
770            &hex("0b023aed31b5a9e486366ea9988b05dba469c6206e58361d9c065bbea7d928204a761efc6e4fa08ed227650134b52c7f7dd0463963e8a4bf21f4899fe5da7f984a")
771        ).expect("Valid g2 point hex encoding");
772
773        assert_eq!(
774            g2.x(),
775            Fq2::new(
776                Fq::from_str(
777                    "5923585509243758863255447226263146374209884951848029582715967108651637186684"
778                )
779                .unwrap(),
780                Fq::from_str(
781                    "5336385337059958111259504403491065820971993066694750945459110579338490853570"
782                )
783                .unwrap(),
784            )
785        );
786
787        assert_eq!(
788            g2.y(),
789            Fq2::new(
790                Fq::from_str(
791                    "10374495865873200088116930399159835104695426846400310764827677226300185211748"
792                )
793                .unwrap(),
794                Fq::from_str(
795                    "5256529835065685814318509161957442385362539991735248614869838648137856366932"
796                )
797                .unwrap(),
798            )
799        );
800
801        // valid point but invalid sign prefix
802        assert!(
803            G2::from_compressed(
804                &hex("0c023aed31b5a9e486366ea9988b05dba469c6206e58361d9c065bbea7d928204a761efc6e4fa08ed227650134b52c7f7dd0463963e8a4bf21f4899fe5da7f984a")
805            ).is_err()
806        );
807    }
808}