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.

767 lines
23 KiB

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