Skip to content
This repository was archived by the owner on Feb 14, 2025. It is now read-only.

Extend address type #67

Merged
merged 3 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}
}