/
hex.go
51 lines (45 loc) · 1.06 KB
/
hex.go
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
package types
import (
"encoding/hex"
"errors"
"golang.org/x/crypto/sha3"
)
func HexAddress(a []byte) string {
if len(a) == 0 {
return ""
}
unchecksummed := hex.EncodeToString(a[:])
sha := sha3.NewLegacyKeccak256()
sha.Write([]byte(unchecksummed))
hash := sha.Sum(nil)
result := []byte(unchecksummed)
for i := 0; i < len(result); i++ {
hashByte := hash[i/2]
if i%2 == 0 {
hashByte = hashByte >> 4
} else {
hashByte &= 0xf
}
if result[i] > '9' && hashByte > 7 {
result[i] -= 32
}
}
return "0x" + string(result)
}
func HexEncode(b []byte) string {
enc := make([]byte, len(b)*2+2)
copy(enc, "0x")
hex.Encode(enc[2:], b)
return string(enc)
}
// Decode decodes a hex string with 0x prefix.
func HexDecode(input string) ([]byte, error) {
if !Has0xPrefix(input) {
return nil, errors.New("hex string must have 0x prefix")
}
return hex.DecodeString(input[2:])
}
// has0xPrefix validates str begins with '0x' or '0X'.
func Has0xPrefix(input string) bool {
return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
}