From bf1803bc578da645be5d6074ebcb6fcdcd3bd781 Mon Sep 17 00:00:00 2001
From: Facundo Medica <14063057+facundomedica@users.noreply.github.com>
Date: Mon, 31 Jul 2023 11:32:33 +0200
Subject: [PATCH] fix(x/auth): internal error on AccountInfo when PubKey is nil
 (#17209)

---
 CHANGELOG.md                     |  1 +
 x/auth/keeper/grpc_query.go      | 11 ++++++++---
 x/auth/keeper/grpc_query_test.go | 14 ++++++++++++++
 3 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5137b980a9fa..f1e871464d68 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
 
 ### Bug Fixes
 
+* (x/auth) [#17209](https://github.com/cosmos/cosmos-sdk/pull/17209) Internal error on AccountInfo when account's public key is not set.
 * (baseapp) [#17159](https://github.com/cosmos/cosmos-sdk/pull/17159) Validators can propose blocks that exceed the gas limit.
 * (x/group) [#17146](https://github.com/cosmos/cosmos-sdk/pull/17146) Rename x/group legacy ORM package's error codespace from "orm" to "legacy_orm", preventing collisions with ORM's error codespace "orm".
 * (x/bank) [#17170](https://github.com/cosmos/cosmos-sdk/pull/17170) Avoid empty spendable error message on send coins.
diff --git a/x/auth/keeper/grpc_query.go b/x/auth/keeper/grpc_query.go
index 1b40d3c3b38c..6e547f89128b 100644
--- a/x/auth/keeper/grpc_query.go
+++ b/x/auth/keeper/grpc_query.go
@@ -226,9 +226,14 @@ func (s queryServer) AccountInfo(ctx context.Context, req *types.QueryAccountInf
 		return nil, status.Errorf(codes.NotFound, "account %s not found", req.Address)
 	}
 
-	pkAny, err := codectypes.NewAnyWithValue(account.GetPubKey())
-	if err != nil {
-		return nil, status.Errorf(codes.Internal, err.Error())
+	// if there is no public key, avoid serializing the nil value
+	pubKey := account.GetPubKey()
+	var pkAny *codectypes.Any
+	if pubKey != nil {
+		pkAny, err = codectypes.NewAnyWithValue(account.GetPubKey())
+		if err != nil {
+			return nil, status.Errorf(codes.Internal, err.Error())
+		}
 	}
 
 	return &types.QueryAccountInfoResponse{
diff --git a/x/auth/keeper/grpc_query_test.go b/x/auth/keeper/grpc_query_test.go
index b0479a8c0991..82e9cfe573fc 100644
--- a/x/auth/keeper/grpc_query_test.go
+++ b/x/auth/keeper/grpc_query_test.go
@@ -521,3 +521,17 @@ func (suite *KeeperTestSuite) TestQueryAccountInfo() {
 	suite.Require().NoError(err)
 	suite.Require().Equal(pkBz, res.Info.PubKey.Value)
 }
+
+func (suite *KeeperTestSuite) TestQueryAccountInfoWithoutPubKey() {
+	acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, addr)
+	suite.accountKeeper.SetAccount(suite.ctx, acc)
+
+	res, err := suite.queryClient.AccountInfo(context.Background(), &types.QueryAccountInfoRequest{
+		Address: addr.String(),
+	})
+
+	suite.Require().NoError(err)
+	suite.Require().NotNil(res.Info)
+	suite.Require().Equal(addr.String(), res.Info.Address)
+	suite.Require().Nil(res.Info.PubKey)
+}