arnaucube
arnaucube/babyjubjub-arkPublic Self-hosted repository
babyjubjub-ark/src/lib.rs
src/lib.rsRaw
  1extern crate rand;
  2#[macro_use]
  3extern crate ff;
  4use ff::*;
  5
  6#[derive(PrimeField)]
  7#[PrimeFieldModulus = "21888242871839275222246405745257275088548364400416034343698204186575808495617"]
  8#[PrimeFieldGenerator = "7"]
  9pub struct Fr(FrRepr);
 10
 11#[macro_use]
 12extern crate arrayref;
 13extern crate generic_array;
 14extern crate mimc_rs;
 15extern crate num;
 16extern crate num_bigint;
 17extern crate num_traits;
 18
 19use rand::Rng;
 20
 21use blake2::{Blake2b, Digest};
 22use mimc_rs::Mimc7;
 23use poseidon_rs::Poseidon;
 24use std::cmp::min;
 25
 26use num_bigint::{BigInt, RandBigInt, RandomBits, Sign, ToBigInt};
 27use num_traits::{One, Zero};
 28
 29use generic_array::GenericArray;
 30
 31pub mod utils;
 32
 33#[macro_use]
 34extern crate lazy_static;
 35
 36lazy_static! {
 37    static ref D: Fr = Fr::from_str("168696").unwrap();
 38    static ref D_big: BigInt = BigInt::parse_bytes(b"168696", 10).unwrap();
 39    static ref A: Fr = Fr::from_str("168700").unwrap();
 40    static ref A_big: BigInt = BigInt::parse_bytes(b"168700", 10).unwrap();
 41    pub static ref Q: BigInt = BigInt::parse_bytes(
 42        b"21888242871839275222246405745257275088548364400416034343698204186575808495617",10
 43    )
 44    .unwrap();
 45    // pub static ref Q: Fr = Fr::from_str(
 46    //     "21888242871839275222246405745257275088548364400416034343698204186575808495617"
 47    // )
 48    // .unwrap();
 49    static ref B8: Point = Point {
 50        x: Fr::from_str(
 51            "5299619240641551281634865583518297030282874472190772894086521144482721001553",
 52        )
 53        .unwrap(),
 54        y: Fr::from_str(
 55            "16950150798460657717958625567821834550301663161624707787222815936182638968203",
 56        )
 57        .unwrap(),
 58            z: Fr::one(),
 59    };
 60    static ref ORDER: Fr = Fr::from_str(
 61        "21888242871839275222246405745257275088614511777268538073601725287587578984328",
 62    )
 63    .unwrap();
 64    // SUBORDER = ORDER >> 3
 65    static ref SUBORDER: Fr = Fr::from_str(
 66        "i2736030358979909402780800718157159386076813972158567259200215660948447373041",
 67    )
 68    .unwrap();
 69}
 70
 71pub struct PointAffine {
 72    pub x: Fr,
 73    pub y: Fr,
 74}
 75
 76#[derive(Clone, Debug)]
 77pub struct Point {
 78    pub x: Fr,
 79    pub y: Fr,
 80    pub z: Fr,
 81}
 82
 83impl Point {
 84    pub fn affine(&self) -> PointAffine {
 85        if self.z.is_zero() {
 86            return PointAffine {
 87                x: Fr::zero(),
 88                y: Fr::zero(),
 89            };
 90        }
 91
 92        let mut zinv = self.z.inverse().unwrap();
 93        let mut x = self.x;
 94        x.mul_assign(&zinv);
 95        let mut y = self.y;
 96        y.mul_assign(&zinv);
 97
 98        PointAffine {
 99            x: x.clone(),
100            y: y.clone(),
101        }
102    }
103    pub fn from_affine(p: PointAffine) -> Point {
104        Point {
105            x: p.x.clone(),
106            y: p.y.clone(),
107            z: Fr::one(),
108        }
109    }
110
111    pub fn add(&self, q: &Point) -> Result<Point, String> {
112        // add-2008-bbjlp https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp
113        let mut a = self.z;
114        a.mul_assign(&q.z);
115        let mut b = a;
116        b.square();
117        let mut c = self.x;
118        c.mul_assign(&q.x);
119        let mut d = self.y;
120        d.mul_assign(&q.y);
121        let mut e = D.clone();
122        e.mul_assign(&c);
123        e.mul_assign(&d);
124        let mut f = b;
125        f.sub_assign(&e);
126        let mut g = b;
127        g.add_assign(&e);
128        let mut x1y1 = self.x;
129        x1y1.add_assign(&self.y);
130        let mut x2y2 = q.x;
131        x2y2.add_assign(&q.y);
132        let mut aux = x1y1;
133        aux.mul_assign(&x2y2);
134        aux.sub_assign(&c);
135        aux.sub_assign(&d);
136        let mut x3 = a;
137        x3.mul_assign(&f);
138        x3.mul_assign(&aux);
139        let mut ac = A.clone();
140        ac.mul_assign(&c);
141        let mut dac = d;
142        dac.sub_assign(&ac);
143        let mut y3 = a;
144        y3.mul_assign(&g);
145        y3.mul_assign(&dac);
146        let mut z3 = f;
147        z3.mul_assign(&g);
148
149        Ok(Point {
150            x: x3.clone(),
151            y: y3.clone(),
152            z: z3.clone(),
153        })
154    }
155
156    pub fn mul_scalar(&self, n: &BigInt) -> Result<Point, String> {
157        let mut r: Point = Point {
158            x: Fr::zero(),
159            y: Fr::one(),
160            z: Fr::one(),
161        };
162        let mut exp: Point = self.clone();
163        let (_, b) = n.to_bytes_le();
164        for i in 0..n.bits() {
165            if test_bit(&b, i) {
166                r = r.add(&exp)?;
167            }
168            exp = exp.add(&exp)?;
169        }
170        Ok(r)
171    }
172
173    pub fn compress(&self) -> [u8; 32] {
174        let p = &self.affine();
175        let mut r: [u8; 32] = [0; 32];
176        let x_big = BigInt::parse_bytes(to_hex(&p.x).as_bytes(), 16).unwrap();
177        let y_big = BigInt::parse_bytes(to_hex(&p.y).as_bytes(), 16).unwrap();
178        let (_, y_bytes) = y_big.to_bytes_le();
179        let len = min(y_bytes.len(), r.len());
180        r[..len].copy_from_slice(&y_bytes[..len]);
181        if &x_big > &(&Q.clone() >> 1) {
182            r[31] = r[31] | 0x80;
183        }
184        r
185    }
186
187    pub fn equals(&self, p: Point) -> bool {
188        if self.x == p.x && self.y == p.y {
189            return true;
190        }
191        false
192    }
193}
194
195pub fn test_bit(b: &Vec<u8>, i: usize) -> bool {
196    return b[i / 8] & (1 << (i % 8)) != 0;
197}
198
199pub fn decompress_point(bb: [u8; 32]) -> Result<Point, String> {
200    // https://tools.ietf.org/html/rfc8032#section-5.2.3
201    let mut sign: bool = false;
202    let mut b = bb.clone();
203    if b[31] & 0x80 != 0x00 {
204        sign = true;
205        b[31] = b[31] & 0x7F;
206    }
207    let y: BigInt = BigInt::from_bytes_le(Sign::Plus, &b[..]);
208    if y >= Q.clone() {
209        return Err("y outside the Finite Field over R".to_string());
210    }
211    let one: BigInt = One::one();
212
213    // x^2 = (1 - y^2) / (a - d * y^2) (mod p)
214    let den = utils::modinv(
215        &utils::modulus(
216            &(&A_big.clone() - utils::modulus(&(&D_big.clone() * (&y * &y)), &Q)),
217            &Q,
218        ),
219        &Q,
220    )?;
221    let mut x: BigInt = utils::modulus(&((one - utils::modulus(&(&y * &y), &Q)) * den), &Q);
222    x = utils::modsqrt(&x, &Q)?;
223
224    if sign && !(&x > &(&Q.clone() >> 1)) || (!sign && (&x > &(&Q.clone() >> 1))) {
225        x = x * -1.to_bigint().unwrap();
226    }
227    x = utils::modulus(&x, &Q);
228    let x_fr: Fr = Fr::from_str(&x.to_string()).unwrap();
229    let y_fr: Fr = Fr::from_str(&y.to_string()).unwrap();
230    Ok(Point::from_affine(PointAffine { x: x_fr, y: y_fr }))
231}
232//
233// #[derive(Debug, Clone)]
234// pub struct Signature {
235//     r_b8: Point,
236//     s: BigInt,
237// }
238//
239// impl Signature {
240//     pub fn compress(&self) -> [u8; 64] {
241//         let mut b: Vec<u8> = Vec::new();
242//         b.append(&mut self.r_b8.compress().to_vec());
243//         let (_, s_bytes) = self.s.to_bytes_le();
244//         let mut s_32bytes: [u8; 32] = [0; 32];
245//         let len = min(s_bytes.len(), s_32bytes.len());
246//         s_32bytes[..len].copy_from_slice(&s_bytes[..len]);
247//         b.append(&mut s_32bytes.to_vec());
248//         let mut r: [u8; 64] = [0; 64];
249//         r[..].copy_from_slice(&b[..]);
250//         r
251//     }
252// }
253//
254// pub fn decompress_signature(b: &[u8; 64]) -> Result<Signature, String> {
255//     let r_b8_bytes: [u8; 32] = *array_ref!(b[..32], 0, 32);
256//     let s: BigInt = BigInt::from_bytes_le(Sign::Plus, &b[32..]);
257//     let r_b8 = decompress_point(r_b8_bytes);
258//     match r_b8 {
259//         Result::Err(err) => return Err(err.to_string()),
260//         Result::Ok(res) => Ok(Signature {
261//             r_b8: res.clone(),
262//             s: s,
263//         }),
264//     }
265// }
266//
267pub struct PrivateKey {
268    key: BigInt,
269}
270
271impl PrivateKey {
272    pub fn public(&self) -> Result<Point, String> {
273        // https://tools.ietf.org/html/rfc8032#section-5.1.5
274        let pk = B8.mul_scalar(&self.key)?;
275        Ok(pk.clone())
276    }
277
278    //     pub fn sign_mimc(&self, msg: BigInt) -> Result<Signature, String> {
279    //         // https://tools.ietf.org/html/rfc8032#section-5.1.6
280    //         let mut hasher = Blake2b::new();
281    //         let (_, sk_bytes) = self.key.to_bytes_be();
282    //         hasher.input(sk_bytes);
283    //         let mut h = hasher.result(); // h: hash(sk)
284    //                                      // s: h[32:64]
285    //         let s = GenericArray::<u8, generic_array::typenum::U32>::from_mut_slice(&mut h[32..64]);
286    //         let (_, msg_bytes) = msg.to_bytes_be();
287    //         let r_bytes = utils::concatenate_arrays(s, &msg_bytes);
288    //         let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]);
289    //         r = utils::modulus(&r, &SUBORDER);
290    //         let r8: Point = B8.mul_scalar(&r)?;
291    //         let a = &self.public()?;
292    //
293    //         let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg];
294    //         let mimc7 = Mimc7::new();
295    //         let hm = mimc7.hash(hm_input)?;
296    //
297    //         let mut s = &self.key << 3;
298    //         s = hm * s;
299    //         s = r + s;
300    //         s = s % &SUBORDER.clone();
301    //
302    //         Ok(Signature {
303    //             r_b8: r8.clone(),
304    //             s: s,
305    //         })
306    //     }
307    // pub fn sign_poseidon(&self, msg: BigInt) -> Result<Signature, String> {
308    //     // https://tools.ietf.org/html/rfc8032#section-5.1.6
309    //     let mut hasher = Blake2b::new();
310    //     let (_, sk_bytes) = self.key.to_bytes_be();
311    //     hasher.input(sk_bytes);
312    //     let mut h = hasher.result(); // h: hash(sk)
313    //                                  // s: h[32:64]
314    //     let s = GenericArray::<u8, generic_array::typenum::U32>::from_mut_slice(&mut h[32..64]);
315    //     let (_, msg_bytes) = msg.to_bytes_be();
316    //     let r_bytes = utils::concatenate_arrays(s, &msg_bytes);
317    //     let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]);
318    //     r = utils::modulus(&r, &SUBORDER);
319    //     let r8: Point = B8.mul_scalar(&r)?;
320    //     let a = &self.public()?;
321    //
322    //     let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg];
323    //     let poseidon = Poseidon::new();
324    //     let hm = poseidon.hash(hm_input)?;
325    //
326    //     let mut s = &self.key << 3;
327    //     s = hm * s;
328    //     s = r + s;
329    //     s = s % &SUBORDER.clone();
330    //
331    //     Ok(Signature {
332    //         r_b8: r8.clone(),
333    //         s: s,
334    //     })
335    // }
336
337    //     pub fn sign_schnorr(&self, m: Vec<u8>) -> Result<(Point, BigInt), String> {
338    //         // random r
339    //         let mut rng = rand::thread_rng();
340    //         let k = rng.gen_biguint(1024).to_bigint().unwrap();
341    //
342    //         // r = k·G
343    //         let r = B8.mul_scalar(&k)?;
344    //
345    //         // h = H(x, r, m)
346    //         let pk = &self.public()?;
347    //         let h = schnorr_hash(&pk, m, &r)?;
348    //
349    //         // s= k+x·h
350    //         let s = k + &self.key * &h;
351    //         Ok((r, s))
352    //     }
353}
354
355// pub fn schnorr_hash(pk: &Point, m: Vec<u8>, c: &Point) -> Result<BigInt, String> {
356//     let b: &mut Vec<u8> = &mut Vec::new();
357//
358//     // other option could be to do it without compressing the points, and concatenating x|y
359//     b.append(&mut pk.compress().to_vec());
360//     b.append(&mut c.compress().to_vec());
361//     b.append(&mut m.clone());
362//
363//     let poseidon = Poseidon::new();
364//     let h = poseidon.hash_bytes(b.to_vec())?;
365//     println!("h {:?}", h.to_string());
366//     Ok(h)
367// }
368//
369// pub fn verify_schnorr(pk: Point, m: Vec<u8>, r: Point, s: BigInt) -> Result<bool, String> {
370//     // sG = s·G
371//     let sg = B8.mul_scalar(&s)?;
372//
373//     // r + h · x
374//     let h = schnorr_hash(&pk, m, &r)?;
375//     let pk_h = pk.mul_scalar(&h)?;
376//     let right = r.add(&pk_h)?;
377//
378//     Ok(sg.equals(right))
379// }
380
381// pub fn new_key() -> PrivateKey {
382//     // https://tools.ietf.org/html/rfc8032#section-5.1.5
383//     let mut rng = rand::thread_rng();
384//     let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap();
385//
386//     let mut hasher = Blake2b::new();
387//     let (_, sk_raw_bytes) = sk_raw.to_bytes_be();
388//     hasher.input(sk_raw_bytes);
389//     let mut h = hasher.result();
390//
391//     h[0] = h[0] & 0xF8;
392//     h[31] = h[31] & 0x7F;
393//     h[31] = h[31] | 0x40;
394//
395//     let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]);
396//
397//     PrivateKey { key: sk }
398// }
399
400// pub fn verify_mimc(pk: Point, sig: Signature, msg: BigInt) -> bool {
401//     let hm_input = vec![
402//         sig.r_b8.x.clone(),
403//         sig.r_b8.y.clone(),
404//         pk.x.clone(),
405//         pk.y.clone(),
406//         msg,
407//     ];
408//     let mimc7 = Mimc7::new();
409//     let hm = match mimc7.hash(hm_input) {
410//         Result::Err(_) => return false,
411//         Result::Ok(hm) => hm,
412//     };
413//     let l = match B8.mul_scalar(&sig.s) {
414//         Result::Err(_) => return false,
415//         Result::Ok(l) => l,
416//     };
417//     let r = match sig
418//         .r_b8
419//         .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap())
420//     {
421//         Result::Err(_) => return false,
422//         Result::Ok(r) => r,
423//     };
424//     l.equals(r)
425// }
426// pub fn verify_poseidon(pk: Point, sig: Signature, msg: BigInt) -> bool {
427//     let hm_input = vec![
428//         sig.r_b8.x.clone(),
429//         sig.r_b8.y.clone(),
430//         pk.x.clone(),
431//         pk.y.clone(),
432//         msg,
433//     ];
434//     let poseidon = Poseidon::new();
435//     let hm = match poseidon.hash(hm_input) {
436//         Result::Err(_) => return false,
437//         Result::Ok(hm) => hm,
438//     };
439//     let l = match B8.mul_scalar(&sig.s) {
440//         Result::Err(_) => return false,
441//         Result::Ok(l) => l,
442//     };
443//     let r = match sig
444//         .r_b8
445//         .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap())
446//     {
447//         Result::Err(_) => return false,
448//         Result::Ok(r) => r,
449//     };
450//     l.equals(r)
451// }
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    extern crate rustc_hex;
457    use rustc_hex::{FromHex, ToHex};
458
459    #[test]
460    fn test_add_same_point() {
461        let p: Point = Point {
462            x: Fr::from_str(
463                "17777552123799933955779906779655732241715742912184938656739573121738514868268",
464            )
465            .unwrap(),
466            y: Fr::from_str(
467                "2626589144620713026669568689430873010625803728049924121243784502389097019475",
468            )
469            .unwrap(),
470            z: Fr::one(),
471        };
472        let q: Point = Point {
473            x: Fr::from_str(
474                "17777552123799933955779906779655732241715742912184938656739573121738514868268",
475            )
476            .unwrap(),
477            y: Fr::from_str(
478                "2626589144620713026669568689430873010625803728049924121243784502389097019475",
479            )
480            .unwrap(),
481            z: Fr::one(),
482        };
483        let res = p.add(&q).unwrap().affine();
484        assert_eq!(
485            res.x,
486            Fr::from_str(
487                "6890855772600357754907169075114257697580319025794532037257385534741338397365"
488            )
489            .unwrap()
490        );
491        assert_eq!(
492            res.y,
493            Fr::from_str(
494                "4338620300185947561074059802482547481416142213883829469920100239455078257889"
495            )
496            .unwrap()
497        );
498    }
499    #[test]
500    fn test_add_different_points() {
501        let p: Point = Point {
502            x: Fr::from_str(
503                "17777552123799933955779906779655732241715742912184938656739573121738514868268",
504            )
505            .unwrap(),
506            y: Fr::from_str(
507                "2626589144620713026669568689430873010625803728049924121243784502389097019475",
508            )
509            .unwrap(),
510            z: Fr::one(),
511        };
512        let q: Point = Point {
513            x: Fr::from_str(
514                "16540640123574156134436876038791482806971768689494387082833631921987005038935",
515            )
516            .unwrap(),
517            y: Fr::from_str(
518                "20819045374670962167435360035096875258406992893633759881276124905556507972311",
519            )
520            .unwrap(),
521            z: Fr::one(),
522        };
523        let res = p.add(&q).unwrap().affine();
524        assert_eq!(
525            res.x,
526            Fr::from_str(
527                "7916061937171219682591368294088513039687205273691143098332585753343424131937"
528            )
529            .unwrap()
530        );
531        assert_eq!(
532            res.y,
533            Fr::from_str(
534                "14035240266687799601661095864649209771790948434046947201833777492504781204499"
535            )
536            .unwrap()
537        );
538    }
539
540    #[test]
541    fn test_mul_scalar() {
542        let p: Point = Point {
543            x: Fr::from_str(
544                "17777552123799933955779906779655732241715742912184938656739573121738514868268",
545            )
546            .unwrap(),
547            y: Fr::from_str(
548                "2626589144620713026669568689430873010625803728049924121243784502389097019475",
549            )
550            .unwrap(),
551            z: Fr::one(),
552        };
553        let res_m = p.mul_scalar(&3.to_bigint().unwrap()).unwrap().affine();
554        let res_a = p.add(&p).unwrap();
555        let res_a = res_a.add(&p).unwrap().affine();
556        assert_eq!(res_m.x, res_a.x);
557        assert_eq!(
558            res_m.x,
559            Fr::from_str(
560                "19372461775513343691590086534037741906533799473648040012278229434133483800898"
561            )
562            .unwrap()
563        );
564        assert_eq!(
565            res_m.y,
566            Fr::from_str(
567                "9458658722007214007257525444427903161243386465067105737478306991484593958249"
568            )
569            .unwrap()
570        );
571
572        let n = BigInt::parse_bytes(
573            b"14035240266687799601661095864649209771790948434046947201833777492504781204499",
574            10,
575        )
576        .unwrap();
577        let res2 = p.mul_scalar(&n).unwrap().affine();
578        assert_eq!(
579            res2.x,
580            Fr::from_str(
581                "17070357974431721403481313912716834497662307308519659060910483826664480189605"
582            )
583            .unwrap()
584        );
585        assert_eq!(
586            res2.y,
587            Fr::from_str(
588                "4014745322800118607127020275658861516666525056516280575712425373174125159339"
589            )
590            .unwrap()
591        );
592    }
593
594    // #[test]
595    // fn test_new_key_sign_verify_mimc_0() {
596    //     let sk = new_key();
597    //     let pk = sk.public().unwrap();
598    //     let msg = 5.to_bigint().unwrap();
599    //     let sig = sk.sign_mimc(msg.clone()).unwrap();
600    //     let v = verify_mimc(pk, sig, msg);
601    //     assert_eq!(v, true);
602    // }
603    //
604    // #[test]
605    // fn test_new_key_sign_verify_mimc_1() {
606    //     let sk = new_key();
607    //     let pk = sk.public().unwrap();
608    //     let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap();
609    //     let sig = sk.sign_mimc(msg.clone()).unwrap();
610    //     let v = verify_mimc(pk, sig, msg);
611    //     assert_eq!(v, true);
612    // }
613
614    // #[test]
615    // fn test_new_key_sign_verify_poseidon_0() {
616    //     let sk = new_key();
617    //     let pk = sk.public().unwrap();
618    //     let msg = 5.to_bigint().unwrap();
619    //     let sig = sk.sign_poseidon(msg.clone()).unwrap();
620    //     let v = verify_poseidon(pk, sig, msg);
621    //     assert_eq!(v, true);
622    // }
623    //
624    // #[test]
625    // fn test_new_key_sign_verify_poseidon_1() {
626    //     let sk = new_key();
627    //     let pk = sk.public().unwrap();
628    //     let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap();
629    //     let sig = sk.sign_poseidon(msg.clone()).unwrap();
630    //     let v = verify_poseidon(pk, sig, msg);
631    //     assert_eq!(v, true);
632    // }
633    //
634    #[test]
635    fn test_point_compress_decompress() {
636        let p: Point = Point {
637            x: Fr::from_str(
638                "17777552123799933955779906779655732241715742912184938656739573121738514868268",
639            )
640            .unwrap(),
641            y: Fr::from_str(
642                "2626589144620713026669568689430873010625803728049924121243784502389097019475",
643            )
644            .unwrap(),
645            z: Fr::one(),
646        };
647        let p_comp = p.compress();
648        assert_eq!(
649            p_comp[..].to_hex(),
650            "53b81ed5bffe9545b54016234682e7b2f699bd42a5e9eae27ff4051bc698ce85"
651        );
652        let p2 = decompress_point(p_comp).unwrap();
653        assert_eq!(p.x, p2.x);
654        assert_eq!(p.y, p2.y);
655    }
656
657    #[test]
658    fn test_point_decompress0() {
659        let y_bytes_raw = "b5328f8791d48f20bec6e481d91c7ada235f1facf22547901c18656b6c3e042f"
660            .from_hex()
661            .unwrap();
662        let mut y_bytes: [u8; 32] = [0; 32];
663        y_bytes.copy_from_slice(&y_bytes_raw);
664        let p = decompress_point(y_bytes).unwrap();
665
666        let expected_px_raw = "b86cc8d9c97daef0afe1a4753c54fb2d8a530dc74c7eee4e72b3fdf2496d2113"
667            .from_hex()
668            .unwrap();
669        let mut e_px_bytes: [u8; 32] = [0; 32];
670        e_px_bytes.copy_from_slice(&expected_px_raw);
671        // let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes);
672        let expected_px: Fr =
673            Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap();
674        assert_eq!(&p.x, &expected_px);
675    }
676
677    #[test]
678    fn test_point_decompress1() {
679        let y_bytes_raw = "70552d3ff548e09266ded29b33ce75139672b062b02aa66bb0d9247ffecf1d0b"
680            .from_hex()
681            .unwrap();
682        let mut y_bytes: [u8; 32] = [0; 32];
683        y_bytes.copy_from_slice(&y_bytes_raw);
684        let p = decompress_point(y_bytes).unwrap();
685
686        let expected_px_raw = "30f1635ba7d56f9cb32c3ffbe6dca508a68c7f43936af11a23c785ce98cb3404"
687            .from_hex()
688            .unwrap();
689        let mut e_px_bytes: [u8; 32] = [0; 32];
690        e_px_bytes.copy_from_slice(&expected_px_raw);
691        // let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes);
692        let expected_px: Fr =
693            Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap();
694        assert_eq!(&p.x, &expected_px);
695    }
696
697    #[test]
698    fn test_point_decompress_loop() {
699        for _ in 0..5 {
700            let random_bytes = rand::thread_rng().gen::<[u8; 32]>();
701            let sk_raw: BigInt = BigInt::from_bytes_le(Sign::Plus, &random_bytes[..]);
702            let mut hasher = Blake2b::new();
703            let (_, sk_raw_bytes) = sk_raw.to_bytes_be();
704            hasher.input(sk_raw_bytes);
705            let mut h = hasher.result();
706
707            h[0] = h[0] & 0xF8;
708            h[31] = h[31] & 0x7F;
709            h[31] = h[31] | 0x40;
710
711            let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]);
712            let point = B8.mul_scalar(&sk).unwrap();
713            let cmp_point = point.compress();
714            let dcmp_point = decompress_point(cmp_point).unwrap().affine();
715            let point_affine = point.affine();
716
717            assert_eq!(&point_affine.x, &dcmp_point.x);
718            assert_eq!(&point_affine.y, &dcmp_point.y);
719        }
720    }
721
722    // #[test]
723    // fn test_signature_compress_decompress() {
724    //     let sk = new_key();
725    //     let pk = sk.public().unwrap();
726    //
727    //     for i in 0..5 {
728    //         let msg_raw = "123456".to_owned() + &i.to_string();
729    //         let msg = BigInt::parse_bytes(msg_raw.as_bytes(), 10).unwrap();
730    //         let sig = sk.sign_mimc(msg.clone()).unwrap();
731    //
732    //         let compressed_sig = sig.compress();
733    //         let decompressed_sig = decompress_signature(&compressed_sig).unwrap();
734    //         assert_eq!(&sig.r_b8.x, &decompressed_sig.r_b8.x);
735    //         assert_eq!(&sig.r_b8.y, &decompressed_sig.r_b8.y);
736    //         assert_eq!(&sig.s, &decompressed_sig.s);
737    //
738    //         let v = verify_mimc(pk.clone(), decompressed_sig, msg);
739    //         assert_eq!(v, true);
740    //     }
741    // }
742
743    // #[test]
744    // fn test_schnorr_signature() {
745    //     let sk = new_key();
746    //     let pk = sk.public().unwrap();
747    //
748    //     let msg: Vec<u8> = ("123456".to_owned() + &1.to_string()).as_bytes().to_vec();
749    //     let (s, e) = sk.sign_schnorr(msg.clone()).unwrap();
750    //     println!("s {:?}", s.x.to_string());
751    //     println!("s {:?}", s.y.to_string());
752    //     println!("e {:?}", e.to_string());
753    //     let verification = verify_schnorr(pk, msg, s, e).unwrap();
754    //     assert_eq!(true, verification);
755    // }
756}