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