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