From 30218dc1f3116c97a61b5e1a976b6e1ac1ff8396 Mon Sep 17 00:00:00 2001 From: arnaucube Date: Sat, 25 Jul 2020 18:33:51 +0200 Subject: [PATCH 1/4] Add benchmarks --- Cargo.toml | 8 +++ benches/bench_babyjubjub.rs | 59 ++++++++++++++++ src/lib.rs | 131 ++++++++++++++++++------------------ 3 files changed, 133 insertions(+), 65 deletions(-) create mode 100644 benches/bench_babyjubjub.rs diff --git a/Cargo.toml b/Cargo.toml index 5f3d28e..970767c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,3 +21,11 @@ mimc-rs = "0.0.2" poseidon-rs = "0.0.1" arrayref = "0.3.5" lazy_static = "1.4.0" + +[dev-dependencies] +criterion = "0.3" + +[[bench]] +name = "bench_babyjubjub" +harness = false + diff --git a/benches/bench_babyjubjub.rs b/benches/bench_babyjubjub.rs new file mode 100644 index 0000000..d73e7c5 --- /dev/null +++ b/benches/bench_babyjubjub.rs @@ -0,0 +1,59 @@ +use criterion::{criterion_group, criterion_main, Criterion}; + +extern crate num; +extern crate num_bigint; +extern crate num_traits; +use num_bigint::{BigInt, ToBigInt}; + +use babyjubjub_rs::{utils, Point}; + +fn criterion_benchmark(c: &mut Criterion) { + let x: BigInt = BigInt::parse_bytes( + b"17777552123799933955779906779655732241715742912184938656739573121738514868268", + 10, + ) + .unwrap(); + c.bench_function("modulus", |b| { + b.iter(|| utils::modulus(&x, &babyjubjub_rs::Q)) + }); + + let p: Point = Point { + x: BigInt::parse_bytes( + b"17777552123799933955779906779655732241715742912184938656739573121738514868268", + 10, + ) + .unwrap(), + y: BigInt::parse_bytes( + b"2626589144620713026669568689430873010625803728049924121243784502389097019475", + 10, + ) + .unwrap(), + }; + let q = p.clone(); + + c.bench_function("add", |b| b.iter(|| p.add(&q))); + + c.bench_function("mul_scalar_small", |b| { + b.iter(|| p.mul_scalar(&3.to_bigint().unwrap())) + }); + let r: BigInt = BigInt::parse_bytes( + b"2626589144620713026669568689430873010625803728049924121243784502389097019475", + 10, + ) + .unwrap(); + c.bench_function("mul_scalar", |b| b.iter(|| p.mul_scalar(&r))); + + let sk = babyjubjub_rs::new_key(); + let pk = sk.public().unwrap(); + let msg = 5.to_bigint().unwrap(); + c.bench_function("sign_poseidon", |b| { + b.iter(|| sk.sign_poseidon(msg.clone())) + }); + let sig = sk.sign_poseidon(msg.clone()).unwrap(); + c.bench_function("verify_poseidon", |b| { + b.iter(|| babyjubjub_rs::verify_poseidon(pk.clone(), sig.clone(), msg.clone())) + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/src/lib.rs b/src/lib.rs index aa1e418..358e448 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,7 +17,7 @@ use num_traits::{One, Zero}; use generic_array::GenericArray; -mod utils; +pub mod utils; #[macro_use] extern crate lazy_static; @@ -25,7 +25,7 @@ extern crate lazy_static; lazy_static! { static ref D: BigInt = BigInt::parse_bytes(b"168696", 10).unwrap(); static ref A: BigInt = BigInt::parse_bytes(b"168700", 10).unwrap(); - static ref Q: BigInt = BigInt::parse_bytes( + pub static ref Q: BigInt = BigInt::parse_bytes( b"21888242871839275222246405745257275088548364400416034343698204186575808495617", 10, ) @@ -156,6 +156,7 @@ pub fn decompress_point(bb: [u8; 32]) -> Result { Ok(Point { x: x, y: y }) } +#[derive(Debug, Clone)] pub struct Signature { r_b8: Point, s: BigInt, @@ -497,25 +498,25 @@ mod tests { ); } - #[test] - fn test_new_key_sign_verify_mimc_0() { - let sk = new_key(); - let pk = sk.public().unwrap(); - let msg = 5.to_bigint().unwrap(); - let sig = sk.sign_mimc(msg.clone()).unwrap(); - let v = verify_mimc(pk, sig, msg); - assert_eq!(v, true); - } - - #[test] - fn test_new_key_sign_verify_mimc_1() { - let sk = new_key(); - let pk = sk.public().unwrap(); - let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); - let sig = sk.sign_mimc(msg.clone()).unwrap(); - let v = verify_mimc(pk, sig, msg); - assert_eq!(v, true); - } + // #[test] + // fn test_new_key_sign_verify_mimc_0() { + // let sk = new_key(); + // let pk = sk.public().unwrap(); + // let msg = 5.to_bigint().unwrap(); + // let sig = sk.sign_mimc(msg.clone()).unwrap(); + // let v = verify_mimc(pk, sig, msg); + // assert_eq!(v, true); + // } + // + // #[test] + // fn test_new_key_sign_verify_mimc_1() { + // let sk = new_key(); + // let pk = sk.public().unwrap(); + // let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); + // let sig = sk.sign_mimc(msg.clone()).unwrap(); + // let v = verify_mimc(pk, sig, msg); + // assert_eq!(v, true); + // } #[test] fn test_new_key_sign_verify_poseidon_0() { let sk = new_key(); @@ -596,50 +597,50 @@ mod tests { assert_eq!(&p.x, &expected_px); } - #[test] - fn test_point_decompress_loop() { - for _ in 0..5 { - let mut rng = rand::thread_rng(); - let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap(); - let mut hasher = Blake2b::new(); - let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); - hasher.input(sk_raw_bytes); - let mut h = hasher.result(); - - h[0] = h[0] & 0xF8; - h[31] = h[31] & 0x7F; - h[31] = h[31] | 0x40; - - let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); - let point = B8.mul_scalar(&sk).unwrap(); - let cmp_point = point.compress(); - let dcmp_point = decompress_point(cmp_point).unwrap(); - - assert_eq!(&point.x, &dcmp_point.x); - assert_eq!(&point.y, &dcmp_point.y); - } - } - - #[test] - fn test_signature_compress_decompress() { - let sk = new_key(); - let pk = sk.public().unwrap(); - - for i in 0..5 { - let msg_raw = "123456".to_owned() + &i.to_string(); - let msg = BigInt::parse_bytes(msg_raw.as_bytes(), 10).unwrap(); - let sig = sk.sign_mimc(msg.clone()).unwrap(); - - let compressed_sig = sig.compress(); - let decompressed_sig = decompress_signature(&compressed_sig).unwrap(); - assert_eq!(&sig.r_b8.x, &decompressed_sig.r_b8.x); - assert_eq!(&sig.r_b8.y, &decompressed_sig.r_b8.y); - assert_eq!(&sig.s, &decompressed_sig.s); - - let v = verify_mimc(pk.clone(), decompressed_sig, msg); - assert_eq!(v, true); - } - } + // #[test] + // fn test_point_decompress_loop() { + // for _ in 0..5 { + // let mut rng = rand::thread_rng(); + // let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap(); + // let mut hasher = Blake2b::new(); + // let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); + // hasher.input(sk_raw_bytes); + // let mut h = hasher.result(); + // + // h[0] = h[0] & 0xF8; + // h[31] = h[31] & 0x7F; + // h[31] = h[31] | 0x40; + // + // let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); + // let point = B8.mul_scalar(&sk).unwrap(); + // let cmp_point = point.compress(); + // let dcmp_point = decompress_point(cmp_point).unwrap(); + // + // assert_eq!(&point.x, &dcmp_point.x); + // assert_eq!(&point.y, &dcmp_point.y); + // } + // } + + // #[test] + // fn test_signature_compress_decompress() { + // let sk = new_key(); + // let pk = sk.public().unwrap(); + // + // for i in 0..5 { + // let msg_raw = "123456".to_owned() + &i.to_string(); + // let msg = BigInt::parse_bytes(msg_raw.as_bytes(), 10).unwrap(); + // let sig = sk.sign_mimc(msg.clone()).unwrap(); + // + // let compressed_sig = sig.compress(); + // let decompressed_sig = decompress_signature(&compressed_sig).unwrap(); + // assert_eq!(&sig.r_b8.x, &decompressed_sig.r_b8.x); + // assert_eq!(&sig.r_b8.y, &decompressed_sig.r_b8.y); + // assert_eq!(&sig.s, &decompressed_sig.s); + // + // let v = verify_mimc(pk.clone(), decompressed_sig, msg); + // assert_eq!(v, true); + // } + // } #[test] fn test_schnorr_signature() { From 2d94206899b17ccbbb3584335a7658679e66355b Mon Sep 17 00:00:00 2001 From: arnaucube Date: Sat, 1 Aug 2020 18:18:43 +0200 Subject: [PATCH 2/4] Optimize point add & mul_scalar methods (On a Intel(R) Core(TM) i7-8705G CPU @ 3.10GHz, with 32 GB of RAM) - before: ``` add time: [53.447 us 53.467 us 53.492 us] mul_scalar time: [121.19 ms 121.22 ms 121.25 ms] ``` - current: ``` add time: [317.34 ns 317.44 ns 317.54 ns] mul_scalar time: [131.05 us 131.28 us 131.58 us] ``` Which is `168x` improvement for `add`, and `923x` improvement for `mul_scalar`. --- Cargo.toml | 3 +- benches/bench_babyjubjub.rs | 67 +-- src/lib.rs | 848 ++++++++++++++++++++---------------- 3 files changed, 512 insertions(+), 406 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 970767c..dbcd6ef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,10 +9,11 @@ repository = "https://github.com/arnaucube/babyjubjub-rs" readme = "README.md" [dependencies] +ff = {package="ff_ce" , version="0.11", features = ["derive"]} +rand = "0.4" num = "0.2.0" num-bigint = {version = "0.2.2", features = ["rand"]} num-traits = "0.2.8" -rand = "0.6.5" blake2 = "0.8" generic-array = "0.13.2" tiny-keccak = "1.5" diff --git a/benches/bench_babyjubjub.rs b/benches/bench_babyjubjub.rs index d73e7c5..38fda56 100644 --- a/benches/bench_babyjubjub.rs +++ b/benches/bench_babyjubjub.rs @@ -1,41 +1,42 @@ use criterion::{criterion_group, criterion_main, Criterion}; +extern crate rand; +#[macro_use] +extern crate ff; +use ff::*; + extern crate num; extern crate num_bigint; -extern crate num_traits; -use num_bigint::{BigInt, ToBigInt}; +use num_bigint::BigInt; use babyjubjub_rs::{utils, Point}; fn criterion_benchmark(c: &mut Criterion) { - let x: BigInt = BigInt::parse_bytes( - b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - 10, - ) - .unwrap(); - c.bench_function("modulus", |b| { - b.iter(|| utils::modulus(&x, &babyjubjub_rs::Q)) - }); + // let x: BigInt = BigInt::parse_bytes( + // b"17777552123799933955779906779655732241715742912184938656739573121738514868268", + // 10, + // ) + // .unwrap(); + // c.bench_function("modulus", |b| { + // b.iter(|| utils::modulus(&x, &babyjubjub_rs::Q)) + // }); let p: Point = Point { - x: BigInt::parse_bytes( - b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - 10, + x: babyjubjub_rs::Fr::from_str( + "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) .unwrap(), - y: BigInt::parse_bytes( - b"2626589144620713026669568689430873010625803728049924121243784502389097019475", - 10, + y: babyjubjub_rs::Fr::from_str( + "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), + z: babyjubjub_rs::Fr::one(), }; let q = p.clone(); c.bench_function("add", |b| b.iter(|| p.add(&q))); - - c.bench_function("mul_scalar_small", |b| { - b.iter(|| p.mul_scalar(&3.to_bigint().unwrap())) - }); + let r: BigInt = BigInt::parse_bytes(b"3", 10).unwrap(); + c.bench_function("mul_scalar_small", |b| b.iter(|| p.mul_scalar(&r))); let r: BigInt = BigInt::parse_bytes( b"2626589144620713026669568689430873010625803728049924121243784502389097019475", 10, @@ -43,16 +44,22 @@ fn criterion_benchmark(c: &mut Criterion) { .unwrap(); c.bench_function("mul_scalar", |b| b.iter(|| p.mul_scalar(&r))); - let sk = babyjubjub_rs::new_key(); - let pk = sk.public().unwrap(); - let msg = 5.to_bigint().unwrap(); - c.bench_function("sign_poseidon", |b| { - b.iter(|| sk.sign_poseidon(msg.clone())) - }); - let sig = sk.sign_poseidon(msg.clone()).unwrap(); - c.bench_function("verify_poseidon", |b| { - b.iter(|| babyjubjub_rs::verify_poseidon(pk.clone(), sig.clone(), msg.clone())) - }); + // c.bench_function("compress", |b| b.iter(|| p.compress())); + // let p_comp = p.compress(); + // c.bench_function("decompress", |b| { + // b.iter(|| babyjubjub_rs::decompress_point(p_comp)) + // }); + + // let sk = babyjubjub_rs::new_key(); + // let pk = sk.public().unwrap(); + // let msg = 5.to_bigint().unwrap(); + // c.bench_function("sign_poseidon", |b| { + // b.iter(|| sk.sign_poseidon(msg.clone())) + // }); + // let sig = sk.sign_poseidon(msg.clone()).unwrap(); + // c.bench_function("verify_poseidon", |b| { + // b.iter(|| babyjubjub_rs::verify_poseidon(pk.clone(), sig.clone(), msg.clone())) + // }); } criterion_group!(benches, criterion_benchmark); diff --git a/src/lib.rs b/src/lib.rs index 358e448..dbb3a94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,13 @@ +extern crate rand; +#[macro_use] +extern crate ff; +use ff::*; + +#[derive(PrimeField)] +#[PrimeFieldModulus = "21888242871839275222246405745257275088548364400416034343698204186575808495617"] +#[PrimeFieldGenerator = "7"] +pub struct Fr(FrRepr); + #[macro_use] extern crate arrayref; extern crate generic_array; @@ -5,14 +15,15 @@ extern crate mimc_rs; extern crate num; extern crate num_bigint; extern crate num_traits; -extern crate rand; + +use rand::Rng; use blake2::{Blake2b, Digest}; use mimc_rs::Mimc7; use poseidon_rs::Poseidon; use std::cmp::min; -use num_bigint::{BigInt, RandBigInt, Sign, ToBigInt}; +use num_bigint::{BigInt, RandBigInt, RandomBits, Sign, ToBigInt}; use num_traits::{One, Zero}; use generic_array::GenericArray; @@ -23,94 +34,151 @@ pub mod utils; extern crate lazy_static; lazy_static! { - static ref D: BigInt = BigInt::parse_bytes(b"168696", 10).unwrap(); - static ref A: BigInt = BigInt::parse_bytes(b"168700", 10).unwrap(); + static ref D: Fr = Fr::from_str("168696").unwrap(); + static ref D_big: BigInt = BigInt::parse_bytes(b"168696", 10).unwrap(); + static ref A: Fr = Fr::from_str("168700").unwrap(); + static ref A_big: BigInt = BigInt::parse_bytes(b"168700", 10).unwrap(); pub static ref Q: BigInt = BigInt::parse_bytes( - b"21888242871839275222246405745257275088548364400416034343698204186575808495617", - 10, + b"21888242871839275222246405745257275088548364400416034343698204186575808495617",10 ) .unwrap(); + // pub static ref Q: Fr = Fr::from_str( + // "21888242871839275222246405745257275088548364400416034343698204186575808495617" + // ) + // .unwrap(); static ref B8: Point = Point { - x: BigInt::parse_bytes( - b"5299619240641551281634865583518297030282874472190772894086521144482721001553", - 10, + x: Fr::from_str( + "5299619240641551281634865583518297030282874472190772894086521144482721001553", ) .unwrap(), - y: BigInt::parse_bytes( - b"16950150798460657717958625567821834550301663161624707787222815936182638968203", - 10, + y: Fr::from_str( + "16950150798460657717958625567821834550301663161624707787222815936182638968203", ) .unwrap(), + z: Fr::one(), }; - static ref ORDER: BigInt = BigInt::parse_bytes( - b"21888242871839275222246405745257275088614511777268538073601725287587578984328", - 10, + static ref ORDER: Fr = Fr::from_str( + "21888242871839275222246405745257275088614511777268538073601725287587578984328", ) .unwrap(); - static ref SUBORDER: BigInt = &BigInt::parse_bytes( - b"21888242871839275222246405745257275088614511777268538073601725287587578984328", - 10, + // SUBORDER = ORDER >> 3 + static ref SUBORDER: Fr = Fr::from_str( + "i2736030358979909402780800718157159386076813972158567259200215660948447373041", ) - .unwrap() - >> 3; + .unwrap(); +} + +pub struct PointAffine { + pub x: Fr, + pub y: Fr, } #[derive(Clone, Debug)] pub struct Point { - pub x: BigInt, - pub y: BigInt, + pub x: Fr, + pub y: Fr, + pub z: Fr, } impl Point { + pub fn affine(&self) -> PointAffine { + if self.z.is_zero() { + return PointAffine { + x: Fr::zero(), + y: Fr::zero(), + }; + } + + let mut zinv = self.z.inverse().unwrap(); + let mut x = self.x; + x.mul_assign(&zinv); + let mut y = self.y; + y.mul_assign(&zinv); + + PointAffine { + x: x.clone(), + y: y.clone(), + } + } + pub fn from_affine(p: PointAffine) -> Point { + Point { + x: p.x.clone(), + y: p.y.clone(), + z: Fr::one(), + } + } + pub fn add(&self, q: &Point) -> Result { - // x = (x1*y2+y1*x2)/(c*(1+d*x1*x2*y1*y2)) - // y = (y1*y2-x1*x2)/(c*(1-d*x1*x2*y1*y2)) - - // x = (x1 * y2 + y1 * x2) / (1 + d * x1 * y1 * y2) - let one: BigInt = One::one(); - let x_num: BigInt = &self.x * &q.y + &self.y * &q.x; - let x_den: BigInt = &one + &D.clone() * &self.x * &q.x * &self.y * &q.y; - let x_den_inv = utils::modinv(&x_den, &Q)?; - let x: BigInt = utils::modulus(&(&x_num * &x_den_inv), &Q); - - // y = (y1 * y2 - a * x1 * x2) / (1 - d * x1 * x2 * y1 * y2) - let y_num = &self.y * &q.y - &A.clone() * &self.x * &q.x; - let y_den = utils::modulus(&(&one - &D.clone() * &self.x * &q.x * &self.y * &q.y), &Q); - let y_den_inv = utils::modinv(&y_den, &Q)?; - let y: BigInt = utils::modulus(&(&y_num * &y_den_inv), &Q); - - Ok(Point { x: x, y: y }) + // add-2008-bbjlp https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp + let mut a = self.z; + a.mul_assign(&q.z); + let mut b = a; + b.square(); + let mut c = self.x; + c.mul_assign(&q.x); + let mut d = self.y; + d.mul_assign(&q.y); + let mut e = D.clone(); + e.mul_assign(&c); + e.mul_assign(&d); + let mut f = b; + f.sub_assign(&e); + let mut g = b; + g.add_assign(&e); + let mut x1y1 = self.x; + x1y1.add_assign(&self.y); + let mut x2y2 = q.x; + x2y2.add_assign(&q.y); + let mut aux = x1y1; + aux.mul_assign(&x2y2); + aux.sub_assign(&c); + aux.sub_assign(&d); + let mut x3 = a; + x3.mul_assign(&f); + x3.mul_assign(&aux); + let mut ac = A.clone(); + ac.mul_assign(&c); + let mut dac = d; + dac.sub_assign(&ac); + let mut y3 = a; + y3.mul_assign(&g); + y3.mul_assign(&dac); + let mut z3 = f; + z3.mul_assign(&g); + + Ok(Point { + x: x3.clone(), + y: y3.clone(), + z: z3.clone(), + }) } pub fn mul_scalar(&self, n: &BigInt) -> Result { let mut r: Point = Point { - x: Zero::zero(), - y: One::one(), + x: Fr::zero(), + y: Fr::one(), + z: Fr::one(), }; - let mut rem: BigInt = n.clone(); let mut exp: Point = self.clone(); - - let zero: BigInt = Zero::zero(); - let one: BigInt = One::one(); - while rem != zero { - let is_odd = &rem & &one == one; - if is_odd == true { + let (_, b) = n.to_bytes_le(); + for i in 0..n.bits() { + if test_bit(&b, i) { r = r.add(&exp)?; } exp = exp.add(&exp)?; - rem = rem >> 1; } - r.x = utils::modulus(&r.x, &Q); - r.y = utils::modulus(&r.y, &Q); Ok(r) } pub fn compress(&self) -> [u8; 32] { + let p = &self.affine(); let mut r: [u8; 32] = [0; 32]; - let (_, y_bytes) = self.y.to_bytes_le(); + let x_big = BigInt::parse_bytes(to_hex(&p.x).as_bytes(), 16).unwrap(); + let y_big = BigInt::parse_bytes(to_hex(&p.y).as_bytes(), 16).unwrap(); + let (_, y_bytes) = y_big.to_bytes_le(); let len = min(y_bytes.len(), r.len()); r[..len].copy_from_slice(&y_bytes[..len]); - if &self.x > &(&Q.clone() >> 1) { + if &x_big > &(&Q.clone() >> 1) { r[31] = r[31] | 0x80; } r @@ -124,6 +192,10 @@ impl Point { } } +pub fn test_bit(b: &Vec, i: usize) -> bool { + return b[i / 8] & (1 << (i % 8)) != 0; +} + pub fn decompress_point(bb: [u8; 32]) -> Result { // https://tools.ietf.org/html/rfc8032#section-5.2.3 let mut sign: bool = false; @@ -141,7 +213,7 @@ pub fn decompress_point(bb: [u8; 32]) -> Result { // x^2 = (1 - y^2) / (a - d * y^2) (mod p) let den = utils::modinv( &utils::modulus( - &(&A.clone() - utils::modulus(&(&D.clone() * (&y * &y)), &Q)), + &(&A_big.clone() - utils::modulus(&(&D_big.clone() * (&y * &y)), &Q)), &Q, ), &Q, @@ -153,43 +225,45 @@ pub fn decompress_point(bb: [u8; 32]) -> Result { x = x * -1.to_bigint().unwrap(); } x = utils::modulus(&x, &Q); - Ok(Point { x: x, y: y }) + let x_fr: Fr = Fr::from_str(&x.to_string()).unwrap(); + let y_fr: Fr = Fr::from_str(&y.to_string()).unwrap(); + Ok(Point::from_affine(PointAffine { x: x_fr, y: y_fr })) } - -#[derive(Debug, Clone)] -pub struct Signature { - r_b8: Point, - s: BigInt, -} - -impl Signature { - pub fn compress(&self) -> [u8; 64] { - let mut b: Vec = Vec::new(); - b.append(&mut self.r_b8.compress().to_vec()); - let (_, s_bytes) = self.s.to_bytes_le(); - let mut s_32bytes: [u8; 32] = [0; 32]; - let len = min(s_bytes.len(), s_32bytes.len()); - s_32bytes[..len].copy_from_slice(&s_bytes[..len]); - b.append(&mut s_32bytes.to_vec()); - let mut r: [u8; 64] = [0; 64]; - r[..].copy_from_slice(&b[..]); - r - } -} - -pub fn decompress_signature(b: &[u8; 64]) -> Result { - let r_b8_bytes: [u8; 32] = *array_ref!(b[..32], 0, 32); - let s: BigInt = BigInt::from_bytes_le(Sign::Plus, &b[32..]); - let r_b8 = decompress_point(r_b8_bytes); - match r_b8 { - Result::Err(err) => return Err(err.to_string()), - Result::Ok(res) => Ok(Signature { - r_b8: res.clone(), - s: s, - }), - } -} - +// +// #[derive(Debug, Clone)] +// pub struct Signature { +// r_b8: Point, +// s: BigInt, +// } +// +// impl Signature { +// pub fn compress(&self) -> [u8; 64] { +// let mut b: Vec = Vec::new(); +// b.append(&mut self.r_b8.compress().to_vec()); +// let (_, s_bytes) = self.s.to_bytes_le(); +// let mut s_32bytes: [u8; 32] = [0; 32]; +// let len = min(s_bytes.len(), s_32bytes.len()); +// s_32bytes[..len].copy_from_slice(&s_bytes[..len]); +// b.append(&mut s_32bytes.to_vec()); +// let mut r: [u8; 64] = [0; 64]; +// r[..].copy_from_slice(&b[..]); +// r +// } +// } +// +// pub fn decompress_signature(b: &[u8; 64]) -> Result { +// let r_b8_bytes: [u8; 32] = *array_ref!(b[..32], 0, 32); +// let s: BigInt = BigInt::from_bytes_le(Sign::Plus, &b[32..]); +// let r_b8 = decompress_point(r_b8_bytes); +// match r_b8 { +// Result::Err(err) => return Err(err.to_string()), +// Result::Ok(res) => Ok(Signature { +// r_b8: res.clone(), +// s: s, +// }), +// } +// } +// pub struct PrivateKey { key: BigInt, } @@ -201,180 +275,180 @@ impl PrivateKey { Ok(pk.clone()) } - pub fn sign_mimc(&self, msg: BigInt) -> Result { - // https://tools.ietf.org/html/rfc8032#section-5.1.6 - let mut hasher = Blake2b::new(); - let (_, sk_bytes) = self.key.to_bytes_be(); - hasher.input(sk_bytes); - let mut h = hasher.result(); // h: hash(sk) - // s: h[32:64] - let s = GenericArray::::from_mut_slice(&mut h[32..64]); - let (_, msg_bytes) = msg.to_bytes_be(); - let r_bytes = utils::concatenate_arrays(s, &msg_bytes); - let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]); - r = utils::modulus(&r, &SUBORDER); - let r8: Point = B8.mul_scalar(&r)?; - let a = &self.public()?; - - let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg]; - let mimc7 = Mimc7::new(); - let hm = mimc7.hash(hm_input)?; - - let mut s = &self.key << 3; - s = hm * s; - s = r + s; - s = s % &SUBORDER.clone(); - - Ok(Signature { - r_b8: r8.clone(), - s: s, - }) - } - pub fn sign_poseidon(&self, msg: BigInt) -> Result { - // https://tools.ietf.org/html/rfc8032#section-5.1.6 - let mut hasher = Blake2b::new(); - let (_, sk_bytes) = self.key.to_bytes_be(); - hasher.input(sk_bytes); - let mut h = hasher.result(); // h: hash(sk) - // s: h[32:64] - let s = GenericArray::::from_mut_slice(&mut h[32..64]); - let (_, msg_bytes) = msg.to_bytes_be(); - let r_bytes = utils::concatenate_arrays(s, &msg_bytes); - let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]); - r = utils::modulus(&r, &SUBORDER); - let r8: Point = B8.mul_scalar(&r)?; - let a = &self.public()?; - - let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg]; - let poseidon = Poseidon::new(); - let hm = poseidon.hash(hm_input)?; - - let mut s = &self.key << 3; - s = hm * s; - s = r + s; - s = s % &SUBORDER.clone(); - - Ok(Signature { - r_b8: r8.clone(), - s: s, - }) - } - - pub fn sign_schnorr(&self, m: Vec) -> Result<(Point, BigInt), String> { - // random r - let mut rng = rand::thread_rng(); - let k = rng.gen_biguint(1024).to_bigint().unwrap(); - - // r = k·G - let r = B8.mul_scalar(&k)?; - - // h = H(x, r, m) - let pk = &self.public()?; - let h = schnorr_hash(&pk, m, &r)?; - - // s= k+x·h - let s = k + &self.key * &h; - Ok((r, s)) - } -} - -pub fn schnorr_hash(pk: &Point, m: Vec, c: &Point) -> Result { - let b: &mut Vec = &mut Vec::new(); - - // other option could be to do it without compressing the points, and concatenating x|y - b.append(&mut pk.compress().to_vec()); - b.append(&mut c.compress().to_vec()); - b.append(&mut m.clone()); - - let poseidon = Poseidon::new(); - let h = poseidon.hash_bytes(b.to_vec())?; - println!("h {:?}", h.to_string()); - Ok(h) -} - -pub fn verify_schnorr(pk: Point, m: Vec, r: Point, s: BigInt) -> Result { - // sG = s·G - let sg = B8.mul_scalar(&s)?; - - // r + h · x - let h = schnorr_hash(&pk, m, &r)?; - let pk_h = pk.mul_scalar(&h)?; - let right = r.add(&pk_h)?; - - Ok(sg.equals(right)) -} - -pub fn new_key() -> PrivateKey { - // https://tools.ietf.org/html/rfc8032#section-5.1.5 - let mut rng = rand::thread_rng(); - let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap(); - - let mut hasher = Blake2b::new(); - let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); - hasher.input(sk_raw_bytes); - let mut h = hasher.result(); - - h[0] = h[0] & 0xF8; - h[31] = h[31] & 0x7F; - h[31] = h[31] | 0x40; - - let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); + // pub fn sign_mimc(&self, msg: BigInt) -> Result { + // // https://tools.ietf.org/html/rfc8032#section-5.1.6 + // let mut hasher = Blake2b::new(); + // let (_, sk_bytes) = self.key.to_bytes_be(); + // hasher.input(sk_bytes); + // let mut h = hasher.result(); // h: hash(sk) + // // s: h[32:64] + // let s = GenericArray::::from_mut_slice(&mut h[32..64]); + // let (_, msg_bytes) = msg.to_bytes_be(); + // let r_bytes = utils::concatenate_arrays(s, &msg_bytes); + // let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]); + // r = utils::modulus(&r, &SUBORDER); + // let r8: Point = B8.mul_scalar(&r)?; + // let a = &self.public()?; + // + // let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg]; + // let mimc7 = Mimc7::new(); + // let hm = mimc7.hash(hm_input)?; + // + // let mut s = &self.key << 3; + // s = hm * s; + // s = r + s; + // s = s % &SUBORDER.clone(); + // + // Ok(Signature { + // r_b8: r8.clone(), + // s: s, + // }) + // } + // pub fn sign_poseidon(&self, msg: BigInt) -> Result { + // // https://tools.ietf.org/html/rfc8032#section-5.1.6 + // let mut hasher = Blake2b::new(); + // let (_, sk_bytes) = self.key.to_bytes_be(); + // hasher.input(sk_bytes); + // let mut h = hasher.result(); // h: hash(sk) + // // s: h[32:64] + // let s = GenericArray::::from_mut_slice(&mut h[32..64]); + // let (_, msg_bytes) = msg.to_bytes_be(); + // let r_bytes = utils::concatenate_arrays(s, &msg_bytes); + // let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]); + // r = utils::modulus(&r, &SUBORDER); + // let r8: Point = B8.mul_scalar(&r)?; + // let a = &self.public()?; + // + // let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg]; + // let poseidon = Poseidon::new(); + // let hm = poseidon.hash(hm_input)?; + // + // let mut s = &self.key << 3; + // s = hm * s; + // s = r + s; + // s = s % &SUBORDER.clone(); + // + // Ok(Signature { + // r_b8: r8.clone(), + // s: s, + // }) + // } - PrivateKey { key: sk } + // pub fn sign_schnorr(&self, m: Vec) -> Result<(Point, BigInt), String> { + // // random r + // let mut rng = rand::thread_rng(); + // let k = rng.gen_biguint(1024).to_bigint().unwrap(); + // + // // r = k·G + // let r = B8.mul_scalar(&k)?; + // + // // h = H(x, r, m) + // let pk = &self.public()?; + // let h = schnorr_hash(&pk, m, &r)?; + // + // // s= k+x·h + // let s = k + &self.key * &h; + // Ok((r, s)) + // } } -pub fn verify_mimc(pk: Point, sig: Signature, msg: BigInt) -> bool { - let hm_input = vec![ - sig.r_b8.x.clone(), - sig.r_b8.y.clone(), - pk.x.clone(), - pk.y.clone(), - msg, - ]; - let mimc7 = Mimc7::new(); - let hm = match mimc7.hash(hm_input) { - Result::Err(_) => return false, - Result::Ok(hm) => hm, - }; - let l = match B8.mul_scalar(&sig.s) { - Result::Err(_) => return false, - Result::Ok(l) => l, - }; - let r = match sig - .r_b8 - .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap()) - { - Result::Err(_) => return false, - Result::Ok(r) => r, - }; - l.equals(r) -} -pub fn verify_poseidon(pk: Point, sig: Signature, msg: BigInt) -> bool { - let hm_input = vec![ - sig.r_b8.x.clone(), - sig.r_b8.y.clone(), - pk.x.clone(), - pk.y.clone(), - msg, - ]; - let poseidon = Poseidon::new(); - let hm = match poseidon.hash(hm_input) { - Result::Err(_) => return false, - Result::Ok(hm) => hm, - }; - let l = match B8.mul_scalar(&sig.s) { - Result::Err(_) => return false, - Result::Ok(l) => l, - }; - let r = match sig - .r_b8 - .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap()) - { - Result::Err(_) => return false, - Result::Ok(r) => r, - }; - l.equals(r) -} +// pub fn schnorr_hash(pk: &Point, m: Vec, c: &Point) -> Result { +// let b: &mut Vec = &mut Vec::new(); +// +// // other option could be to do it without compressing the points, and concatenating x|y +// b.append(&mut pk.compress().to_vec()); +// b.append(&mut c.compress().to_vec()); +// b.append(&mut m.clone()); +// +// let poseidon = Poseidon::new(); +// let h = poseidon.hash_bytes(b.to_vec())?; +// println!("h {:?}", h.to_string()); +// Ok(h) +// } +// +// pub fn verify_schnorr(pk: Point, m: Vec, r: Point, s: BigInt) -> Result { +// // sG = s·G +// let sg = B8.mul_scalar(&s)?; +// +// // r + h · x +// let h = schnorr_hash(&pk, m, &r)?; +// let pk_h = pk.mul_scalar(&h)?; +// let right = r.add(&pk_h)?; +// +// Ok(sg.equals(right)) +// } + +// pub fn new_key() -> PrivateKey { +// // https://tools.ietf.org/html/rfc8032#section-5.1.5 +// let mut rng = rand::thread_rng(); +// let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap(); +// +// let mut hasher = Blake2b::new(); +// let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); +// hasher.input(sk_raw_bytes); +// let mut h = hasher.result(); +// +// h[0] = h[0] & 0xF8; +// h[31] = h[31] & 0x7F; +// h[31] = h[31] | 0x40; +// +// let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); +// +// PrivateKey { key: sk } +// } + +// pub fn verify_mimc(pk: Point, sig: Signature, msg: BigInt) -> bool { +// let hm_input = vec![ +// sig.r_b8.x.clone(), +// sig.r_b8.y.clone(), +// pk.x.clone(), +// pk.y.clone(), +// msg, +// ]; +// let mimc7 = Mimc7::new(); +// let hm = match mimc7.hash(hm_input) { +// Result::Err(_) => return false, +// Result::Ok(hm) => hm, +// }; +// let l = match B8.mul_scalar(&sig.s) { +// Result::Err(_) => return false, +// Result::Ok(l) => l, +// }; +// let r = match sig +// .r_b8 +// .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap()) +// { +// Result::Err(_) => return false, +// Result::Ok(r) => r, +// }; +// l.equals(r) +// } +// pub fn verify_poseidon(pk: Point, sig: Signature, msg: BigInt) -> bool { +// let hm_input = vec![ +// sig.r_b8.x.clone(), +// sig.r_b8.y.clone(), +// pk.x.clone(), +// pk.y.clone(), +// msg, +// ]; +// let poseidon = Poseidon::new(); +// let hm = match poseidon.hash(hm_input) { +// Result::Err(_) => return false, +// Result::Ok(hm) => hm, +// }; +// let l = match B8.mul_scalar(&sig.s) { +// Result::Err(_) => return false, +// Result::Ok(l) => l, +// }; +// let r = match sig +// .r_b8 +// .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap()) +// { +// Result::Err(_) => return false, +// Result::Ok(r) => r, +// }; +// l.equals(r) +// } #[cfg(test)] mod tests { @@ -385,101 +459,114 @@ mod tests { #[test] fn test_add_same_point() { let p: Point = Point { - x: BigInt::parse_bytes( - b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - 10, + x: Fr::from_str( + "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) .unwrap(), - y: BigInt::parse_bytes( - b"2626589144620713026669568689430873010625803728049924121243784502389097019475", - 10, + y: Fr::from_str( + "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), + z: Fr::one(), }; let q: Point = Point { - x: BigInt::parse_bytes( - b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - 10, + x: Fr::from_str( + "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) .unwrap(), - y: BigInt::parse_bytes( - b"2626589144620713026669568689430873010625803728049924121243784502389097019475", - 10, + y: Fr::from_str( + "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), + z: Fr::one(), }; - let res = p.add(&q).unwrap(); + let res = p.add(&q).unwrap().affine(); assert_eq!( - res.x.to_string(), - "6890855772600357754907169075114257697580319025794532037257385534741338397365" + res.x, + Fr::from_str( + "6890855772600357754907169075114257697580319025794532037257385534741338397365" + ) + .unwrap() ); assert_eq!( - res.y.to_string(), - "4338620300185947561074059802482547481416142213883829469920100239455078257889" + res.y, + Fr::from_str( + "4338620300185947561074059802482547481416142213883829469920100239455078257889" + ) + .unwrap() ); } #[test] fn test_add_different_points() { let p: Point = Point { - x: BigInt::parse_bytes( - b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - 10, + x: Fr::from_str( + "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) .unwrap(), - y: BigInt::parse_bytes( - b"2626589144620713026669568689430873010625803728049924121243784502389097019475", - 10, + y: Fr::from_str( + "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), + z: Fr::one(), }; let q: Point = Point { - x: BigInt::parse_bytes( - b"16540640123574156134436876038791482806971768689494387082833631921987005038935", - 10, + x: Fr::from_str( + "16540640123574156134436876038791482806971768689494387082833631921987005038935", ) .unwrap(), - y: BigInt::parse_bytes( - b"20819045374670962167435360035096875258406992893633759881276124905556507972311", - 10, + y: Fr::from_str( + "20819045374670962167435360035096875258406992893633759881276124905556507972311", ) .unwrap(), + z: Fr::one(), }; - let res = p.add(&q).unwrap(); + let res = p.add(&q).unwrap().affine(); assert_eq!( - res.x.to_string(), - "7916061937171219682591368294088513039687205273691143098332585753343424131937" + res.x, + Fr::from_str( + "7916061937171219682591368294088513039687205273691143098332585753343424131937" + ) + .unwrap() ); assert_eq!( - res.y.to_string(), - "14035240266687799601661095864649209771790948434046947201833777492504781204499" + res.y, + Fr::from_str( + "14035240266687799601661095864649209771790948434046947201833777492504781204499" + ) + .unwrap() ); } #[test] fn test_mul_scalar() { let p: Point = Point { - x: BigInt::parse_bytes( - b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - 10, + x: Fr::from_str( + "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) .unwrap(), - y: BigInt::parse_bytes( - b"2626589144620713026669568689430873010625803728049924121243784502389097019475", - 10, + y: Fr::from_str( + "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), + z: Fr::one(), }; - let res_m = p.mul_scalar(&3.to_bigint().unwrap()).unwrap(); + let res_m = p.mul_scalar(&3.to_bigint().unwrap()).unwrap().affine(); let res_a = p.add(&p).unwrap(); - let res_a = res_a.add(&p).unwrap(); + let res_a = res_a.add(&p).unwrap().affine(); assert_eq!(res_m.x, res_a.x); assert_eq!( - res_m.x.to_string(), - "19372461775513343691590086534037741906533799473648040012278229434133483800898" + res_m.x, + Fr::from_str( + "19372461775513343691590086534037741906533799473648040012278229434133483800898" + ) + .unwrap() ); assert_eq!( - res_m.y.to_string(), - "9458658722007214007257525444427903161243386465067105737478306991484593958249" + res_m.y, + Fr::from_str( + "9458658722007214007257525444427903161243386465067105737478306991484593958249" + ) + .unwrap() ); let n = BigInt::parse_bytes( @@ -487,14 +574,20 @@ mod tests { 10, ) .unwrap(); - let res2 = p.mul_scalar(&n).unwrap(); + let res2 = p.mul_scalar(&n).unwrap().affine(); assert_eq!( - res2.x.to_string(), - "17070357974431721403481313912716834497662307308519659060910483826664480189605" + res2.x, + Fr::from_str( + "17070357974431721403481313912716834497662307308519659060910483826664480189605" + ) + .unwrap() ); assert_eq!( - res2.y.to_string(), - "4014745322800118607127020275658861516666525056516280575712425373174125159339" + res2.y, + Fr::from_str( + "4014745322800118607127020275658861516666525056516280575712425373174125159339" + ) + .unwrap() ); } @@ -517,39 +610,39 @@ mod tests { // let v = verify_mimc(pk, sig, msg); // assert_eq!(v, true); // } - #[test] - fn test_new_key_sign_verify_poseidon_0() { - let sk = new_key(); - let pk = sk.public().unwrap(); - let msg = 5.to_bigint().unwrap(); - let sig = sk.sign_poseidon(msg.clone()).unwrap(); - let v = verify_poseidon(pk, sig, msg); - assert_eq!(v, true); - } - - #[test] - fn test_new_key_sign_verify_poseidon_1() { - let sk = new_key(); - let pk = sk.public().unwrap(); - let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); - let sig = sk.sign_poseidon(msg.clone()).unwrap(); - let v = verify_poseidon(pk, sig, msg); - assert_eq!(v, true); - } + // #[test] + // fn test_new_key_sign_verify_poseidon_0() { + // let sk = new_key(); + // let pk = sk.public().unwrap(); + // let msg = 5.to_bigint().unwrap(); + // let sig = sk.sign_poseidon(msg.clone()).unwrap(); + // let v = verify_poseidon(pk, sig, msg); + // assert_eq!(v, true); + // } + // + // #[test] + // fn test_new_key_sign_verify_poseidon_1() { + // let sk = new_key(); + // let pk = sk.public().unwrap(); + // let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); + // let sig = sk.sign_poseidon(msg.clone()).unwrap(); + // let v = verify_poseidon(pk, sig, msg); + // assert_eq!(v, true); + // } + // #[test] fn test_point_compress_decompress() { let p: Point = Point { - x: BigInt::parse_bytes( - b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - 10, + x: Fr::from_str( + "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) .unwrap(), - y: BigInt::parse_bytes( - b"2626589144620713026669568689430873010625803728049924121243784502389097019475", - 10, + y: Fr::from_str( + "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), + z: Fr::one(), }; let p_comp = p.compress(); assert_eq!( @@ -575,7 +668,9 @@ mod tests { .unwrap(); let mut e_px_bytes: [u8; 32] = [0; 32]; e_px_bytes.copy_from_slice(&expected_px_raw); - let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes); + // let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes); + let expected_px: Fr = + Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap(); assert_eq!(&p.x, &expected_px); } @@ -593,33 +688,36 @@ mod tests { .unwrap(); let mut e_px_bytes: [u8; 32] = [0; 32]; e_px_bytes.copy_from_slice(&expected_px_raw); - let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes); + // let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes); + let expected_px: Fr = + Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap(); assert_eq!(&p.x, &expected_px); } - // #[test] - // fn test_point_decompress_loop() { - // for _ in 0..5 { - // let mut rng = rand::thread_rng(); - // let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap(); - // let mut hasher = Blake2b::new(); - // let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); - // hasher.input(sk_raw_bytes); - // let mut h = hasher.result(); - // - // h[0] = h[0] & 0xF8; - // h[31] = h[31] & 0x7F; - // h[31] = h[31] | 0x40; - // - // let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); - // let point = B8.mul_scalar(&sk).unwrap(); - // let cmp_point = point.compress(); - // let dcmp_point = decompress_point(cmp_point).unwrap(); - // - // assert_eq!(&point.x, &dcmp_point.x); - // assert_eq!(&point.y, &dcmp_point.y); - // } - // } + #[test] + fn test_point_decompress_loop() { + for _ in 0..5 { + let random_bytes = rand::thread_rng().gen::<[u8; 32]>(); + let sk_raw: BigInt = BigInt::from_bytes_le(Sign::Plus, &random_bytes[..]); + let mut hasher = Blake2b::new(); + let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); + hasher.input(sk_raw_bytes); + let mut h = hasher.result(); + + h[0] = h[0] & 0xF8; + h[31] = h[31] & 0x7F; + h[31] = h[31] | 0x40; + + let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); + let point = B8.mul_scalar(&sk).unwrap(); + let cmp_point = point.compress(); + let dcmp_point = decompress_point(cmp_point).unwrap().affine(); + let point_affine = point.affine(); + + assert_eq!(&point_affine.x, &dcmp_point.x); + assert_eq!(&point_affine.y, &dcmp_point.y); + } + } // #[test] // fn test_signature_compress_decompress() { @@ -642,17 +740,17 @@ mod tests { // } // } - #[test] - fn test_schnorr_signature() { - let sk = new_key(); - let pk = sk.public().unwrap(); - - let msg: Vec = ("123456".to_owned() + &1.to_string()).as_bytes().to_vec(); - let (s, e) = sk.sign_schnorr(msg.clone()).unwrap(); - println!("s {:?}", s.x.to_string()); - println!("s {:?}", s.y.to_string()); - println!("e {:?}", e.to_string()); - let verification = verify_schnorr(pk, msg, s, e).unwrap(); - assert_eq!(true, verification); - } + // #[test] + // fn test_schnorr_signature() { + // let sk = new_key(); + // let pk = sk.public().unwrap(); + // + // let msg: Vec = ("123456".to_owned() + &1.to_string()).as_bytes().to_vec(); + // let (s, e) = sk.sign_schnorr(msg.clone()).unwrap(); + // println!("s {:?}", s.x.to_string()); + // println!("s {:?}", s.y.to_string()); + // println!("e {:?}", e.to_string()); + // let verification = verify_schnorr(pk, msg, s, e).unwrap(); + // assert_eq!(true, verification); + // } } From 04d20b9e05aece18e4f462e1e66235f25c4de696 Mon Sep 17 00:00:00 2001 From: arnaucube Date: Sun, 2 Aug 2020 16:23:40 +0200 Subject: [PATCH 3/4] Update sign&verify (poseidon) to last optimization (On a Intel(R) Core(TM) i7-8705G CPU @ 3.10GHz, with 32 GB of RAM) - before: ``` sign_poseidon time: [383.01 ms 384.46 ms 385.98 ms] verify_poseidon time: [250.56 ms 251.46 ms 252.43 ms] ``` - current: ``` sign_poseidon time: [973.38 us 973.83 us 974.41 us] verify_poseidon time: [835.34 us 839.94 us 845.29 us] ``` sign_poseidon: `394x` improvement verify_poseidon: `300x` improvement --- Cargo.toml | 3 +- benches/bench_babyjubjub.rs | 49 ++--- src/lib.rs | 414 +++++++++++++++++++----------------- 3 files changed, 236 insertions(+), 230 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index dbcd6ef..3f0caeb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ readme = "README.md" [dependencies] ff = {package="ff_ce" , version="0.11", features = ["derive"]} rand = "0.4" +rand6 = {package="rand", version="0.6.5"} num = "0.2.0" num-bigint = {version = "0.2.2", features = ["rand"]} num-traits = "0.2.8" @@ -19,7 +20,7 @@ generic-array = "0.13.2" tiny-keccak = "1.5" rustc-hex = "1.0.0" mimc-rs = "0.0.2" -poseidon-rs = "0.0.1" +poseidon-rs = "0.0.3" arrayref = "0.3.5" lazy_static = "1.4.0" diff --git a/benches/bench_babyjubjub.rs b/benches/bench_babyjubjub.rs index 38fda56..1583e12 100644 --- a/benches/bench_babyjubjub.rs +++ b/benches/bench_babyjubjub.rs @@ -7,20 +7,11 @@ use ff::*; extern crate num; extern crate num_bigint; -use num_bigint::BigInt; +use num_bigint::{BigInt, ToBigInt}; use babyjubjub_rs::{utils, Point}; fn criterion_benchmark(c: &mut Criterion) { - // let x: BigInt = BigInt::parse_bytes( - // b"17777552123799933955779906779655732241715742912184938656739573121738514868268", - // 10, - // ) - // .unwrap(); - // c.bench_function("modulus", |b| { - // b.iter(|| utils::modulus(&x, &babyjubjub_rs::Q)) - // }); - let p: Point = Point { x: babyjubjub_rs::Fr::from_str( "17777552123799933955779906779655732241715742912184938656739573121738514868268", @@ -30,11 +21,13 @@ fn criterion_benchmark(c: &mut Criterion) { "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), - z: babyjubjub_rs::Fr::one(), }; let q = p.clone(); - c.bench_function("add", |b| b.iter(|| p.add(&q))); + let p_projective = p.projective(); + let q_projective = q.projective(); + + c.bench_function("add", |b| b.iter(|| p_projective.add(&q_projective))); let r: BigInt = BigInt::parse_bytes(b"3", 10).unwrap(); c.bench_function("mul_scalar_small", |b| b.iter(|| p.mul_scalar(&r))); let r: BigInt = BigInt::parse_bytes( @@ -44,22 +37,22 @@ fn criterion_benchmark(c: &mut Criterion) { .unwrap(); c.bench_function("mul_scalar", |b| b.iter(|| p.mul_scalar(&r))); - // c.bench_function("compress", |b| b.iter(|| p.compress())); - // let p_comp = p.compress(); - // c.bench_function("decompress", |b| { - // b.iter(|| babyjubjub_rs::decompress_point(p_comp)) - // }); - - // let sk = babyjubjub_rs::new_key(); - // let pk = sk.public().unwrap(); - // let msg = 5.to_bigint().unwrap(); - // c.bench_function("sign_poseidon", |b| { - // b.iter(|| sk.sign_poseidon(msg.clone())) - // }); - // let sig = sk.sign_poseidon(msg.clone()).unwrap(); - // c.bench_function("verify_poseidon", |b| { - // b.iter(|| babyjubjub_rs::verify_poseidon(pk.clone(), sig.clone(), msg.clone())) - // }); + c.bench_function("point compress", |b| b.iter(|| p.compress())); + let p_comp = p.compress(); + c.bench_function("point decompress", |b| { + b.iter(|| babyjubjub_rs::decompress_point(p_comp)) + }); + + let sk = babyjubjub_rs::new_key(); + let pk = sk.public().unwrap(); + let msg = 5.to_bigint().unwrap(); + c.bench_function("sign_poseidon", |b| { + b.iter(|| sk.sign_poseidon(msg.clone())) + }); + let sig = sk.sign_poseidon(msg.clone()).unwrap(); + c.bench_function("verify_poseidon", |b| { + b.iter(|| babyjubjub_rs::verify_poseidon(pk.clone(), sig.clone(), msg.clone())) + }); } criterion_group!(benches, criterion_benchmark); diff --git a/src/lib.rs b/src/lib.rs index dbb3a94..ca76297 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,10 +3,8 @@ extern crate rand; extern crate ff; use ff::*; -#[derive(PrimeField)] -#[PrimeFieldModulus = "21888242871839275222246405745257275088548364400416034343698204186575808495617"] -#[PrimeFieldGenerator = "7"] -pub struct Fr(FrRepr); +use poseidon_rs::Poseidon; +pub type Fr = poseidon_rs::Fr; // alias #[macro_use] extern crate arrayref; @@ -16,11 +14,11 @@ extern crate num; extern crate num_bigint; extern crate num_traits; -use rand::Rng; +extern crate rand6; +use rand6::Rng; use blake2::{Blake2b, Digest}; use mimc_rs::Mimc7; -use poseidon_rs::Poseidon; use std::cmp::min; use num_bigint::{BigInt, RandBigInt, RandomBits, Sign, ToBigInt}; @@ -55,35 +53,37 @@ lazy_static! { "16950150798460657717958625567821834550301663161624707787222815936182638968203", ) .unwrap(), - z: Fr::one(), + // z: Fr::one(), }; static ref ORDER: Fr = Fr::from_str( "21888242871839275222246405745257275088614511777268538073601725287587578984328", ) .unwrap(); - // SUBORDER = ORDER >> 3 - static ref SUBORDER: Fr = Fr::from_str( - "i2736030358979909402780800718157159386076813972158567259200215660948447373041", - ) - .unwrap(); -} -pub struct PointAffine { - pub x: Fr, - pub y: Fr, + // SUBORDER = ORDER >> 3 + // static ref SUBORDER: Fr = Fr::from_str( + // "i2736030358979909402780800718157159386076813972158567259200215660948447373041", + // ) + // .unwrap(); + static ref SUBORDER: BigInt = &BigInt::parse_bytes( + b"21888242871839275222246405745257275088614511777268538073601725287587578984328", + 10, + ) + .unwrap() + >> 3; } #[derive(Clone, Debug)] -pub struct Point { +pub struct PointProjective { pub x: Fr, pub y: Fr, pub z: Fr, } -impl Point { - pub fn affine(&self) -> PointAffine { +impl PointProjective { + pub fn affine(&self) -> Point { if self.z.is_zero() { - return PointAffine { + return Point { x: Fr::zero(), y: Fr::zero(), }; @@ -95,20 +95,12 @@ impl Point { let mut y = self.y; y.mul_assign(&zinv); - PointAffine { + Point { x: x.clone(), y: y.clone(), } } - pub fn from_affine(p: PointAffine) -> Point { - Point { - x: p.x.clone(), - y: p.y.clone(), - z: Fr::one(), - } - } - - pub fn add(&self, q: &Point) -> Result { + pub fn add(&self, q: &PointProjective) -> Result { // add-2008-bbjlp https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp let mut a = self.z; a.mul_assign(&q.z); @@ -146,20 +138,36 @@ impl Point { let mut z3 = f; z3.mul_assign(&g); - Ok(Point { + Ok(PointProjective { x: x3.clone(), y: y3.clone(), z: z3.clone(), }) } +} + +#[derive(Clone, Debug)] +pub struct Point { + pub x: Fr, + pub y: Fr, +} + +impl Point { + pub fn projective(&self) -> PointProjective { + PointProjective { + x: self.x.clone(), + y: self.y.clone(), + z: Fr::one(), + } + } pub fn mul_scalar(&self, n: &BigInt) -> Result { - let mut r: Point = Point { + let mut r: PointProjective = PointProjective { x: Fr::zero(), y: Fr::one(), z: Fr::one(), }; - let mut exp: Point = self.clone(); + let mut exp: PointProjective = self.projective(); let (_, b) = n.to_bytes_le(); for i in 0..n.bits() { if test_bit(&b, i) { @@ -167,11 +175,11 @@ impl Point { } exp = exp.add(&exp)?; } - Ok(r) + Ok(r.affine()) } pub fn compress(&self) -> [u8; 32] { - let p = &self.affine(); + let p = &self; let mut r: [u8; 32] = [0; 32]; let x_big = BigInt::parse_bytes(to_hex(&p.x).as_bytes(), 16).unwrap(); let y_big = BigInt::parse_bytes(to_hex(&p.y).as_bytes(), 16).unwrap(); @@ -227,43 +235,43 @@ pub fn decompress_point(bb: [u8; 32]) -> Result { x = utils::modulus(&x, &Q); let x_fr: Fr = Fr::from_str(&x.to_string()).unwrap(); let y_fr: Fr = Fr::from_str(&y.to_string()).unwrap(); - Ok(Point::from_affine(PointAffine { x: x_fr, y: y_fr })) + Ok(Point { x: x_fr, y: y_fr }) } -// -// #[derive(Debug, Clone)] -// pub struct Signature { -// r_b8: Point, -// s: BigInt, -// } -// -// impl Signature { -// pub fn compress(&self) -> [u8; 64] { -// let mut b: Vec = Vec::new(); -// b.append(&mut self.r_b8.compress().to_vec()); -// let (_, s_bytes) = self.s.to_bytes_le(); -// let mut s_32bytes: [u8; 32] = [0; 32]; -// let len = min(s_bytes.len(), s_32bytes.len()); -// s_32bytes[..len].copy_from_slice(&s_bytes[..len]); -// b.append(&mut s_32bytes.to_vec()); -// let mut r: [u8; 64] = [0; 64]; -// r[..].copy_from_slice(&b[..]); -// r -// } -// } -// -// pub fn decompress_signature(b: &[u8; 64]) -> Result { -// let r_b8_bytes: [u8; 32] = *array_ref!(b[..32], 0, 32); -// let s: BigInt = BigInt::from_bytes_le(Sign::Plus, &b[32..]); -// let r_b8 = decompress_point(r_b8_bytes); -// match r_b8 { -// Result::Err(err) => return Err(err.to_string()), -// Result::Ok(res) => Ok(Signature { -// r_b8: res.clone(), -// s: s, -// }), -// } -// } -// + +#[derive(Debug, Clone)] +pub struct Signature { + r_b8: Point, + s: BigInt, +} + +impl Signature { + pub fn compress(&self) -> [u8; 64] { + let mut b: Vec = Vec::new(); + b.append(&mut self.r_b8.compress().to_vec()); + let (_, s_bytes) = self.s.to_bytes_le(); + let mut s_32bytes: [u8; 32] = [0; 32]; + let len = min(s_bytes.len(), s_32bytes.len()); + s_32bytes[..len].copy_from_slice(&s_bytes[..len]); + b.append(&mut s_32bytes.to_vec()); + let mut r: [u8; 64] = [0; 64]; + r[..].copy_from_slice(&b[..]); + r + } +} + +pub fn decompress_signature(b: &[u8; 64]) -> Result { + let r_b8_bytes: [u8; 32] = *array_ref!(b[..32], 0, 32); + let s: BigInt = BigInt::from_bytes_le(Sign::Plus, &b[32..]); + let r_b8 = decompress_point(r_b8_bytes); + match r_b8 { + Result::Err(err) => return Err(err.to_string()), + Result::Ok(res) => Ok(Signature { + r_b8: res.clone(), + s: s, + }), + } +} + pub struct PrivateKey { key: BigInt, } @@ -304,35 +312,39 @@ impl PrivateKey { // s: s, // }) // } - // pub fn sign_poseidon(&self, msg: BigInt) -> Result { - // // https://tools.ietf.org/html/rfc8032#section-5.1.6 - // let mut hasher = Blake2b::new(); - // let (_, sk_bytes) = self.key.to_bytes_be(); - // hasher.input(sk_bytes); - // let mut h = hasher.result(); // h: hash(sk) - // // s: h[32:64] - // let s = GenericArray::::from_mut_slice(&mut h[32..64]); - // let (_, msg_bytes) = msg.to_bytes_be(); - // let r_bytes = utils::concatenate_arrays(s, &msg_bytes); - // let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]); - // r = utils::modulus(&r, &SUBORDER); - // let r8: Point = B8.mul_scalar(&r)?; - // let a = &self.public()?; - // - // let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg]; - // let poseidon = Poseidon::new(); - // let hm = poseidon.hash(hm_input)?; - // - // let mut s = &self.key << 3; - // s = hm * s; - // s = r + s; - // s = s % &SUBORDER.clone(); - // - // Ok(Signature { - // r_b8: r8.clone(), - // s: s, - // }) - // } + + pub fn sign_poseidon(&self, msg: BigInt) -> Result { + // https://tools.ietf.org/html/rfc8032#section-5.1.6 + let mut hasher = Blake2b::new(); + let (_, sk_bytes) = self.key.to_bytes_be(); + hasher.input(sk_bytes); + let mut h = hasher.result(); // h: hash(sk) + // s: h[32:64] + let (_, msg_bytes) = msg.to_bytes_be(); + let msgFr: Fr = Fr::from_str(&msg.to_string()).unwrap(); + + let s = GenericArray::::from_mut_slice(&mut h[32..64]); + let r_bytes = utils::concatenate_arrays(s, &msg_bytes); + let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]); + r = utils::modulus(&r, &SUBORDER); + let r8: Point = B8.mul_scalar(&r)?; + let a = &self.public()?; + + let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msgFr]; + let poseidon = Poseidon::new(); + let hm = poseidon.hash(hm_input)?; + + let mut s = &self.key << 3; + let hmB = BigInt::parse_bytes(to_hex(&hm).as_bytes(), 16).unwrap(); + s = hmB * s; + s = r + s; + s = s % &SUBORDER.clone(); + + Ok(Signature { + r_b8: r8.clone(), + s: s, + }) + } // pub fn sign_schnorr(&self, m: Vec) -> Result<(Point, BigInt), String> { // // random r @@ -378,24 +390,24 @@ impl PrivateKey { // Ok(sg.equals(right)) // } -// pub fn new_key() -> PrivateKey { -// // https://tools.ietf.org/html/rfc8032#section-5.1.5 -// let mut rng = rand::thread_rng(); -// let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap(); -// -// let mut hasher = Blake2b::new(); -// let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); -// hasher.input(sk_raw_bytes); -// let mut h = hasher.result(); -// -// h[0] = h[0] & 0xF8; -// h[31] = h[31] & 0x7F; -// h[31] = h[31] | 0x40; -// -// let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); -// -// PrivateKey { key: sk } -// } +pub fn new_key() -> PrivateKey { + // https://tools.ietf.org/html/rfc8032#section-5.1.5 + let mut rng = rand6::thread_rng(); + let sk_raw = rng.gen_biguint(1024).to_bigint().unwrap(); + + let mut hasher = Blake2b::new(); + let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); + hasher.input(sk_raw_bytes); + let mut h = hasher.result(); + + h[0] = h[0] & 0xF8; + h[31] = h[31] & 0x7F; + h[31] = h[31] | 0x40; + + let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); + + PrivateKey { key: sk } +} // pub fn verify_mimc(pk: Point, sig: Signature, msg: BigInt) -> bool { // let hm_input = vec![ @@ -423,32 +435,37 @@ impl PrivateKey { // }; // l.equals(r) // } -// pub fn verify_poseidon(pk: Point, sig: Signature, msg: BigInt) -> bool { -// let hm_input = vec![ -// sig.r_b8.x.clone(), -// sig.r_b8.y.clone(), -// pk.x.clone(), -// pk.y.clone(), -// msg, -// ]; -// let poseidon = Poseidon::new(); -// let hm = match poseidon.hash(hm_input) { -// Result::Err(_) => return false, -// Result::Ok(hm) => hm, -// }; -// let l = match B8.mul_scalar(&sig.s) { -// Result::Err(_) => return false, -// Result::Ok(l) => l, -// }; -// let r = match sig -// .r_b8 -// .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap()) -// { -// Result::Err(_) => return false, -// Result::Ok(r) => r, -// }; -// l.equals(r) -// } + +pub fn verify_poseidon(pk: Point, sig: Signature, msg: BigInt) -> bool { + let (_, msg_bytes) = msg.to_bytes_be(); + let msgFr: Fr = Fr::from_str(&msg.to_string()).unwrap(); + let hm_input = vec![ + sig.r_b8.x.clone(), + sig.r_b8.y.clone(), + pk.x.clone(), + pk.y.clone(), + msgFr, + ]; + let poseidon = Poseidon::new(); + let hm = match poseidon.hash(hm_input) { + Result::Err(_) => return false, + Result::Ok(hm) => hm, + }; + let l = match B8.mul_scalar(&sig.s) { + Result::Err(_) => return false, + Result::Ok(l) => l, + }; + let hmB = BigInt::parse_bytes(to_hex(&hm).as_bytes(), 16).unwrap(); + let r = match sig.r_b8.projective().add( + &pk.mul_scalar(&(8.to_bigint().unwrap() * hmB)) + .unwrap() + .projective(), + ) { + Result::Err(_) => return false, + Result::Ok(r) => r, + }; + l.equals(r.affine()) +} #[cfg(test)] mod tests { @@ -458,7 +475,7 @@ mod tests { #[test] fn test_add_same_point() { - let p: Point = Point { + let p: PointProjective = PointProjective { x: Fr::from_str( "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) @@ -469,7 +486,7 @@ mod tests { .unwrap(), z: Fr::one(), }; - let q: Point = Point { + let q: PointProjective = PointProjective { x: Fr::from_str( "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) @@ -498,7 +515,7 @@ mod tests { } #[test] fn test_add_different_points() { - let p: Point = Point { + let p: PointProjective = PointProjective { x: Fr::from_str( "17777552123799933955779906779655732241715742912184938656739573121738514868268", ) @@ -509,7 +526,7 @@ mod tests { .unwrap(), z: Fr::one(), }; - let q: Point = Point { + let q: PointProjective = PointProjective { x: Fr::from_str( "16540640123574156134436876038791482806971768689494387082833631921987005038935", ) @@ -548,11 +565,10 @@ mod tests { "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), - z: Fr::one(), }; - let res_m = p.mul_scalar(&3.to_bigint().unwrap()).unwrap().affine(); - let res_a = p.add(&p).unwrap(); - let res_a = res_a.add(&p).unwrap().affine(); + let res_m = p.mul_scalar(&3.to_bigint().unwrap()).unwrap(); + let res_a = p.projective().add(&p.projective()).unwrap(); + let res_a = res_a.add(&p.projective()).unwrap().affine(); assert_eq!(res_m.x, res_a.x); assert_eq!( res_m.x, @@ -574,7 +590,7 @@ mod tests { 10, ) .unwrap(); - let res2 = p.mul_scalar(&n).unwrap().affine(); + let res2 = p.mul_scalar(&n).unwrap(); assert_eq!( res2.x, Fr::from_str( @@ -611,26 +627,26 @@ mod tests { // assert_eq!(v, true); // } - // #[test] - // fn test_new_key_sign_verify_poseidon_0() { - // let sk = new_key(); - // let pk = sk.public().unwrap(); - // let msg = 5.to_bigint().unwrap(); - // let sig = sk.sign_poseidon(msg.clone()).unwrap(); - // let v = verify_poseidon(pk, sig, msg); - // assert_eq!(v, true); - // } - // - // #[test] - // fn test_new_key_sign_verify_poseidon_1() { - // let sk = new_key(); - // let pk = sk.public().unwrap(); - // let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); - // let sig = sk.sign_poseidon(msg.clone()).unwrap(); - // let v = verify_poseidon(pk, sig, msg); - // assert_eq!(v, true); - // } - // + #[test] + fn test_new_key_sign_verify_poseidon_0() { + let sk = new_key(); + let pk = sk.public().unwrap(); + let msg = 5.to_bigint().unwrap(); + let sig = sk.sign_poseidon(msg.clone()).unwrap(); + let v = verify_poseidon(pk, sig, msg); + assert_eq!(v, true); + } + + #[test] + fn test_new_key_sign_verify_poseidon_1() { + let sk = new_key(); + let pk = sk.public().unwrap(); + let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); + let sig = sk.sign_poseidon(msg.clone()).unwrap(); + let v = verify_poseidon(pk, sig, msg); + assert_eq!(v, true); + } + #[test] fn test_point_compress_decompress() { let p: Point = Point { @@ -642,7 +658,6 @@ mod tests { "2626589144620713026669568689430873010625803728049924121243784502389097019475", ) .unwrap(), - z: Fr::one(), }; let p_comp = p.compress(); assert_eq!( @@ -668,7 +683,6 @@ mod tests { .unwrap(); let mut e_px_bytes: [u8; 32] = [0; 32]; e_px_bytes.copy_from_slice(&expected_px_raw); - // let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes); let expected_px: Fr = Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap(); assert_eq!(&p.x, &expected_px); @@ -688,7 +702,6 @@ mod tests { .unwrap(); let mut e_px_bytes: [u8; 32] = [0; 32]; e_px_bytes.copy_from_slice(&expected_px_raw); - // let expected_px: BigInt = BigInt::from_bytes_le(Sign::Plus, &e_px_bytes); let expected_px: Fr = Fr::from_str(&BigInt::from_bytes_le(Sign::Plus, &e_px_bytes).to_string()).unwrap(); assert_eq!(&p.x, &expected_px); @@ -697,7 +710,7 @@ mod tests { #[test] fn test_point_decompress_loop() { for _ in 0..5 { - let random_bytes = rand::thread_rng().gen::<[u8; 32]>(); + let random_bytes = rand6::thread_rng().gen::<[u8; 32]>(); let sk_raw: BigInt = BigInt::from_bytes_le(Sign::Plus, &random_bytes[..]); let mut hasher = Blake2b::new(); let (_, sk_raw_bytes) = sk_raw.to_bytes_be(); @@ -711,34 +724,33 @@ mod tests { let sk = BigInt::from_bytes_le(Sign::Plus, &h[..]); let point = B8.mul_scalar(&sk).unwrap(); let cmp_point = point.compress(); - let dcmp_point = decompress_point(cmp_point).unwrap().affine(); - let point_affine = point.affine(); + let dcmp_point = decompress_point(cmp_point).unwrap(); - assert_eq!(&point_affine.x, &dcmp_point.x); - assert_eq!(&point_affine.y, &dcmp_point.y); + assert_eq!(&point.x, &dcmp_point.x); + assert_eq!(&point.y, &dcmp_point.y); } } - // #[test] - // fn test_signature_compress_decompress() { - // let sk = new_key(); - // let pk = sk.public().unwrap(); - // - // for i in 0..5 { - // let msg_raw = "123456".to_owned() + &i.to_string(); - // let msg = BigInt::parse_bytes(msg_raw.as_bytes(), 10).unwrap(); - // let sig = sk.sign_mimc(msg.clone()).unwrap(); - // - // let compressed_sig = sig.compress(); - // let decompressed_sig = decompress_signature(&compressed_sig).unwrap(); - // assert_eq!(&sig.r_b8.x, &decompressed_sig.r_b8.x); - // assert_eq!(&sig.r_b8.y, &decompressed_sig.r_b8.y); - // assert_eq!(&sig.s, &decompressed_sig.s); - // - // let v = verify_mimc(pk.clone(), decompressed_sig, msg); - // assert_eq!(v, true); - // } - // } + #[test] + fn test_signature_compress_decompress() { + let sk = new_key(); + let pk = sk.public().unwrap(); + + for i in 0..5 { + let msg_raw = "123456".to_owned() + &i.to_string(); + let msg = BigInt::parse_bytes(msg_raw.as_bytes(), 10).unwrap(); + let sig = sk.sign_poseidon(msg.clone()).unwrap(); + + let compressed_sig = sig.compress(); + let decompressed_sig = decompress_signature(&compressed_sig).unwrap(); + assert_eq!(&sig.r_b8.x, &decompressed_sig.r_b8.x); + assert_eq!(&sig.r_b8.y, &decompressed_sig.r_b8.y); + assert_eq!(&sig.s, &decompressed_sig.s); + + let v = verify_poseidon(pk.clone(), decompressed_sig, msg); + assert_eq!(v, true); + } + } // #[test] // fn test_schnorr_signature() { From 80d682ea931f94e45c4ad676b72d4584e0d2212f Mon Sep 17 00:00:00 2001 From: arnaucube Date: Sun, 2 Aug 2020 19:22:02 +0200 Subject: [PATCH 4/4] Update Schnorr to last changes, rm MiMC7 methods --- README.md | 7 +- benches/bench_babyjubjub.rs | 10 +- src/lib.rs | 192 +++++++++++++----------------------- 3 files changed, 79 insertions(+), 130 deletions(-) diff --git a/README.md b/README.md index d5dd137..2d29bbf 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,14 @@ # babyjubjub-rs [![Crates.io](https://img.shields.io/crates/v/babyjubjub-rs.svg)](https://crates.io/crates/babyjubjub-rs) [![Build Status](https://travis-ci.org/arnaucube/babyjubjub-rs.svg?branch=master)](https://travis-ci.org/arnaucube/babyjubjub-rs) -BabyJubJub elliptic curve implementation in Rust. A twisted edwards curve embedded in the curve of BN128. +BabyJubJub elliptic curve implementation in Rust. A twisted edwards curve embedded in the curve of BN128/BN256. BabyJubJub curve explanation: https://medium.com/zokrates/efficient-ecc-in-zksnarks-using-zokrates-bd9ae37b8186 Uses: -- MiMC7 hash function: https://github.com/arnaucube/mimc-rs - Poseidon hash function https://github.com/arnaucube/poseidon-rs -Compatible with the BabyJubJub Go implementation from https://github.com/iden3/go-iden3-crypto +Compatible with the BabyJubJub implementations in: +- Go, from https://github.com/iden3/go-iden3-crypto +- circom & javascript, from https://github.com/iden3/circomlib ## Warning Doing this in my free time to get familiar with Rust, **do not use in production**. diff --git a/benches/bench_babyjubjub.rs b/benches/bench_babyjubjub.rs index 1583e12..67218bb 100644 --- a/benches/bench_babyjubjub.rs +++ b/benches/bench_babyjubjub.rs @@ -46,12 +46,10 @@ fn criterion_benchmark(c: &mut Criterion) { let sk = babyjubjub_rs::new_key(); let pk = sk.public().unwrap(); let msg = 5.to_bigint().unwrap(); - c.bench_function("sign_poseidon", |b| { - b.iter(|| sk.sign_poseidon(msg.clone())) - }); - let sig = sk.sign_poseidon(msg.clone()).unwrap(); - c.bench_function("verify_poseidon", |b| { - b.iter(|| babyjubjub_rs::verify_poseidon(pk.clone(), sig.clone(), msg.clone())) + c.bench_function("sign", |b| b.iter(|| sk.sign(msg.clone()))); + let sig = sk.sign(msg.clone()).unwrap(); + c.bench_function("verify", |b| { + b.iter(|| babyjubjub_rs::verify(pk.clone(), sig.clone(), msg.clone())) }); } diff --git a/src/lib.rs b/src/lib.rs index ca76297..2d8e4ba 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +// WARNING still updating the code, it works, but is still in process the refactor. + extern crate rand; #[macro_use] extern crate ff; @@ -283,37 +285,10 @@ impl PrivateKey { Ok(pk.clone()) } - // pub fn sign_mimc(&self, msg: BigInt) -> Result { - // // https://tools.ietf.org/html/rfc8032#section-5.1.6 - // let mut hasher = Blake2b::new(); - // let (_, sk_bytes) = self.key.to_bytes_be(); - // hasher.input(sk_bytes); - // let mut h = hasher.result(); // h: hash(sk) - // // s: h[32:64] - // let s = GenericArray::::from_mut_slice(&mut h[32..64]); - // let (_, msg_bytes) = msg.to_bytes_be(); - // let r_bytes = utils::concatenate_arrays(s, &msg_bytes); - // let mut r = BigInt::from_bytes_be(Sign::Plus, &r_bytes[..]); - // r = utils::modulus(&r, &SUBORDER); - // let r8: Point = B8.mul_scalar(&r)?; - // let a = &self.public()?; - // - // let hm_input = vec![r8.x.clone(), r8.y.clone(), a.x.clone(), a.y.clone(), msg]; - // let mimc7 = Mimc7::new(); - // let hm = mimc7.hash(hm_input)?; - // - // let mut s = &self.key << 3; - // s = hm * s; - // s = r + s; - // s = s % &SUBORDER.clone(); - // - // Ok(Signature { - // r_b8: r8.clone(), - // s: s, - // }) - // } - - pub fn sign_poseidon(&self, msg: BigInt) -> Result { + pub fn sign(&self, msg: BigInt) -> Result { + if msg > Q.clone() { + return Err("msg outside the Finite Field".to_string()); + } // https://tools.ietf.org/html/rfc8032#section-5.1.6 let mut hasher = Blake2b::new(); let (_, sk_bytes) = self.key.to_bytes_be(); @@ -346,49 +321,48 @@ impl PrivateKey { }) } - // pub fn sign_schnorr(&self, m: Vec) -> Result<(Point, BigInt), String> { - // // random r - // let mut rng = rand::thread_rng(); - // let k = rng.gen_biguint(1024).to_bigint().unwrap(); - // - // // r = k·G - // let r = B8.mul_scalar(&k)?; - // - // // h = H(x, r, m) - // let pk = &self.public()?; - // let h = schnorr_hash(&pk, m, &r)?; - // - // // s= k+x·h - // let s = k + &self.key * &h; - // Ok((r, s)) - // } + pub fn sign_schnorr(&self, m: BigInt) -> Result<(Point, BigInt), String> { + // random r + let mut rng = rand6::thread_rng(); + let k = rng.gen_biguint(1024).to_bigint().unwrap(); + + // r = k·G + let r = B8.mul_scalar(&k)?; + + // h = H(x, r, m) + let pk = &self.public()?; + let h = schnorr_hash(&pk, m, &r)?; + + // s= k+x·h + let s = k + &self.key * &h; + Ok((r, s)) + } } -// pub fn schnorr_hash(pk: &Point, m: Vec, c: &Point) -> Result { -// let b: &mut Vec = &mut Vec::new(); -// -// // other option could be to do it without compressing the points, and concatenating x|y -// b.append(&mut pk.compress().to_vec()); -// b.append(&mut c.compress().to_vec()); -// b.append(&mut m.clone()); -// -// let poseidon = Poseidon::new(); -// let h = poseidon.hash_bytes(b.to_vec())?; -// println!("h {:?}", h.to_string()); -// Ok(h) -// } -// -// pub fn verify_schnorr(pk: Point, m: Vec, r: Point, s: BigInt) -> Result { -// // sG = s·G -// let sg = B8.mul_scalar(&s)?; -// -// // r + h · x -// let h = schnorr_hash(&pk, m, &r)?; -// let pk_h = pk.mul_scalar(&h)?; -// let right = r.add(&pk_h)?; -// -// Ok(sg.equals(right)) -// } +pub fn schnorr_hash(pk: &Point, msg: BigInt, c: &Point) -> Result { + if msg > Q.clone() { + return Err("msg outside the Finite Field".to_string()); + } + let msgFr: Fr = Fr::from_str(&msg.to_string()).unwrap(); + let hm_input = vec![pk.x.clone(), pk.y.clone(), c.x.clone(), c.y.clone(), msgFr]; + let poseidon = Poseidon::new(); + let h = poseidon.hash(hm_input)?; + println!("h {:?}", h.to_string()); + let hB = BigInt::parse_bytes(to_hex(&h).as_bytes(), 16).unwrap(); + Ok(hB) +} + +pub fn verify_schnorr(pk: Point, m: BigInt, r: Point, s: BigInt) -> Result { + // sG = s·G + let sg = B8.mul_scalar(&s)?; + + // r + h · x + let h = schnorr_hash(&pk, m, &r)?; + let pk_h = pk.mul_scalar(&h)?; + let right = r.projective().add(&pk_h.projective())?; + + Ok(sg.equals(right.affine())) +} pub fn new_key() -> PrivateKey { // https://tools.ietf.org/html/rfc8032#section-5.1.5 @@ -409,34 +383,10 @@ pub fn new_key() -> PrivateKey { PrivateKey { key: sk } } -// pub fn verify_mimc(pk: Point, sig: Signature, msg: BigInt) -> bool { -// let hm_input = vec![ -// sig.r_b8.x.clone(), -// sig.r_b8.y.clone(), -// pk.x.clone(), -// pk.y.clone(), -// msg, -// ]; -// let mimc7 = Mimc7::new(); -// let hm = match mimc7.hash(hm_input) { -// Result::Err(_) => return false, -// Result::Ok(hm) => hm, -// }; -// let l = match B8.mul_scalar(&sig.s) { -// Result::Err(_) => return false, -// Result::Ok(l) => l, -// }; -// let r = match sig -// .r_b8 -// .add(&pk.mul_scalar(&(8.to_bigint().unwrap() * hm)).unwrap()) -// { -// Result::Err(_) => return false, -// Result::Ok(r) => r, -// }; -// l.equals(r) -// } - -pub fn verify_poseidon(pk: Point, sig: Signature, msg: BigInt) -> bool { +pub fn verify(pk: Point, sig: Signature, msg: BigInt) -> bool { + if msg > Q.clone() { + return false; + } let (_, msg_bytes) = msg.to_bytes_be(); let msgFr: Fr = Fr::from_str(&msg.to_string()).unwrap(); let hm_input = vec![ @@ -628,22 +578,22 @@ mod tests { // } #[test] - fn test_new_key_sign_verify_poseidon_0() { + fn test_new_key_sign_verify_0() { let sk = new_key(); let pk = sk.public().unwrap(); let msg = 5.to_bigint().unwrap(); - let sig = sk.sign_poseidon(msg.clone()).unwrap(); - let v = verify_poseidon(pk, sig, msg); + let sig = sk.sign(msg.clone()).unwrap(); + let v = verify(pk, sig, msg); assert_eq!(v, true); } #[test] - fn test_new_key_sign_verify_poseidon_1() { + fn test_new_key_sign_verify_1() { let sk = new_key(); let pk = sk.public().unwrap(); let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); - let sig = sk.sign_poseidon(msg.clone()).unwrap(); - let v = verify_poseidon(pk, sig, msg); + let sig = sk.sign(msg.clone()).unwrap(); + let v = verify(pk, sig, msg); assert_eq!(v, true); } @@ -739,7 +689,7 @@ mod tests { for i in 0..5 { let msg_raw = "123456".to_owned() + &i.to_string(); let msg = BigInt::parse_bytes(msg_raw.as_bytes(), 10).unwrap(); - let sig = sk.sign_poseidon(msg.clone()).unwrap(); + let sig = sk.sign(msg.clone()).unwrap(); let compressed_sig = sig.compress(); let decompressed_sig = decompress_signature(&compressed_sig).unwrap(); @@ -747,22 +697,22 @@ mod tests { assert_eq!(&sig.r_b8.y, &decompressed_sig.r_b8.y); assert_eq!(&sig.s, &decompressed_sig.s); - let v = verify_poseidon(pk.clone(), decompressed_sig, msg); + let v = verify(pk.clone(), decompressed_sig, msg); assert_eq!(v, true); } } - // #[test] - // fn test_schnorr_signature() { - // let sk = new_key(); - // let pk = sk.public().unwrap(); - // - // let msg: Vec = ("123456".to_owned() + &1.to_string()).as_bytes().to_vec(); - // let (s, e) = sk.sign_schnorr(msg.clone()).unwrap(); - // println!("s {:?}", s.x.to_string()); - // println!("s {:?}", s.y.to_string()); - // println!("e {:?}", e.to_string()); - // let verification = verify_schnorr(pk, msg, s, e).unwrap(); - // assert_eq!(true, verification); - // } + #[test] + fn test_schnorr_signature() { + let sk = new_key(); + let pk = sk.public().unwrap(); + + let msg = BigInt::parse_bytes(b"123456789012345678901234567890", 10).unwrap(); + let (s, e) = sk.sign_schnorr(msg.clone()).unwrap(); + println!("s {:?}", s.x.to_string()); + println!("s {:?}", s.y.to_string()); + println!("e {:?}", e.to_string()); + let verification = verify_schnorr(pk, msg, s, e).unwrap(); + assert_eq!(true, verification); + } }