1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::io::{self, Error, ErrorKind};
use ethereum_types::{Address, H256};
use ring::digest::{digest, SHA256};
use ripemd::{Digest, Ripemd160};
use secp256k1::{self, PublicKey};
use sha3::Keccak256;
use crate::ids::short;
use avalanche_utils::prefix;
pub fn hash_sha256_ripemd160<S>(pub_key_bytes: S) -> io::Result<Vec<u8>>
where
S: AsRef<[u8]>,
{
let digest_sha256 = digest(&SHA256, pub_key_bytes.as_ref());
let sha256_ripemd160 = Ripemd160::digest(&digest_sha256);
if sha256_ripemd160.len() != 20 {
return Err(Error::new(
ErrorKind::InvalidData,
format!(
"ripemd160 of sha256 must be 20-byte, got {}",
sha256_ripemd160.len()
),
));
}
Ok(sha256_ripemd160.to_vec())
}
pub fn to_short_bytes(public_key: &PublicKey) -> io::Result<Vec<u8>> {
let public_key_bytes_compressed = public_key.serialize();
hash_sha256_ripemd160(&public_key_bytes_compressed)
}
pub fn to_short(public_key: &PublicKey) -> io::Result<short::Id> {
let public_key_bytes_compressed = public_key.serialize();
short::Id::from_public_key_bytes(&public_key_bytes_compressed)
}
pub fn to_eth(public_key: &PublicKey) -> io::Result<String> {
let public_key_bytes_uncompressed = public_key.serialize_uncompressed();
let digest_h256 = keccak256(&public_key_bytes_uncompressed[1..]);
let digest_h256 = &digest_h256.0[12..];
let addr = Address::from_slice(digest_h256);
let addr_hex = hex::encode(addr);
let addr_eip55 = eth_checksum(&addr_hex);
Ok(prefix::prepend_0x(&addr_eip55))
}
fn keccak256(data: impl AsRef<[u8]>) -> H256 {
H256::from_slice(&Keccak256::digest(data.as_ref()))
}
fn eth_checksum(addr: &str) -> String {
let addr_lower_case = prefix::strip_0x(addr).to_lowercase();
let digest_h256 = keccak256(&addr_lower_case.as_bytes());
checksum_eip55(&addr_lower_case, &hex::encode(digest_h256))
}
fn checksum_eip55(addr: &str, addr_hash: &str) -> String {
let mut chksum = String::new();
for (c, hash_char) in addr.chars().zip(addr_hash.chars()) {
if hash_char.to_digit(16) >= Some(8) {
chksum.extend(c.to_uppercase());
} else {
chksum.push(c);
}
}
chksum
}