【区块链】Address

EoA

CA

Proxy

Token

NFT

Swap

EIP55

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
import (
"encoding/hex"
"errors"
"strconv"
"strings"

"golang.org/x/crypto/sha3"
)

func ToCheckSumAddress(address string) (string, error) {
if address == "" {
return "", errors.New("empty address")
}

if strings.HasPrefix(address, "0x") {
address = address[2:]
}

bytes, err := hex.DecodeString(address)
if err != nil {
return "", err
}

hash := calculateKeccak256([]byte(strings.ToLower(address)))
result := "0x"
for i, b := range bytes {
result += checksumByte(b>>4, hash[i]>>4)
result += checksumByte(b&0xF, hash[i]&0xF)
}

return result, nil
}

func checksumByte(addr, hash byte) string {
result := strconv.FormatUint(uint64(addr), 16)
if hash >= 8 {
return strings.ToUpper(result)
} else {
return result
}
}

func calculateKeccak256(addr []byte) []byte {
hash := sha3.NewLegacyKeccak256()
hash.Write(addr)
return hash.Sum(nil)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func TestToCheckSumAddress(t *testing.T) {
cases := []string{
"0xe01511d7333A18e969758BBdC9C7f50CcF30160A",
"0x62d17DE1fbDF36597F12F19717C39985A921426e",
"0x6F702345360D6D8533d2362eC834bf5f1aB63910",
}
for _, c := range cases {
t.Run(c, func(t *testing.T) {
res, err := ToCheckSumAddress(strings.ToLower(c))
assert.Nil(t, err)
assert.Equal(t, res, c)
})
}
}

【区块链】Address
https://weitrue.github.io/2024/06/06/chain-address/
作者
Pony W
发布于
2024年6月6日
许可协议