diff --git a/protocol/identity/alias/generate.go b/protocol/identity/alias/generate.go index 8c175142a..9e817e29c 100644 --- a/protocol/identity/alias/generate.go +++ b/protocol/identity/alias/generate.go @@ -4,6 +4,7 @@ import ( "crypto/ecdsa" "encoding/hex" "fmt" + "strings" "github.com/status-im/status-go/eth-node/crypto" ) @@ -31,7 +32,8 @@ func GenerateFromPublicKey(publicKey *ecdsa.PublicKey) string { // GenerateFromPublicKeyString returns the 3 words name given a public key // prefixed with 0x func GenerateFromPublicKeyString(publicKeyString string) (string, error) { - publicKeyBytes, err := hex.DecodeString(publicKeyString[2:]) + pk := strings.TrimPrefix(publicKeyString, "0x") + publicKeyBytes, err := hex.DecodeString(pk) if err != nil { return "", err } diff --git a/protocol/identity/alias/generate_test.go b/protocol/identity/alias/generate_test.go index 77638934d..bf8dc1247 100644 --- a/protocol/identity/alias/generate_test.go +++ b/protocol/identity/alias/generate_test.go @@ -15,10 +15,47 @@ func TestGenerate(t *testing.T) { } func TestGenerateFromPublicKeyString(t *testing.T) { - pk := "0x04eedbaafd6adf4a9233a13e7b1c3c14461fffeba2e9054b8d456ce5f6ebeafadcbf3dce3716253fbc391277fa5a086b60b283daf61fb5b1f26895f456c2f31ae3" + tests := []struct { + name string + publicKey string + alias string + errorExpected bool + }{ + { + name: "valid public key - start with 0x", + publicKey: "0x04eedbaafd6adf4a9233a13e7b1c3c14461fffeba2e9054b8d456ce5f6ebeafadcbf3dce3716253fbc391277fa5a086b60b283daf61fb5b1f26895f456c2f31ae3", + alias: "Darkorange Blue Bubblefish", + errorExpected: false, + }, + { + name: "valid public key - without 0x", + publicKey: "04eedbaafd6adf4a9233a13e7b1c3c14461fffeba2e9054b8d456ce5f6ebeafadcbf3dce3716253fbc391277fa5a086b60b283daf61fb5b1f26895f456c2f31ae3", + alias: "Darkorange Blue Bubblefish", + errorExpected: false, + }, + { + name: "invalid public key", + publicKey: "0x04eedbaafd6adf4a9233a13e7b1c3c14461fffeba2e9054b8d456ce5f6ebeafadcbf3dce3716253fbc391277fa5a086b", + alias: "", + errorExpected: true, + }, + { + name: "empty public key", + publicKey: "", + alias: "", + errorExpected: true, + }, + } - name, err := GenerateFromPublicKeyString(pk) - require.NoError(t, err) - require.NotNil(t, name) - require.Equal(t, "Darkorange Blue Bubblefish", name) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + name, err := GenerateFromPublicKeyString(tt.publicKey) + if tt.errorExpected { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.Equal(t, tt.alias, name) + }) + } }