Skip to content

Commit

Permalink
Revert "Mege PR #6749: auth: remove custom JSON marshaling"
Browse files Browse the repository at this point in the history
This reverts commit c251361.
  • Loading branch information
kfangw authored and Sangyeop.lee committed Dec 8, 2020
1 parent 7836a58 commit 1a28da1
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
46 changes: 46 additions & 0 deletions x/auth/types/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package types

import (
"bytes"
"encoding/json"
"errors"
"time"

Expand Down Expand Up @@ -167,3 +168,48 @@ func (acc BaseAccount) MarshalYAML() (interface{}, error) {

return string(bz), err
}

// MarshalJSON returns the JSON representation of a BaseAccount.
func (acc BaseAccount) MarshalJSON() ([]byte, error) {
alias := baseAccountPretty{
Address: acc.Address,
Coins: acc.Coins,
AccountNumber: acc.AccountNumber,
Sequence: acc.Sequence,
}

if acc.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, acc.PubKey)
if err != nil {
return nil, err
}

alias.PubKey = pks
}

return json.Marshal(alias)
}

// UnmarshalJSON unmarshals raw JSON bytes into a BaseAccount.
func (acc *BaseAccount) UnmarshalJSON(bz []byte) error {
var alias baseAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
return err
}

if alias.PubKey != "" {
pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, alias.PubKey)
if err != nil {
return err
}

acc.PubKey = pk
}

acc.Address = alias.Address
acc.Coins = alias.Coins
acc.AccountNumber = alias.AccountNumber
acc.Sequence = alias.Sequence

return nil
}
26 changes: 26 additions & 0 deletions x/auth/types/account_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"encoding/json"
"errors"
"testing"

Expand Down Expand Up @@ -128,3 +129,28 @@ func TestGenesisAccountValidate(t *testing.T) {
})
}
}

func TestBaseAccountJSON(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := NewBaseAccount(addr, coins, pubkey, 10, 50)

bz, err := json.Marshal(baseAcc)
require.NoError(t, err)

bz1, err := baseAcc.MarshalJSON()
require.NoError(t, err)
require.Equal(t, string(bz1), string(bz))

var a BaseAccount
require.NoError(t, json.Unmarshal(bz, &a))
require.Equal(t, baseAcc.String(), a.String())

bz, err = ModuleCdc.MarshalJSON(baseAcc)
require.NoError(t, err)

var b BaseAccount
require.NoError(t, ModuleCdc.UnmarshalJSON(bz, &b))
require.Equal(t, baseAcc.String(), b.String())
}

0 comments on commit 1a28da1

Please sign in to comment.