From 7b13af118401b1acac903f1e869c59dec4516375 Mon Sep 17 00:00:00 2001 From: Yaroslav Vorobiov Date: Sun, 30 Oct 2022 15:19:16 +0100 Subject: [PATCH] private/blockchain: address checksum hex Updates blockchain.Address.Hex to return mixedcase checksum hash. Change-Id: I74c830b49eceb30876c8ef20d3adc4816de51a64 --- private/blockchain/types.go | 18 ++++++++++++++++++ private/blockchain/types_test.go | 22 ++++++++++++---------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/private/blockchain/types.go b/private/blockchain/types.go index 1bde7e42f..3b46ead60 100644 --- a/private/blockchain/types.go +++ b/private/blockchain/types.go @@ -9,6 +9,7 @@ import ( "reflect" "github.com/zeebo/errs" + "golang.org/x/crypto/sha3" ) // Error for the package (mainly parsing errors). @@ -61,6 +62,23 @@ func (a Address) Hex() string { var buf [len(a)*2 + 2]byte copy(buf[:2], "0x") 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[:]) } diff --git a/private/blockchain/types_test.go b/private/blockchain/types_test.go index fc37cb699..38b29211e 100644 --- a/private/blockchain/types_test.go +++ b/private/blockchain/types_test.go @@ -21,18 +21,12 @@ func TestBytesToAddress(t *testing.T) { require.Error(t, err) } -func TestHex(t *testing.T) { +func TestAddressHex(t *testing.T) { addresses := []string{ - "0xd15aaacddf4b72ba8fc5c41fc4b03f05aa73385c", - "0xbe8f1abb014ec9988b6185ab4d8870992e838231", - "0xd24400ae8bfebb18ca49be86258a3c749cf46853", + "0xDAFEA492D9c6733ae3d56b7Ed1ADB60692c98Bc5", + "0xd24400ae8BfEBb18cA49Be86258a3C749cf46853", + "0x4E58657CD8b3401B6f7Db9Cd0408f06582c458b5", } - hashes := []string{ - "0xdea1082dbea119c822dfe804264f5b880d4208ef51e8c5a8995eff10a5094de8", - "0xd1a78f16158b550945dd39182d188c3fb7285b431223c8b0fe38f4181e9ac197", - "0x47a5b3fae0bad45631a65324001f75dea311898e26ee10597a66953b57dfe332", - } - for _, address := range addresses { decoded, err := hex.DecodeString(address[2:]) require.NoError(t, err) @@ -42,6 +36,14 @@ func TestHex(t *testing.T) { require.Equal(t, address, a.Hex()) } +} + +func TestHashHex(t *testing.T) { + hashes := []string{ + "0xdea1082dbea119c822dfe804264f5b880d4208ef51e8c5a8995eff10a5094de8", + "0xd1a78f16158b550945dd39182d188c3fb7285b431223c8b0fe38f4181e9ac197", + "0x47a5b3fae0bad45631a65324001f75dea311898e26ee10597a66953b57dfe332", + } for _, hash := range hashes { decoded, err := hex.DecodeString(hash[2:]) require.NoError(t, err)