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