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