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.

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