babyjubjub-rs/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) -> Result<PointProjective, String> {
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 Ok(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) -> Result<Point, String> {
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 Ok(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) -> Result<Point, String> {
302 // https://tools.ietf.org/html/rfc8032#section-5.1.5
303 let pk = B8.mul_scalar(&self.scalar_key())?;
304 Ok(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 = match B8.mul_scalar(&sig.s) {
413 Result::Err(_) => return false,
414 Result::Ok(l) => l,
415 };
416 let hm_b = BigInt::parse_bytes(to_hex(&hm).as_bytes(), 16).unwrap();
417 let r = match sig.r_b8.projective().add(
418 &pk.mul_scalar(&(8.to_bigint().unwrap() * hm_b))
419 .unwrap()
420 .projective(),
421 ) {
422 Result::Err(_) => return false,
423 Result::Ok(r) => r,
424 };
425 l.equals(r.affine())
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431 extern crate rustc_hex;
432 use rustc_hex::{FromHex, ToHex};
433
434 #[test]
435 fn test_add_same_point() {
436 let p: PointProjective = PointProjective {
437 x: Fr::from_str(
438 "17777552123799933955779906779655732241715742912184938656739573121738514868268",
439 )
440 .unwrap(),
441 y: Fr::from_str(
442 "2626589144620713026669568689430873010625803728049924121243784502389097019475",
443 )
444 .unwrap(),
445 z: Fr::one(),
446 };
447 let q: PointProjective = PointProjective {
448 x: Fr::from_str(
449 "17777552123799933955779906779655732241715742912184938656739573121738514868268",
450 )
451 .unwrap(),
452 y: Fr::from_str(
453 "2626589144620713026669568689430873010625803728049924121243784502389097019475",
454 )
455 .unwrap(),
456 z: Fr::one(),
457 };
458 let res = p.add(&q).unwrap().affine();
459 assert_eq!(
460 res.x,
461 Fr::from_str(
462 "6890855772600357754907169075114257697580319025794532037257385534741338397365"
463 )
464 .unwrap()
465 );
466 assert_eq!(
467 res.y,
468 Fr::from_str(
469 "4338620300185947561074059802482547481416142213883829469920100239455078257889"
470 )
471 .unwrap()
472 );
473 }
474 #[test]
475 fn test_add_different_points() {
476 let p: PointProjective = PointProjective {
477 x: Fr::from_str(
478 "17777552123799933955779906779655732241715742912184938656739573121738514868268",
479 )
480 .unwrap(),
481 y: Fr::from_str(
482 "2626589144620713026669568689430873010625803728049924121243784502389097019475",
483 )
484 .unwrap(),
485 z: Fr::one(),
486 };
487 let q: PointProjective = PointProjective {
488 x: Fr::from_str(
489 "16540640123574156134436876038791482806971768689494387082833631921987005038935",
490 )
491 .unwrap(),
492 y: Fr::from_str(
493 "20819045374670962167435360035096875258406992893633759881276124905556507972311",
494 )
495 .unwrap(),
496 z: Fr::one(),
497 };
498 let res = p.add(&q).unwrap().affine();
499 assert_eq!(
500 res.x,
501 Fr::from_str(
502 "7916061937171219682591368294088513039687205273691143098332585753343424131937"
503 )
504 .unwrap()
505 );
506 assert_eq!(
507 res.y,
508 Fr::from_str(
509 "14035240266687799601661095864649209771790948434046947201833777492504781204499"
510 )
511 .unwrap()
512 );
513 }
514
515 #[test]
516 fn test_mul_scalar() {
517 let p: Point = Point {
518 x: Fr::from_str(
519 "17777552123799933955779906779655732241715742912184938656739573121738514868268",
520 )
521 .unwrap(),
522 y: Fr::from_str(
523 "2626589144620713026669568689430873010625803728049924121243784502389097019475",
524 )
525 .unwrap(),
526 };
527 let res_m = p.mul_scalar(&3.to_bigint().unwrap()).unwrap();
528 let res_a = p.projective().add(&p.projective()).unwrap();
529 let res_a = res_a.add(&p.projective()).unwrap().affine();
530 assert_eq!(res_m.x, res_a.x);
531 assert_eq!(
532 res_m.x,
533 Fr::from_str(
534 "19372461775513343691590086534037741906533799473648040012278229434133483800898"
535 )
536 .unwrap()
537 );
538 assert_eq!(
539 res_m.y,
540 Fr::from_str(
541 "9458658722007214007257525444427903161243386465067105737478306991484593958249"
542 )
543 .unwrap()
544 );
545
546 let n = BigInt::parse_bytes(
547 b"14035240266687799601661095864649209771790948434046947201833777492504781204499",
548 10,
549 )
550 .unwrap();
551 let res2 = p.mul_scalar(&n).unwrap();
552 assert_eq!(
553 res2.x,
554 Fr::from_str(
555 "17070357974431721403481313912716834497662307308519659060910483826664480189605"
556 )
557 .unwrap()
558 );
559 assert_eq!(
560 res2.y,
561 Fr::from_str(
562 "4014745322800118607127020275658861516666525056516280575712425373174125159339"
563 )
564 .unwrap()
565 );
566 }
567
568 #[test]
569 fn test_new_key_sign_verify_0() {
570 let sk = new_key();
571 let pk = sk.public().unwrap();
572 let msg = 5.to_bigint().unwrap();
573 let sig = sk.sign(msg.clone()).unwrap();
574 let v = verify(pk, sig, msg);
575 assert_eq!(v, true);
576 }
577
578 #[test]
579 fn test_new_key_sign_verify_1() {
580 let sk = new_key();
581 let pk = sk.public().unwrap();
582 let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap();
583 let sig = sk.sign(msg.clone()).unwrap();
584 let v = verify(pk, sig, msg);
585 assert_eq!(v, true);
586 }
587
588 #[test]
589 fn test_point_compress_decompress() {
590 let p: Point = Point {
591 x: Fr::from_str(
592 "17777552123799933955779906779655732241715742912184938656739573121738514868268",
593 )
594 .unwrap(),
595 y: Fr::from_str(
596 "2626589144620713026669568689430873010625803728049924121243784502389097019475",
597 )
598 .unwrap(),
599 };
600 let p_comp = p.compress();
601 assert_eq!(
602 p_comp[..].to_hex(),
603 "53b81ed5bffe9545b54016234682e7b2f699bd42a5e9eae27ff4051bc698ce85"
604 );
605 let p2 = decompress_point(p_comp).unwrap();
606 assert_eq!(p.x, p2.x);
607 assert_eq!(p.y, p2.y);
608 }
609
610 #[test]
611 fn test_point_decompress0() {
612 let y_bytes_raw = "b5328f8791d48f20bec6e481d91c7ada235f1facf22547901c18656b6c3e042f"
613 .from_hex()
614 .unwrap();
615 let mut y_bytes: [u8; 32] = [0; 32];
616 y_bytes.copy_from_slice(&y_bytes_raw);
617 let p = decompress_point(y_bytes).unwrap();
618
619 let expected_px_raw = "b86cc8d9c97daef0afe1a4753c54fb2d8a530dc74c7eee4e72b3fdf2496d2113"
620 .from_hex()
621 .unwrap();
622 let mut e_px_bytes: [u8; 32] = [0; 32];
623 e_px_bytes.copy_from_slice(&expected_px_raw);
624 let expected_px: Fr =
625 Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap();
626 assert_eq!(&p.x, &expected_px);
627 }
628
629 #[test]
630 fn test_point_decompress1() {
631 let y_bytes_raw = "70552d3ff548e09266ded29b33ce75139672b062b02aa66bb0d9247ffecf1d0b"
632 .from_hex()
633 .unwrap();
634 let mut y_bytes: [u8; 32] = [0; 32];
635 y_bytes.copy_from_slice(&y_bytes_raw);
636 let p = decompress_point(y_bytes).unwrap();
637
638 let expected_px_raw = "30f1635ba7d56f9cb32c3ffbe6dca508a68c7f43936af11a23c785ce98cb3404"
639 .from_hex()
640 .unwrap();
641 let mut e_px_bytes: [u8; 32] = [0; 32];
642 e_px_bytes.copy_from_slice(&expected_px_raw);
643 let expected_px: Fr =
644 Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap();
645 assert_eq!(&p.x, &expected_px);
646 }
647
648 #[test]
649 fn test_point_decompress_loop() {
650 for _ in 0..5 {
651 let random_bytes = rand6::thread_rng().gen::<[u8; 32]>();
652 let sk_raw: BigInt = BigInt::from_bytes_le(Sign::Plus, &random_bytes[..]);
653 let (_, sk_raw_bytes) = sk_raw.to_bytes_be();
654 let mut h = blake_hash::Blake512::digest(&sk_raw_bytes);
655
656 h[0] = h[0] & 0xF8;
657 h[31] = h[31] & 0x7F;
658 h[31] = h[31] | 0x40;
659
660 let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]);
661 let point = B8.mul_scalar(&sk).unwrap();
662 let cmp_point = point.compress();
663 let dcmp_point = decompress_point(cmp_point).unwrap();
664
665 assert_eq!(&point.x, &dcmp_point.x);
666 assert_eq!(&point.y, &dcmp_point.y);
667 }
668 }
669
670 #[test]
671 fn test_signature_compress_decompress() {
672 let sk = new_key();
673 let pk = sk.public().unwrap();
674
675 for i in 0..5 {
676 let msg_raw = "123456".to_owned() + &i.to_string();
677 let msg = BigInt::parse_bytes(msg_raw.as_bytes(), 10).unwrap();
678 let sig = sk.sign(msg.clone()).unwrap();
679
680 let compressed_sig = sig.compress();
681 let decompressed_sig = decompress_signature(&compressed_sig).unwrap();
682 assert_eq!(&sig.r_b8.x, &decompressed_sig.r_b8.x);
683 assert_eq!(&sig.r_b8.y, &decompressed_sig.r_b8.y);
684 assert_eq!(&sig.s, &decompressed_sig.s);
685
686 let v = verify(pk.clone(), decompressed_sig, msg);
687 assert_eq!(v, true);
688 }
689 }
690
691 #[test]
692 fn test_schnorr_signature() {
693 let sk = new_key();
694 let pk = sk.public().unwrap();
695
696 let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap();
697 let (s, e) = sk.sign_schnorr(msg.clone()).unwrap();
698 let verification = verify_schnorr(pk, msg, s, e).unwrap();
699 assert_eq!(true, verification);
700 }
701
702 #[test]
703 fn test_circomlib_testvector() {
704 let sk_raw_bytes =
705 hex::decode("0001020304050607080900010203040506070809000102030405060708090001")
706 .unwrap();
707
708 // test blake compatible with circomlib implementation
709 let h = blake_hash::Blake512::digest(&sk_raw_bytes);
710 assert_eq!(h.to_hex(), "c992db23d6290c70ffcc02f7abeb00b9d00fa8b43e55d7949c28ba6be7545d3253882a61bd004a236ef1cdba01b27ba0aedfb08eefdbfb7c19657c880b43ddf1");
711
712 // test private key
713 let sk = PrivateKey::import(
714 hex::decode("0001020304050607080900010203040506070809000102030405060708090001")
715 .unwrap(),
716 )
717 .unwrap();
718 assert_eq!(
719 sk.scalar_key().to_string(),
720 "6466070937662820620902051049739362987537906109895538826186780010858059362905"
721 );
722
723 // test public key
724 let pk = sk.public().unwrap();
725 assert_eq!(
726 pk.x.to_string(),
727 "Fr(0x1d5ac1f31407018b7d413a4f52c8f74463b30e6ac2238220ad8b254de4eaa3a2)"
728 );
729 assert_eq!(
730 pk.y.to_string(),
731 "Fr(0x1e1de8a908826c3f9ac2e0ceee929ecd0caf3b99b3ef24523aaab796a6f733c4)"
732 );
733
734 // test signature & verification
735 let msg = BigInt::from_bytes_le(Sign::Plus, &hex::decode("00010203040506070809").unwrap());
736 println!("msg {:?}", msg.to_string());
737 let sig = sk.sign(msg.clone()).unwrap();
738 assert_eq!(
739 sig.r_b8.x.to_string(),
740 "Fr(0x192b4e51adf302c8139d356d0e08e2404b5ace440ef41fc78f5c4f2428df0765)"
741 );
742 assert_eq!(
743 sig.r_b8.y.to_string(),
744 "Fr(0x2202bebcf57b820863e0acc88970b6ca7d987a0d513c2ddeb42e3f5d31b4eddf)"
745 );
746 assert_eq!(
747 sig.s.to_string(),
748 "1398758333392199195742243841591064350253744445503462896781493968760929513778"
749 );
750 let v = verify(pk, sig, msg);
751 assert_eq!(v, true);
752 }
753}