From bc2f8f8a54d79ccea1916fa1895c71498deb235d Mon Sep 17 00:00:00 2001 From: Petr Hanzl <84449820+petr-hanzl@users.noreply.github.com> Date: Fri, 12 Apr 2024 02:01:36 +0700 Subject: [PATCH] Extend address type (#67) --- types/address.go | 52 +++++++++++++++++++++++++++++++++++++++++++-- types/types_test.go | 31 +++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 types/types_test.go diff --git a/types/address.go b/types/address.go index 2ce28ad..3b8b2b5 100644 --- a/types/address.go +++ b/types/address.go @@ -4,9 +4,57 @@ import ( "encoding/hex" ) +const AddressLength = 20 + // Address represents the 20 byte address of an Ethereum account. -type Address [20]byte +type Address [AddressLength]byte func (a Address) String() string { - return "0x" + hex.EncodeToString(a[:]) + return "0x" + hex.EncodeToString(a.Bytes()) +} + +func (a Address) Bytes() []byte { return a[:] } + +// HexToAddress returns Address with byte values of s. +// If s is larger than len(h), s will be cropped from the left. +func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) } + +// BytesToAddress returns Address with value b. +// If b is larger than len(h), b will be cropped from the left. +func BytesToAddress(b []byte) Address { + var a Address + a.SetBytes(b) + return a +} + +// SetBytes sets the address to the value of b. +// If b is larger than len(a), b will be cropped from the left. +func (a *Address) SetBytes(b []byte) { + if len(b) > len(a) { + b = b[len(b)-AddressLength:] + } + copy(a[AddressLength-len(b):], b) +} + +// FromHex returns the bytes represented by the hexadecimal string s. +// s may be prefixed with "0x". +func FromHex(s string) []byte { + if has0xPrefix(s) { + s = s[2:] + } + if len(s)%2 == 1 { + s = "0" + s + } + return Hex2Bytes(s) +} + +// has0xPrefix validates str begins with '0x' or '0X'. +func has0xPrefix(str string) bool { + return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') +} + +// Hex2Bytes returns the bytes represented by the hexadecimal string str. +func Hex2Bytes(str string) []byte { + h, _ := hex.DecodeString(str) + return h } diff --git a/types/types_test.go b/types/types_test.go new file mode 100644 index 0000000..d464ad1 --- /dev/null +++ b/types/types_test.go @@ -0,0 +1,31 @@ +package types + +import ( + "math/big" + "testing" +) + +func TestAddress_Convertation(t *testing.T) { + addrStr := "0x9c1a711a5e31a9461f6d1f662068e0a2f9edf552" + addr := HexToAddress(addrStr) + + if addr.String() != addrStr { + t.Fatal("incorrect address conversion") + } +} + +func TestHash_Compare(t *testing.T) { + a := big.NewInt(1) + b := big.NewInt(2) + + h1 := BigToHash(a) + h2 := BigToHash(b) + + if h1.Compare(h2) != -1 { + t.Fatal("incorrect comparing") + } + + if h1.Uint64() != uint64(1) { + t.Fatal("incorrect uint64 conversion") + } +}