cs_mwc_bch/util/
hash160.rs

1use digest::{FixedOutput, Input};
2use hex;
3use ring::digest::{digest, SHA256};
4use ripemd160::{Digest, Ripemd160};
5use std::fmt;
6
7/// 160-bit hash for public key addresses
8#[derive(Default, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct Hash160(pub [u8; 20]);
10
11/// Hashes a data array once with SHA256 and again with RIPEMD160
12pub fn hash160(data: &[u8]) -> Hash160 {
13    let sha256 = digest(&SHA256, data);
14    let mut ripemd160 = Ripemd160::new();
15    ripemd160.process(sha256.as_ref());
16    let mut hash160 = [0; 20];
17    hash160.clone_from_slice(&ripemd160.fixed_result());
18    Hash160(hash160)
19}
20
21impl fmt::Debug for Hash160 {
22    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
23        write!(f, "{}", hex::encode(self.0))
24    }
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30    use hex;
31
32    #[test]
33    fn tohash160() {
34        let pubkey = "126999eabe3f84a3a9f5c09e87faab27484818a0ec1d67b94c9a02e40268499d98538cf770198550adfb9d1d473e5e926bb00e4c58baec1fb42ffa6069781003e4";
35        let pubkey = hex::decode(pubkey).unwrap();
36        assert!(hex::encode(hash160(&pubkey).0) == "3c231b5e624a42e99a87160c6e4231718a6d77c0");
37    }
38}