Skip to content

Commit

Permalink
Extend address type (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
cabrador committed Apr 11, 2024
1 parent 6d51459 commit bc2f8f8
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 2 deletions.
52 changes: 50 additions & 2 deletions types/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
31 changes: 31 additions & 0 deletions types/types_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}

0 comments on commit bc2f8f8

Please sign in to comment.