Skip to content

Commit

Permalink
Fix HexToHash/Address (umbracle#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
ferranbt authored Dec 30, 2021
1 parent 79572f9 commit ad7f564
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
30 changes: 28 additions & 2 deletions structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type Address [20]byte
// HexToAddress converts an hex string value to an address object
func HexToAddress(str string) Address {
a := Address{}
a.UnmarshalText([]byte(str))
a.UnmarshalText(completeHex(str, 20))
return a
}

Expand All @@ -47,6 +47,11 @@ func (a Address) MarshalText() ([]byte, error) {
return []byte(a.String()), nil
}

// Bytes returns the bytes of the Address
func (a Address) Bytes() []byte {
return a[:]
}

func (a Address) String() string {
return a.checksumEncode()
}
Expand Down Expand Up @@ -76,7 +81,7 @@ type Hash [32]byte
// HexToHash converts an hex string value to a hash object
func HexToHash(str string) Hash {
h := Hash{}
h.UnmarshalText([]byte(str))
h.UnmarshalText(completeHex(str, 32))
return h
}

Expand All @@ -101,6 +106,11 @@ func (h Hash) MarshalText() ([]byte, error) {
return []byte(h.String()), nil
}

// Bytes returns the bytes of the Hash
func (h Hash) Bytes() []byte {
return h[:]
}

func (h Hash) String() string {
return "0x" + hex.EncodeToString(h[:])
}
Expand Down Expand Up @@ -285,3 +295,19 @@ type Key interface {
Address() Address
Sign(hash []byte) ([]byte, error)
}

func completeHex(str string, num int) []byte {
num = num * 2
str = strings.TrimPrefix(str, "0x")

size := len(str)
if size < num {
for i := size; i < num; i++ {
str = "0" + str
}
} else {
diff := size - num
str = str[diff:]
}
return []byte("0x" + str)
}
12 changes: 11 additions & 1 deletion structs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestAddressChecksum(t *testing.T) {
func TestAddress_Checksum(t *testing.T) {
cases := []struct {
src, dst string
}{
Expand All @@ -32,3 +32,13 @@ func TestAddressChecksum(t *testing.T) {
assert.Equal(t, addr.String(), c.dst)
}
}

func TestAddress_HexToString(t *testing.T) {
assert.Equal(t, HexToAddress("0x1").String(), "0x0000000000000000000000000000000000000001")
assert.Equal(t, HexToAddress("00000000000000000000000000000000000000001").String(), "0x0000000000000000000000000000000000000001")
assert.Equal(t, HexToAddress("0000000000000000000000000000000000000001").String(), "0x0000000000000000000000000000000000000001")
}

func TestHash_HexToString(t *testing.T) {
assert.Equal(t, HexToHash("1").String(), "0x0000000000000000000000000000000000000000000000000000000000000001")
}

0 comments on commit ad7f564

Please sign in to comment.