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