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