private/blockchain: address checksum hex

Updates blockchain.Address.Hex to return mixedcase
checksum hash.

Change-Id: I74c830b49eceb30876c8ef20d3adc4816de51a64
This commit is contained in:
Yaroslav Vorobiov 2022-10-30 15:19:16 +01:00
parent 9a303b00bf
commit 7b13af1184
2 changed files with 30 additions and 10 deletions

View File

@ -9,6 +9,7 @@ import (
"reflect" "reflect"
"github.com/zeebo/errs" "github.com/zeebo/errs"
"golang.org/x/crypto/sha3"
) )
// Error for the package (mainly parsing errors). // Error for the package (mainly parsing errors).
@ -61,6 +62,23 @@ func (a Address) Hex() string {
var buf [len(a)*2 + 2]byte var buf [len(a)*2 + 2]byte
copy(buf[:2], "0x") copy(buf[:2], "0x")
hex.Encode(buf[2:], a[:]) hex.Encode(buf[2:], a[:])
// https://eips.ethereum.org/EIPS/eip-55
sha := sha3.NewLegacyKeccak256()
sha.Write(buf[2:])
hash := sha.Sum(nil)
for i := 2; i < len(buf); i++ {
hashByte := hash[(i-2)/2]
if i%2 == 0 {
hashByte >>= 4
} else {
hashByte &= 0xf
}
if buf[i] > '9' && hashByte > 7 {
buf[i] -= 32
}
}
return string(buf[:]) return string(buf[:])
} }

View File

@ -21,18 +21,12 @@ func TestBytesToAddress(t *testing.T) {
require.Error(t, err) require.Error(t, err)
} }
func TestHex(t *testing.T) { func TestAddressHex(t *testing.T) {
addresses := []string{ addresses := []string{
"0xd15aaacddf4b72ba8fc5c41fc4b03f05aa73385c", "0xDAFEA492D9c6733ae3d56b7Ed1ADB60692c98Bc5",
"0xbe8f1abb014ec9988b6185ab4d8870992e838231", "0xd24400ae8BfEBb18cA49Be86258a3C749cf46853",
"0xd24400ae8bfebb18ca49be86258a3c749cf46853", "0x4E58657CD8b3401B6f7Db9Cd0408f06582c458b5",
} }
hashes := []string{
"0xdea1082dbea119c822dfe804264f5b880d4208ef51e8c5a8995eff10a5094de8",
"0xd1a78f16158b550945dd39182d188c3fb7285b431223c8b0fe38f4181e9ac197",
"0x47a5b3fae0bad45631a65324001f75dea311898e26ee10597a66953b57dfe332",
}
for _, address := range addresses { for _, address := range addresses {
decoded, err := hex.DecodeString(address[2:]) decoded, err := hex.DecodeString(address[2:])
require.NoError(t, err) require.NoError(t, err)
@ -42,6 +36,14 @@ func TestHex(t *testing.T) {
require.Equal(t, address, a.Hex()) require.Equal(t, address, a.Hex())
} }
}
func TestHashHex(t *testing.T) {
hashes := []string{
"0xdea1082dbea119c822dfe804264f5b880d4208ef51e8c5a8995eff10a5094de8",
"0xd1a78f16158b550945dd39182d188c3fb7285b431223c8b0fe38f4181e9ac197",
"0x47a5b3fae0bad45631a65324001f75dea311898e26ee10597a66953b57dfe332",
}
for _, hash := range hashes { for _, hash := range hashes {
decoded, err := hex.DecodeString(hash[2:]) decoded, err := hex.DecodeString(hash[2:])
require.NoError(t, err) require.NoError(t, err)