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) }
|