You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

739 lines
23 KiB

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