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