Skip to content

Commit

Permalink
POS-2622: chg: address consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
marcello33 committed Oct 8, 2024
1 parent 0c645c8 commit e5ca416
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 9 deletions.
28 changes: 23 additions & 5 deletions x/auth/codec/hex_codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,18 @@ func NewHexCodec() address.Codec {
}

// StringToBytes encodes text to bytes
func (bc hexCodec) StringToBytes(text string) ([]byte, error) {
if len(strings.TrimSpace(text)) == 0 {
func (bc hexCodec) StringToBytes(hexAddr string) ([]byte, error) {
if len(strings.TrimSpace(hexAddr)) == 0 {
return []byte{}, errors.New("empty address string is not allowed")
}

bz := common.FromHex(text)
hexAddr = strings.ToLower(hexAddr)

if !has0xPrefix(hexAddr) {
hexAddr = "0x" + hexAddr
}

bz := common.FromHex(hexAddr)

if err := sdk.VerifyAddressFormat(bz); err != nil {
return nil, err
Expand All @@ -44,7 +50,19 @@ func (bc hexCodec) BytesToString(bz []byte) (string, error) {
return "", err
}

text := common.Bytes2Hex(bz)
hexAddr := common.Bytes2Hex(bz)

hexAddr = strings.ToLower(hexAddr)

if has0xPrefix(hexAddr) {
return hexAddr, nil
} else {
return "0x" + hexAddr, nil
}

}

return text, nil
// 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')
}
2 changes: 1 addition & 1 deletion x/auth/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/types"
)

const addrStr = "8186b214a917fb4922eb984fb80cfafa30ee8810"
const addrStr = "0x8186b214a917fb4922eb984fb80cfafa30ee8810"

var addrBytes = []byte{129, 134, 178, 20, 169, 23, 251, 73, 34, 235, 152, 79, 184, 12, 250, 250, 48, 238, 136, 16}

Expand Down
5 changes: 2 additions & 3 deletions x/auth/types/credentials_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package types_test

import (
"strings"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -44,11 +43,11 @@ func TestNewModuleCrendentials(t *testing.T) {
require.NoError(t, err)
require.False(t, credential.Equals(c))

address := secp256k1.GenPrivKey().PubKey().Address()
address := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address())
expected := sdk.MustAccAddressFromHex(address.String())
c, err = authtypes.NewModuleCredential("group", address)
require.NoError(t, err)
require.Equal(t, strings.ToLower(expected.String()), "0x"+strings.ToLower(address.String()))
require.Equal(t, expected.String(), address.String())
}

func TestNewBaseAccountWithPubKey(t *testing.T) {
Expand Down

0 comments on commit e5ca416

Please sign in to comment.