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