Skip to content
Open
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
21 changes: 18 additions & 3 deletions address/address_v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ package address
import (
"encoding/hex"
"log"

"github.com/pkg/errors"
"strings"

"github.com/iotexproject/iotex-address/address/bech32"
"github.com/pkg/errors"
)

// V1AddressStringLength is the length of v1 address string
Expand All @@ -28,14 +28,29 @@ type v1 struct {
AddressLength int
}

// FromString decodes an encoded address string into an address struct
// FromString decodes an encoded address string (in io1 or 0x format) into an address struct
func (v *v1) FromString(encodedAddr string) (Address, error) {
// Check if the address is in Ethereum 0x format
if strings.HasPrefix(encodedAddr, "0x") {
// Check length
if len(encodedAddr) != 42 {
return nil, errors.Wrapf(ErrInvalidAddr, "invalid 0x address length: expected 42 characters, got %d", len(encodedAddr))
}
// Convert from hex (0x) format to bytes
return v.FromHex(encodedAddr)
}

// Handle special addresses in io1 format
if IsAddrV1Special(encodedAddr) {
return newAddrV1Special(encodedAddr), nil
}

// Validate length for io1 addresses
if len(encodedAddr) != V1AddressStringLength {
return nil, errors.Wrapf(ErrInvalidAddr, "address length = %d, expecting 41", len(encodedAddr))
}

// Decode the IoTeX Bech32 format address (io1)
payload, err := v.decodeBech32(encodedAddr)
if err != nil {
return nil, err
Expand Down
17 changes: 17 additions & 0 deletions address/address_v1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,24 @@ func TestAddress(t *testing.T) {
addr2, err = FromHex(addrHex[:len(addrHex)-2])
require.NoError(err)
require.Equal(addr2.Hex()[4:], addrHex[2:len(addrHex)-2])

// Additional tests for 0x format addresses
t.Run("0x format address", func(t *testing.T) {
// Valid Ethereum-style 0x address
ethAddress := "0xba0104cD02672840Da55Bb14bebdd047Dfbfc02B"
addr, err := FromString(ethAddress)
require.NoError(err, "Expected no error for valid 0x address")
require.NotNil(addr, "Expected a non-nil address for valid 0x address")
require.Equal(strings.ToLower(ethAddress), addr.Hex(), "Expected address to match 0x format")

// Invalid 0x address (wrong length)
invalidEthAddress := "0xba0104cD02672840Da55Bb14bebdd047"
addr, err = FromString(invalidEthAddress)
require.Error(err, "Expected error for invalid 0x address length")
require.Nil(addr, "Expected nil address for invalid 0x address")
})
}

t.Run("testnet", func(t *testing.T) {
require.NoError(os.Setenv("IOTEX_NETWORK_TYPE", "testnet"))
runTest(t)
Expand Down
Loading