threshold_bls/hash/
mod.rs

1pub mod hasher;
2pub mod try_and_increment;
3use crate::curve::BLSError;
4
5/// Trait for hashing arbitrary data to a group element on an elliptic curve
6pub trait HashToCurve {
7    /// The type of the curve being used.
8    type Output;
9
10    /// Given a domain separator and a message, produces
11    /// a hash of them which is a curve point.
12    fn hash(&self, domain: &[u8], message: &[u8]) -> Result<Self::Output, BLSError>;
13}
14
15#[cfg(test)]
16mod test {
17
18    use super::{
19        hasher::{Hasher, Keccak256Hasher},
20        try_and_increment::TryAndIncrement,
21        *,
22    };
23    use ark_bn254::Parameters;
24    use ark_ec::{bn::BnParameters, models::SWModelParameters, ProjectiveCurve};
25    use ark_serialize::CanonicalSerialize;
26    use ethers_core::{types::U256, utils::hex};
27
28    #[test]
29    fn hash_to_curve_direct_g1() {
30        let h = Keccak256Hasher;
31        // hash_to_curve_test::<_, <Parameters as BnParameters>::G1Parameters>(h, b"hello");
32        hash_to_curve_test::<_, <Parameters as BnParameters>::G2Parameters>(h, b"hello01");
33        hash_to_curve_test::<_, <Parameters as BnParameters>::G2Parameters>(h, b"hello02");
34        hash_to_curve_test::<_, <Parameters as BnParameters>::G2Parameters>(h, b"hello03");
35        hash_to_curve_test::<_, <Parameters as BnParameters>::G2Parameters>(h, b"hello04");
36        hash_to_curve_test::<_, <Parameters as BnParameters>::G2Parameters>(h, b"hello05");
37    }
38
39    fn hash_to_curve_test<X: Hasher<Error = BLSError>, P: SWModelParameters>(h: X, input: &[u8]) {
40        let hasher = TryAndIncrement::<X, P>::new(&h);
41        let g = hasher.hash(&[], input).unwrap();
42
43        let mut xbytes = vec![];
44        g.into_affine().x.serialize(&mut xbytes).unwrap();
45        println!("{}", g);
46        let mut ybytes = vec![];
47        g.into_affine().y.serialize(&mut ybytes).unwrap();
48        print_point("x", &xbytes);
49        print_point("y", &ybytes);
50    }
51
52    fn print_point(xy: &str, bytes: &[u8]) {
53        let x1 = &mut bytes[..32].to_vec();
54        let x2 = &mut bytes[32..].to_vec();
55
56        x1.reverse();
57        x2.reverse();
58
59        println!("{}", xy);
60        // Hex
61        print!("{:?}", hex::encode(x1.clone()));
62        print!(" ");
63        println!("{:?}", hex::encode(x2.clone()));
64        // Dec
65        print!("{:?}", U256::from(&x1 as &[u8]));
66        print!(" ");
67        println!("{:?}", U256::from(&x2 as &[u8]));
68        println!("");
69    }
70}