diff --git a/CHANGELOG.md b/CHANGELOG.md index 70534bae75..c064382428 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ * (proto) [\#106](https://github.com/line/lfb-sdk/pull/106) Rename package of proto files * (api) [\#130](https://github.com/line/lfb-sdk/pull/130) Rename rest apis * (auth) [\#265](https://github.com/line/lfb-sdk/pull/265) Introduce sig block height for the new replay protection +* (global) [\#298](https://github.com/line/lfb-sdk/pull/298) Treat addresses as strings ### Build, CI * (ci) [\#234](https://github.com/line/lfb-sdk/pull/234) Fix branch name in ci script diff --git a/Makefile b/Makefile index a88b408d67..784fad84be 100644 --- a/Makefile +++ b/Makefile @@ -394,7 +394,7 @@ proto-all: proto-format proto-lint proto-gen proto-gen: @echo "Generating Protobuf files" - $(DOCKER) run --rm -e -v $(CURDIR):/workspace --workdir /workspace tendermintdev/sdk-proto-gen sh ./scripts/protocgen.sh + $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace tendermintdev/sdk-proto-gen sh ./scripts/protocgen.sh proto-format: @echo "Formatting Protobuf files" diff --git a/baseapp/accountwgs_test.go b/baseapp/accountwgs_test.go index 859dc06c4f..0050a053c1 100644 --- a/baseapp/accountwgs_test.go +++ b/baseapp/accountwgs_test.go @@ -92,7 +92,7 @@ func newTestPrivKeys(num int) []*secp256k1.PrivKey { func getAddrs(privs []*secp256k1.PrivKey) []sdk.AccAddress { addrs := make([]sdk.AccAddress, 0, len(privs)) for _, priv := range privs { - addrs = append(addrs, sdk.AccAddress(priv.PubKey().Address())) + addrs = append(addrs, sdk.BytesToAccAddress(priv.PubKey().Address())) } return addrs } diff --git a/baseapp/msg_service_router_test.go b/baseapp/msg_service_router_test.go index 0b889f688a..9356bc80b0 100644 --- a/baseapp/msg_service_router_test.go +++ b/baseapp/msg_service_router_test.go @@ -103,8 +103,8 @@ func TestMsgService(t *testing.T) { // Second round: all signer infos are set, so each signer can sign. signerData := authsigning.SignerData{ - ChainID: "test", - Sequence: 0, + ChainID: "test", + Sequence: 0, } sigV2, err = tx.SignWithPrivKey( encCfg.TxConfig.SignModeHandler().DefaultMode(), signerData, diff --git a/client/context.go b/client/context.go index 0c531a6f2a..b7320cc023 100644 --- a/client/context.go +++ b/client/context.go @@ -287,28 +287,28 @@ func (ctx Context) printOutput(out []byte) error { // address is returned. func GetFromFields(kr keyring.Keyring, from string, genOnly bool) (sdk.AccAddress, string, keyring.KeyType, error) { if from == "" { - return nil, "", 0, nil + return "", "", 0, nil } if genOnly { - addr, err := sdk.AccAddressFromBech32(from) + err := sdk.ValidateAccAddress(from) if err != nil { - return nil, "", 0, errors.Wrap(err, "must provide a valid Bech32 address in generate-only mode") + return sdk.AccAddress(from), "", 0, errors.Wrap(err, "must provide a valid Bech32 address in generate-only mode") } - return addr, "", 0, nil + return sdk.AccAddress(from), "", 0, nil } var info keyring.Info - if addr, err := sdk.AccAddressFromBech32(from); err == nil { - info, err = kr.KeyByAddress(addr) + if err := sdk.ValidateAccAddress(from); err == nil { + info, err = kr.KeyByAddress(sdk.AccAddress(from)) if err != nil { - return nil, "", 0, err + return sdk.AccAddress(from), "", 0, err } } else { info, err = kr.Key(from) if err != nil { - return nil, "", 0, err + return "", "", 0, err } } diff --git a/client/debug/main.go b/client/debug/main.go index 28223da35f..456e68bad7 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -75,7 +75,7 @@ func PubkeyCmd() *cobra.Command { Example: $ %s debug pubkey TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz -$ %s debug pubkey cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg +$ %s debug pubkey linkpub1cqmsrdepq28g8wmpa2hmq06y770jcjr48ntw932wc8l0cl7fz5xr4sahy3s3v0r3mez `, version.AppName, version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -127,23 +127,23 @@ func AddrCmd() *cobra.Command { Long: fmt.Sprintf(`Convert an address between hex encoding and bech32. Example: -$ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg +$ %s debug addr link19wgf6ymq2ur6r59st95e04e49m69z4al4fc982 `, version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { addrString := args[0] - var addr []byte + var addrBytes []byte // try hex, then bech32 var err error - addr, err = hex.DecodeString(addrString) + addrBytes, err = hex.DecodeString(addrString) if err != nil { var err2 error - addr, err2 = sdk.AccAddressFromBech32(addrString) + addrBytes, err2 = sdk.AccAddressToBytes(addrString) if err2 != nil { var err3 error - addr, err3 = sdk.ValAddressFromBech32(addrString) + addrBytes, err3 = sdk.ValAddressToBytes(addrString) if err3 != nil { return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3) @@ -152,11 +152,11 @@ $ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg } } - accAddr := sdk.AccAddress(addr) - valAddr := sdk.ValAddress(addr) + accAddr := sdk.BytesToAccAddress(addrBytes) + valAddr := sdk.BytesToValAddress(addrBytes) - cmd.Println("Address:", addr) - cmd.Printf("Address (hex): %X\n", addr) + cmd.Println("Address Bytes:", addrBytes) + cmd.Printf("Address (hex): %X\n", addrBytes) cmd.Printf("Bech32 Acc: %s\n", accAddr) cmd.Printf("Bech32 Val: %s\n", valAddr) return nil diff --git a/client/keys/show.go b/client/keys/show.go index 6f2b8264af..94316dccc6 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -146,12 +146,12 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { func fetchKey(kb keyring.Keyring, keyref string) (keyring.Info, error) { info, err := kb.Key(keyref) if err != nil { - accAddr, err := sdk.AccAddressFromBech32(keyref) + err := sdk.ValidateAccAddress(keyref) if err != nil { return info, err } - info, err = kb.KeyByAddress(accAddr) + info, err = kb.KeyByAddress(sdk.AccAddress(keyref)) if err != nil { return info, errors.New("key not found") } diff --git a/client/keys/show_test.go b/client/keys/show_test.go index 6c80dab19f..9c58073cfe 100644 --- a/client/keys/show_test.go +++ b/client/keys/show_test.go @@ -29,7 +29,9 @@ func Test_multiSigKey_Properties(t *testing.T) { require.Equal(t, "myMultisig", tmp.GetName()) require.Equal(t, keyring.TypeMulti, tmp.GetType()) require.Equal(t, "BDF0C827D34CA39919C7688EB5A95383C60B3471", tmp.GetPubKey().Address().String()) - require.Equal(t, "link1hhcvsf7nfj3ejxw8dz8tt22ns0rqkdr3rrh7xy", sdk.MustBech32ifyAddressBytes("link", tmp.GetAddress())) + acc := tmp.GetAddress() + addrBytes, _ := sdk.AccAddressToBytes(acc.String()) + require.Equal(t, "link1hhcvsf7nfj3ejxw8dz8tt22ns0rqkdr3rrh7xy", sdk.MustBech32ifyAddressBytes("link", addrBytes)) } func Test_showKeysCmd(t *testing.T) { diff --git a/client/rpc/validators.go b/client/rpc/validators.go index d87d2331c5..b6456ab2e1 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -109,7 +109,7 @@ func validatorOutput(validator *osttypes.Validator) (ValidatorOutput, error) { } return ValidatorOutput{ - Address: sdk.ConsAddress(validator.Address), + Address: sdk.BytesToConsAddress(validator.Address), PubKey: pk, ProposerPriority: validator.ProposerPriority, VotingPower: validator.VotingPower, diff --git a/client/tx/tx.go b/client/tx/tx.go index 562983b0c5..8d762ab413 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -316,7 +316,9 @@ func PrepareFactory(clientCtx client.Context, txf Factory) (Factory, error) { if err != nil { return txf, err } - sigBlockHeight = height + // `ctx.Height` of checkTx may be later by 1 block than consensus block height. + // Some cli integrated test fails because of this(sigBlockHeight = height). + sigBlockHeight = height - 1 } } diff --git a/crypto/keyring/info.go b/crypto/keyring/info.go index 12b97d7a2d..92ab49fe64 100644 --- a/crypto/keyring/info.go +++ b/crypto/keyring/info.go @@ -69,7 +69,7 @@ func (i localInfo) GetPubKey() cryptotypes.PubKey { // GetType implements Info interface func (i localInfo) GetAddress() types.AccAddress { - return i.PubKey.Address().Bytes() + return types.BytesToAccAddress(i.PubKey.Address()) } // GetType implements Info interface @@ -117,7 +117,7 @@ func (i ledgerInfo) GetPubKey() cryptotypes.PubKey { // GetAddress implements Info interface func (i ledgerInfo) GetAddress() types.AccAddress { - return i.PubKey.Address().Bytes() + return types.BytesToAccAddress(i.PubKey.Address()) } // GetPath implements Info interface @@ -169,7 +169,7 @@ func (i offlineInfo) GetAlgo() hd.PubKeyType { // GetAddress implements Info interface func (i offlineInfo) GetAddress() types.AccAddress { - return i.PubKey.Address().Bytes() + return types.BytesToAccAddress(i.PubKey.Address()) } // GetPath implements Info interface @@ -225,7 +225,7 @@ func (i multiInfo) GetPubKey() cryptotypes.PubKey { // GetAddress implements Info interface func (i multiInfo) GetAddress() types.AccAddress { - return i.PubKey.Address().Bytes() + return types.BytesToAccAddress(i.PubKey.Address()) } // GetPath implements Info interface diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 24cd617cba..c60dd0fc7a 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -79,7 +79,8 @@ func TestKeyManagementKeyRing(t *testing.T) { require.NotNil(t, err) _, err = kb.KeyByAddress(accAddr(i2)) require.NoError(t, err) - addr, err := sdk.AccAddressFromBech32("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") + addr := sdk.AccAddress("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") + err = sdk.ValidateAccAddress(addr.String()) require.NoError(t, err) _, err = kb.KeyByAddress(addr) require.NotNil(t, err) @@ -432,7 +433,8 @@ func TestInMemoryKeyManagement(t *testing.T) { require.NotNil(t, err) _, err = cstore.KeyByAddress(accAddr(i2)) require.NoError(t, err) - addr, err := sdk.AccAddressFromBech32("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") + addr := sdk.AccAddress("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") + err = sdk.ValidateAccAddress(addr.String()) require.NoError(t, err) _, err = cstore.KeyByAddress(addr) require.NotNil(t, err) diff --git a/crypto/keyring/output.go b/crypto/keyring/output.go index ebec1c3b0c..a6d2f9dbfd 100644 --- a/crypto/keyring/output.go +++ b/crypto/keyring/output.go @@ -50,7 +50,7 @@ func Bech32KeysOutput(infos []Info) ([]KeyOutput, error) { // Bech32ConsKeyOutput create a KeyOutput in with "cons" Bech32 prefixes. func Bech32ConsKeyOutput(keyInfo Info) (KeyOutput, error) { - consAddr := sdk.ConsAddress(keyInfo.GetPubKey().Address().Bytes()) + consAddr := sdk.BytesToConsAddress(keyInfo.GetPubKey().Address()) bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, keyInfo.GetPubKey()) if err != nil { @@ -62,7 +62,7 @@ func Bech32ConsKeyOutput(keyInfo Info) (KeyOutput, error) { // Bech32ValKeyOutput create a KeyOutput in with "val" Bech32 prefixes. func Bech32ValKeyOutput(keyInfo Info) (KeyOutput, error) { - valAddr := sdk.ValAddress(keyInfo.GetPubKey().Address().Bytes()) + valAddr := sdk.BytesToValAddress(keyInfo.GetPubKey().Address()) bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeValPub, keyInfo.GetPubKey()) if err != nil { @@ -76,7 +76,7 @@ func Bech32ValKeyOutput(keyInfo Info) (KeyOutput, error) { // public key is a multisig public key, then the threshold and constituent // public keys will be added. func Bech32KeyOutput(keyInfo Info) (KeyOutput, error) { - accAddr := sdk.AccAddress(keyInfo.GetPubKey().Address().Bytes()) + accAddr := sdk.BytesToAccAddress(keyInfo.GetPubKey().Address()) bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, keyInfo.GetPubKey()) if err != nil { return KeyOutput{}, err @@ -88,7 +88,7 @@ func Bech32KeyOutput(keyInfo Info) (KeyOutput, error) { pubKeys := make([]multisigPubKeyOutput, len(mInfo.PubKeys)) for i, pk := range mInfo.PubKeys { - accAddr := sdk.AccAddress(pk.PubKey.Address().Bytes()) + accAddr := sdk.BytesToAccAddress(pk.PubKey.Address()) bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk.PubKey) if err != nil { diff --git a/crypto/keyring/output_test.go b/crypto/keyring/output_test.go index 33039aac51..e3a6cca2cd 100644 --- a/crypto/keyring/output_test.go +++ b/crypto/keyring/output_test.go @@ -14,11 +14,11 @@ import ( func TestBech32KeysOutput(t *testing.T) { tmpKey := secp256k1.GenPrivKey().PubKey() bechTmpKey := sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, tmpKey) - tmpAddr := sdk.AccAddress(tmpKey.Address().Bytes()) + tmpAddr := sdk.BytesToAccAddress(tmpKey.Address()) multisigPks := kmultisig.NewLegacyAminoPubKey(1, []types.PubKey{tmpKey}) multiInfo := NewMultiInfo("multisig", multisigPks) - accAddr := sdk.AccAddress(multiInfo.GetPubKey().Address().Bytes()) + accAddr := sdk.BytesToAccAddress(multiInfo.GetPubKey().Address()) bechPubKey := sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, multiInfo.GetPubKey()) expectedOutput := NewKeyOutput(multiInfo.GetName(), multiInfo.GetType().String(), accAddr.String(), bechPubKey) diff --git a/crypto/keys/multisig/multisig_test.go b/crypto/keys/multisig/multisig_test.go index 5d5a2f480f..f9a3228b94 100644 --- a/crypto/keys/multisig/multisig_test.go +++ b/crypto/keys/multisig/multisig_test.go @@ -20,7 +20,7 @@ func TestAddress(t *testing.T) { pubKeys, _ := generatePubKeysAndSignatures(5, msg) multisigKey := kmultisig.NewLegacyAminoPubKey(2, pubKeys) - require.Len(t, multisigKey.Address().Bytes(), 20) + require.Len(t, multisigKey.Address(), 20) } func TestEquals(t *testing.T) { diff --git a/crypto/ledger/ledger_mock.go b/crypto/ledger/ledger_mock.go index d714c80964..2ee1525323 100644 --- a/crypto/ledger/ledger_mock.go +++ b/crypto/ledger/ledger_mock.go @@ -82,7 +82,7 @@ func (mock LedgerSECP256K1Mock) GetAddressPubKeySECP256K1(derivationPath []uint3 // Generate the bech32 addr using existing ostcrypto/etc. pub := &csecp256k1.PubKey{Key: compressedPublicKey} - addr := sdk.AccAddress(pub.Address()).String() + addr := sdk.BytesToAccAddress(pub.Address()).String() return pk, addr, err } diff --git a/crypto/ledger/ledger_test.go b/crypto/ledger/ledger_test.go index adb7896426..2b5bbf07a5 100644 --- a/crypto/ledger/ledger_test.go +++ b/crypto/ledger/ledger_test.go @@ -36,7 +36,7 @@ func TestPublicKeyUnsafe(t *testing.T) { require.Equal(t, "linkpub1cqmsrdepq27djm9tzq3sftqsayx95refxk8r5jn0kyshhql9mdjhjx829zlvzygzwr2", pubKeyAddr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) - addr := sdk.AccAddress(priv.PubKey().Address()).String() + addr := sdk.BytesToAccAddress(priv.PubKey().Address()).String() require.Equal(t, "link1tdl7n2acgmec0y5nng0q2fahl9khyct3cgsktn", addr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) } @@ -117,7 +117,7 @@ func TestPublicKeySafe(t *testing.T) { require.Equal(t, "link1tdl7n2acgmec0y5nng0q2fahl9khyct3cgsktn", addr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) - addr2 := sdk.AccAddress(priv.PubKey().Address()).String() + addr2 := sdk.BytesToAccAddress(priv.PubKey().Address()).String() require.Equal(t, addr, addr2) } @@ -162,7 +162,7 @@ func TestPublicKeyHDPath(t *testing.T) { require.NotNil(t, addr) require.NotNil(t, priv) - addr2 := sdk.AccAddress(priv.PubKey().Address()).String() + addr2 := sdk.BytesToAccAddress(priv.PubKey().Address()).String() require.Equal(t, addr2, addr) require.Equal(t, expectedAddrs[i], addr, diff --git a/docs/core/proto-docs.md b/docs/core/proto-docs.md index 578d79b700..cfaff20e10 100644 --- a/docs/core/proto-docs.md +++ b/docs/core/proto-docs.md @@ -9525,7 +9525,7 @@ TxBody is the body of a transaction that all signers sign over. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | `messages` | [google.protobuf.Any](#google.protobuf.Any) | repeated | messages is a list of messages to be executed. The required signers of those messages define the number and order of elements in AuthInfo's signer_infos and Tx's signatures. Each required signer address is added to the list only the first time it occurs. By convention, the first required signer (usually from the first message) is referred to as the primary signer and pays the fee for the whole transaction. | -| `sig_block_height` | [uint64](#uint64) | | sig block height is available between current block height and current block height - `VALID_SIG_BLOCK_DURATION` this is used for distinguish signatures instead of account number. this is mandatory. | +| `sig_block_height` | [uint64](#uint64) | | sig block height is available between current block height and current block height - `VALID_SIG_BLOCK_PERIOD` this is used for distinguish signatures instead of account number. this is mandatory. | | `memo` | [string](#string) | | memo is any arbitrary memo to be added to the transaction | | `timeout_height` | [uint64](#uint64) | | timeout is the block height after which this transaction will not be processed by the chain | | `extension_options` | [google.protobuf.Any](#google.protobuf.Any) | repeated | extension_options are arbitrary options that can be added by chains when the default options are not sufficient. If any of these are present and can't be handled, the transaction will be rejected | diff --git a/server/init.go b/server/init.go index b3e756ced0..ba23290bdc 100644 --- a/server/init.go +++ b/server/init.go @@ -16,7 +16,7 @@ func GenerateCoinKey(algo keyring.SignatureAlgo) (sdk.AccAddress, string, error) if err != nil { return sdk.AccAddress([]byte{}), "", err } - return sdk.AccAddress(info.GetPubKey().Address()), secret, nil + return sdk.BytesToAccAddress(info.GetPubKey().Address()), secret, nil } // GenerateSaveCoinKey returns the address of a public key, along with the secret @@ -48,5 +48,5 @@ func GenerateSaveCoinKey(keybase keyring.Keyring, keyName string, overwrite bool return sdk.AccAddress([]byte{}), "", err } - return sdk.AccAddress(info.GetPubKey().Address()), secret, nil + return sdk.BytesToAccAddress(info.GetPubKey().Address()), secret, nil } diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 2bd27546e3..3871e8d091 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -87,7 +87,7 @@ func ShowAddressCmd() *cobra.Command { cfg := serverCtx.Config privValidator := pvm.LoadFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()) - valConsAddr := (sdk.ConsAddress)(privValidator.GetAddress()) + valConsAddr := sdk.BytesToConsAddress(privValidator.GetAddress()) output, _ := cmd.Flags().GetString(cli.OutputFlag) if strings.ToLower(output) == "json" { diff --git a/simapp/export.go b/simapp/export.go index dcb1e984be..e8462b9400 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -58,7 +58,7 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] allowedAddrsMap := make(map[string]bool) for _, addr := range jailAllowedAddrs { - _, err := sdk.ValAddressFromBech32(addr) + err := sdk.ValidateValAddress(addr) if err != nil { log.Fatal(err) } @@ -79,15 +79,9 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] // withdraw all delegator rewards dels := app.StakingKeeper.GetAllDelegations(ctx) for _, delegation := range dels { - valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(delegation.ValidatorAddress) - delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } + delAddr := sdk.AccAddress(delegation.DelegatorAddress) _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) } @@ -115,14 +109,8 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] // reinitialize all delegations for _, del := range dels { - valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) - if err != nil { - panic(err) - } - delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(del.ValidatorAddress) + delAddr := sdk.AccAddress(del.DelegatorAddress) app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) } diff --git a/simapp/genesis_account_test.go b/simapp/genesis_account_test.go index 94a419eece..be968b47a9 100644 --- a/simapp/genesis_account_test.go +++ b/simapp/genesis_account_test.go @@ -15,7 +15,7 @@ import ( func TestSimGenesisAccountValidate(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) vestingStart := time.Now().UTC() @@ -44,7 +44,7 @@ func TestSimGenesisAccountValidate(t *testing.T) { { "valid basic account with module name", simapp.SimGenesisAccount{ - BaseAccount: authtypes.NewBaseAccount(sdk.AccAddress(crypto.AddressHash([]byte("testmod"))), nil, 0), + BaseAccount: authtypes.NewBaseAccount(sdk.BytesToAccAddress(crypto.AddressHash([]byte("testmod"))), nil, 0), ModuleName: "testmod", }, false, diff --git a/simapp/simd/cmd/genaccounts.go b/simapp/simd/cmd/genaccounts.go index d4edc5b3f4..2729ae11fc 100644 --- a/simapp/simd/cmd/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -48,7 +48,8 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa config.SetRoot(clientCtx.HomeDir) - addr, err := sdk.AccAddressFromBech32(args[0]) + addr := sdk.AccAddress(args[0]) + err := sdk.ValidateAccAddress(args[0]) if err != nil { inBuf := bufio.NewReader(cmd.InOrStdin()) keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 2b54bf4d4f..17d858ea6b 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -208,7 +208,7 @@ func InitTestnet( valTokens := sdk.TokensFromConsensusPower(100) createValMsg, err := stakingtypes.NewMsgCreateValidator( - sdk.ValAddress(addr), + addr.ToValAddress(), valPubKeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index ea1534a433..cd85e9aa06 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "sort" "strconv" "testing" "time" @@ -102,8 +103,9 @@ func SetupWithGenesisValSet(t *testing.T, valSet *osttypes.ValidatorSet, genAccs require.NoError(t, err) pkAny, err := codectypes.NewAnyWithValue(pk) require.NoError(t, err) + valAddr := sdk.BytesToValAddress(val.Address) validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), + OperatorAddress: valAddr.String(), ConsensusPubkey: pkAny, Jailed: false, Status: stakingtypes.Bonded, @@ -116,7 +118,7 @@ func SetupWithGenesisValSet(t *testing.T, valSet *osttypes.ValidatorSet, genAccs MinSelfDelegation: sdk.ZeroInt(), } validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) + delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), valAddr, sdk.OneDec())) } @@ -199,7 +201,7 @@ func createRandomAccounts(accNum int) []sdk.AccAddress { testAddrs := make([]sdk.AccAddress, accNum) for i := 0; i < accNum; i++ { pk := ed25519.GenPrivKey().PubKey() - testAddrs[i] = sdk.AccAddress(pk.Address()) + testAddrs[i] = sdk.BytesToAccAddress(pk.Address()) } return testAddrs @@ -235,7 +237,7 @@ func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes // fill all the addresses with some coins, set the loose pool tokens simultaneously for _, pubKey := range pubKeys { - saveAccount(app, ctx, sdk.AccAddress(pubKey.Address()), initCoins) + saveAccount(app, ctx, sdk.BytesToAccAddress(pubKey.Address()), initCoins) } } @@ -246,6 +248,51 @@ func setTotalSupply(app *SimApp, ctx sdk.Context, accAmt sdk.Int, totalAccounts app.BankKeeper.SetSupply(ctx, banktypes.NewSupply(prevSupply.GetTotal().Add(totalSupply...))) } +// SortAddresses - Sorts Addresses +func SortAddresses(addrs []sdk.AccAddress) { + byteAddrs := make([][]byte, len(addrs)) + + for i, addr := range addrs { + byteAddrs[i] = addr.Bytes() + } + + SortByteArrays(byteAddrs) + + for i, byteAddr := range byteAddrs { + addrs[i] = sdk.AccAddress(string(byteAddr)) + } +} + +// implement `Interface` in sort package. +type sortByteArrays [][]byte + +func (b sortByteArrays) Len() int { + return len(b) +} + +func (b sortByteArrays) Less(i, j int) bool { + // bytes package already implements Comparable for []byte. + switch bytes.Compare(b[i], b[j]) { + case -1: + return true + case 0, 1: + return false + default: + panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") + } +} + +func (b sortByteArrays) Swap(i, j int) { + b[j], b[i] = b[i], b[j] +} + +// SortByteArrays - sorts the provided byte array +func SortByteArrays(src [][]byte) [][]byte { + sorted := sortByteArrays(src) + sort.Sort(sorted) + return sorted +} + // AddTestAddrs constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { @@ -269,6 +316,7 @@ func addTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int, stra saveAccount(app, ctx, addr, initCoins) } + SortAddresses(testAddrs) return testAddrs } @@ -287,7 +335,7 @@ func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress { valAddrs := make([]sdk.ValAddress, len(addrs)) for i, addr := range addrs { - valAddrs[i] = sdk.ValAddress(addr) + valAddrs[i] = addr.ToValAddress() } return valAddrs @@ -296,19 +344,19 @@ func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress { func TestAddr(addr string, bech string) (sdk.AccAddress, error) { res, err := sdk.AccAddressFromHex(addr) if err != nil { - return nil, err + return "", err } bechexpected := res.String() if bech != bechexpected { - return nil, fmt.Errorf("bech encoding doesn't match reference") + return "", fmt.Errorf("bech encoding doesn't match reference") } - bechres, err := sdk.AccAddressFromBech32(bech) + err = sdk.ValidateAccAddress(bech) if err != nil { - return nil, err + return "", err } - if !bytes.Equal(bechres, res) { - return nil, err + if !sdk.AccAddress(bech).Equals(res) { + return "", err } return res, nil diff --git a/testutil/network/network.go b/testutil/network/network.go index bffdfb84f9..5a95e740f8 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -297,7 +297,7 @@ func New(t *testing.T, cfg Config) *Network { require.NoError(t, err) createValMsg, err := stakingtypes.NewMsgCreateValidator( - sdk.ValAddress(addr), + addr.ToValAddress(), valPubKeys[i], sdk.NewCoin(cfg.BondDenom, cfg.BondedTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), @@ -355,7 +355,7 @@ func New(t *testing.T, cfg Config) *Network { P2PAddress: tmCfg.P2P.ListenAddress, APIAddress: apiAddr, Address: addr, - ValAddress: sdk.ValAddress(addr), + ValAddress: addr.ToValAddress(), } } diff --git a/testutil/testdata/tx.go b/testutil/testdata/tx.go index 19f7966cfb..a681661f8a 100644 --- a/testutil/testdata/tx.go +++ b/testutil/testdata/tx.go @@ -12,7 +12,7 @@ import ( func KeyTestPubAddr() (cryptotypes.PrivKey, cryptotypes.PubKey, sdk.AccAddress) { key := secp256k1.GenPrivKey() pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) + addr := sdk.BytesToAccAddress(pub.Address()) return key, pub, addr } @@ -53,12 +53,12 @@ func (msg *TestMsg) GetSignBytes() []byte { func (msg *TestMsg) GetSigners() []sdk.AccAddress { addrs := make([]sdk.AccAddress, len(msg.Signers)) for i, in := range msg.Signers { - addr, err := sdk.AccAddressFromBech32(in) + err := sdk.ValidateAccAddress(in) if err != nil { panic(err) } - addrs[i] = addr + addrs[i] = sdk.AccAddress(in) } return addrs diff --git a/types/address.go b/types/address.go index 2150a5bb0f..0f5a032534 100644 --- a/types/address.go +++ b/types/address.go @@ -1,7 +1,6 @@ package types import ( - "bytes" "encoding/hex" "encoding/json" "errors" @@ -29,8 +28,9 @@ const ( // config.SetFullFundraiserPath(yourFullFundraiserPath) // config.Seal() - // AddrLen defines a valid address length - AddrLen = 20 + BytesAddrLen = 20 + //AddrLen = len(Bech32MainPrefix) + 1 + 38 + // Bech32MainPrefix defines the main SDK Bech32 prefix of an account's address Bech32MainPrefix = "link" @@ -69,6 +69,8 @@ const ( Bech32PrefixConsPub = Bech32MainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic ) +const DefaultBech32CacheSize = 1 << 30 // maximum size of cache (1GB) + // Address is a common interface for different types of addresses used by the SDK type Address interface { Equals(Address) bool @@ -81,13 +83,13 @@ type Address interface { } // Ensure that different address types implement the interface -var _ Address = AccAddress{} -var _ Address = ValAddress{} -var _ Address = ConsAddress{} +var _ Address = AccAddress("") +var _ Address = ValAddress("") +var _ Address = ConsAddress("") -var _ yaml.Marshaler = AccAddress{} -var _ yaml.Marshaler = ValAddress{} -var _ yaml.Marshaler = ConsAddress{} +var _ yaml.Marshaler = AccAddress("") +var _ yaml.Marshaler = ValAddress("") +var _ yaml.Marshaler = ConsAddress("") // ---------------------------------------------------------------------------- // account @@ -119,6 +121,12 @@ func SetBech32Cache(size int64) { } } +// Used only for test cases +func InvalidateBech32Cache() { + bech32Cache.bech32ToAddrCache = nil + bech32Cache.addrToBech32Cache = nil +} + func (cache *Bech32Cache) GetAddr(bech32Addr string) ([]byte, bool) { if cache.bech32ToAddrCache != nil { rawAddr, ok := cache.bech32ToAddrCache.Get(bech32Addr) @@ -148,16 +156,14 @@ func (cache *Bech32Cache) Set(bech32Addr string, rawAddr []byte) { } } -const DefaultBech32CacheSize = 1 << 30 // maximum size of cache (1GB). - // AccAddress a wrapper around bytes meant to represent an account address. // When marshaled to a string or JSON, it uses Bech32. -type AccAddress []byte +type AccAddress string // AccAddressFromHex creates an AccAddress from a hex string. -func AccAddressFromHex(address string) (addr AccAddress, err error) { - bz, err := addressBytesFromHexString(address) - return AccAddress(bz), err +func AccAddressFromHex(addressBytesHex string) (addr AccAddress, err error) { + bz, err := addressBytesFromHexString(addressBytesHex) + return BytesToAccAddress(bz), err } // VerifyAddressFormat verifies that the provided bytes form a valid address @@ -168,67 +174,39 @@ func VerifyAddressFormat(bz []byte) error { if verifier != nil { return verifier(bz) } - if len(bz) != AddrLen { - return fmt.Errorf("incorrect address length (expected: %d, actual: %d)", AddrLen, len(bz)) + if len(bz) != BytesAddrLen { + if len(bz) == 0 { + return errors.New("empty address string is not allowed") + } + return fmt.Errorf("incorrect address length (expected: %d, actual: %d)", BytesAddrLen, len(bz)) } return nil } -// AccAddressFromBech32 creates an AccAddress from a Bech32 string. -func AccAddressFromBech32(bech32Addr string) (AccAddress, error) { - addr, ok := bech32Cache.GetAddr(bech32Addr) - if ok { - return addr, nil - } - - if len(strings.TrimSpace(bech32Addr)) == 0 { - return AccAddress{}, errors.New("empty address string is not allowed") - } - - bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix() - - bz, err := GetFromBech32(bech32Addr, bech32PrefixAccAddr) - if err != nil { - return nil, err - } - - err = VerifyAddressFormat(bz) - if err != nil { - return nil, err - } - bech32Cache.Set(bech32Addr, bz) - return bz, nil -} - // Returns boolean for whether two AccAddresses are Equal func (aa AccAddress) Equals(aa2 Address) bool { if aa.Empty() && aa2.Empty() { return true } - return bytes.Equal(aa.Bytes(), aa2.Bytes()) + return strings.EqualFold(aa.String(), aa2.String()) } // Returns boolean for whether an AccAddress is empty func (aa AccAddress) Empty() bool { - if aa == nil { - return true - } - - aa2 := AccAddress{} - return bytes.Equal(aa.Bytes(), aa2.Bytes()) + return len(string(aa)) == 0 } // Marshal returns the raw address bytes. It is needed for protobuf // compatibility. func (aa AccAddress) Marshal() ([]byte, error) { - return aa, nil + return []byte(aa.String()), nil } // Unmarshal sets the address to the given data. It is needed for protobuf // compatibility. func (aa *AccAddress) Unmarshal(data []byte) error { - *aa = data + *aa = AccAddress(data) return nil } @@ -246,21 +224,11 @@ func (aa AccAddress) MarshalYAML() (interface{}, error) { func (aa *AccAddress) UnmarshalJSON(data []byte) error { var s string err := json.Unmarshal(data, &s) - if err != nil { return err } - if s == "" { - *aa = AccAddress{} - return nil - } - - aa2, err := AccAddressFromBech32(s) - if err != nil { - return err - } - - *aa = aa2 + // TODO: address validation? + *aa = AccAddress(s) return nil } @@ -271,44 +239,29 @@ func (aa *AccAddress) UnmarshalYAML(data []byte) error { if err != nil { return err } - if s == "" { - *aa = AccAddress{} - return nil - } - - aa2, err := AccAddressFromBech32(s) - if err != nil { - return err - } - - *aa = aa2 + // TODO: address validation? + *aa = AccAddress(s) return nil } // Bytes returns the raw address bytes. func (aa AccAddress) Bytes() []byte { - return aa + return []byte(aa.String()) } // String implements the Stringer interface. func (aa AccAddress) String() string { - bech32Addr, ok := bech32Cache.GetBech32(aa) - if ok { - return bech32Addr - } - - if aa.Empty() { - return "" - } + return string(aa) +} - bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix() +func (aa AccAddress) ToValAddress() ValAddress { + bytes, _ := AccAddressToBytes(aa.String()) + return BytesToValAddress(bytes) +} - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixAccAddr, aa.Bytes()) - if err != nil { - panic(err) - } - bech32Cache.Set(bech32Addr, aa) - return bech32Addr +func (aa AccAddress) ToConsAddress() ConsAddress { + bytes, _ := AccAddressToBytes(aa.String()) + return BytesToConsAddress(bytes) } // Format implements the fmt.Formatter interface. @@ -324,29 +277,77 @@ func (aa AccAddress) Format(s fmt.State, verb rune) { } } +func BytesToAccAddress(addrBytes []byte) AccAddress { + bech32Addr, ok := bech32Cache.GetBech32(addrBytes) + if ok { + return AccAddress(bech32Addr) + } + bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix() + + bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixAccAddr, addrBytes) + if err != nil { + panic(err) + } + bech32Cache.Set(bech32Addr, addrBytes) + return AccAddress(bech32Addr) +} + +func AccAddressToBytes(bech32Addr string) ([]byte, error) { + bz, ok := bech32Cache.GetAddr(bech32Addr) + if ok { + return bz, nil + } + + if len(strings.TrimSpace(bech32Addr)) == 0 { + return nil, errors.New("empty address string is not allowed") + } + + bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix() + + bz, err := GetFromBech32(bech32Addr, bech32PrefixAccAddr) + if err != nil { + return nil, err + } + + err = VerifyAddressFormat(bz) + if err != nil { + return nil, err + } + bech32Cache.Set(bech32Addr, bz) + return bz, nil +} + +func ValidateAccAddress(bech32Addr string) error { + _, err := AccAddressToBytes(bech32Addr) + return err +} + // ---------------------------------------------------------------------------- // validator operator // ---------------------------------------------------------------------------- // ValAddress defines a wrapper around bytes meant to present a validator's // operator. When marshaled to a string or JSON, it uses Bech32. -type ValAddress []byte +type ValAddress string -// ValAddressFromHex creates a ValAddress from a hex string. -func ValAddressFromHex(address string) (addr ValAddress, err error) { - bz, err := addressBytesFromHexString(address) - return ValAddress(bz), err +func BytesToValAddress(addrBytes []byte) ValAddress { + bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix() + + bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixValAddr, addrBytes) + if err != nil { + panic(err) + } + return ValAddress(bech32Addr) } -// ValAddressFromBech32 creates a ValAddress from a Bech32 string. -func ValAddressFromBech32(address string) (addr ValAddress, err error) { - if len(strings.TrimSpace(address)) == 0 { - return ValAddress{}, errors.New("empty address string is not allowed") +func ValAddressToBytes(bech32Addr string) ([]byte, error) { + if len(strings.TrimSpace(bech32Addr)) == 0 { + return nil, errors.New("empty address string is not allowed") } bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix() - bz, err := GetFromBech32(address, bech32PrefixValAddr) + bz, err := GetFromBech32(bech32Addr, bech32PrefixValAddr) if err != nil { return nil, err } @@ -355,8 +356,18 @@ func ValAddressFromBech32(address string) (addr ValAddress, err error) { if err != nil { return nil, err } + return bz, nil +} - return ValAddress(bz), nil +func ValidateValAddress(bech32Addr string) error { + _, err := ValAddressToBytes(bech32Addr) + return err +} + +// ValAddressFromHex creates a ValAddress from a hex string. +func ValAddressFromHex(address string) (addr ValAddress, err error) { + bz, err := addressBytesFromHexString(address) + return BytesToValAddress(bz), err } // Returns boolean for whether two ValAddresses are Equal @@ -365,29 +376,24 @@ func (va ValAddress) Equals(va2 Address) bool { return true } - return bytes.Equal(va.Bytes(), va2.Bytes()) + return strings.EqualFold(va.String(), va2.String()) } // Returns boolean for whether an AccAddress is empty func (va ValAddress) Empty() bool { - if va == nil { - return true - } - - va2 := ValAddress{} - return bytes.Equal(va.Bytes(), va2.Bytes()) + return va == "" } // Marshal returns the raw address bytes. It is needed for protobuf // compatibility. func (va ValAddress) Marshal() ([]byte, error) { - return va, nil + return []byte(va), nil } // Unmarshal sets the address to the given data. It is needed for protobuf // compatibility. func (va *ValAddress) Unmarshal(data []byte) error { - *va = data + *va = ValAddress(data) return nil } @@ -404,66 +410,33 @@ func (va ValAddress) MarshalYAML() (interface{}, error) { // UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. func (va *ValAddress) UnmarshalJSON(data []byte) error { var s string - err := json.Unmarshal(data, &s) if err != nil { return err } - if s == "" { - *va = ValAddress{} - return nil - } - - va2, err := ValAddressFromBech32(s) - if err != nil { - return err - } - - *va = va2 + *va = ValAddress(s) return nil } // UnmarshalYAML unmarshals from YAML assuming Bech32 encoding. func (va *ValAddress) UnmarshalYAML(data []byte) error { var s string - err := yaml.Unmarshal(data, &s) if err != nil { return err } - if s == "" { - *va = ValAddress{} - return nil - } - - va2, err := ValAddressFromBech32(s) - if err != nil { - return err - } - - *va = va2 + *va = ValAddress(s) return nil } // Bytes returns the raw address bytes. func (va ValAddress) Bytes() []byte { - return va + return []byte(va.String()) } // String implements the Stringer interface. func (va ValAddress) String() string { - if va.Empty() { - return "" - } - - bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix() - - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixValAddr, va.Bytes()) - if err != nil { - panic(err) - } - - return bech32Addr + return string(va) } // Format implements the fmt.Formatter interface. @@ -479,29 +452,42 @@ func (va ValAddress) Format(s fmt.State, verb rune) { } } +func (va ValAddress) ToAccAddress() AccAddress { + bytes, _ := ValAddressToBytes(va.String()) + return BytesToAccAddress(bytes) +} + +func (va ValAddress) ToConsAddress() ConsAddress { + bytes, _ := ValAddressToBytes(va.String()) + return BytesToConsAddress(bytes) +} + // ---------------------------------------------------------------------------- // consensus node // ---------------------------------------------------------------------------- // ConsAddress defines a wrapper around bytes meant to present a consensus node. // When marshaled to a string or JSON, it uses Bech32. -type ConsAddress []byte +type ConsAddress string -// ConsAddressFromHex creates a ConsAddress from a hex string. -func ConsAddressFromHex(address string) (addr ConsAddress, err error) { - bz, err := addressBytesFromHexString(address) - return ConsAddress(bz), err +func BytesToConsAddress(addrBytes []byte) ConsAddress { + bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix() + + bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixConsAddr, addrBytes) + if err != nil { + panic(err) + } + return ConsAddress(bech32Addr) } -// ConsAddressFromBech32 creates a ConsAddress from a Bech32 string. -func ConsAddressFromBech32(address string) (addr ConsAddress, err error) { - if len(strings.TrimSpace(address)) == 0 { - return ConsAddress{}, errors.New("empty address string is not allowed") +func ConsAddressToBytes(bech32Addr string) ([]byte, error) { + if len(strings.TrimSpace(bech32Addr)) == 0 { + return nil, errors.New("empty address string is not allowed") } bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix() - bz, err := GetFromBech32(address, bech32PrefixConsAddr) + bz, err := GetFromBech32(bech32Addr, bech32PrefixConsAddr) if err != nil { return nil, err } @@ -510,13 +496,23 @@ func ConsAddressFromBech32(address string) (addr ConsAddress, err error) { if err != nil { return nil, err } + return bz, nil +} - return ConsAddress(bz), nil +// ConsAddressFromHex creates a ConsAddress from a hex string. +func ConsAddressFromHex(address string) (addr ConsAddress, err error) { + bz, err := addressBytesFromHexString(address) + return BytesToConsAddress(bz), err +} + +func ValidateConsAddress(bech32Addr string) error { + _, err := ConsAddressToBytes(bech32Addr) + return err } // get ConsAddress from pubkey func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress { - return ConsAddress(pubkey.Address()) + return BytesToConsAddress(pubkey.Address()) } // Returns boolean for whether two ConsAddress are Equal @@ -525,29 +521,24 @@ func (ca ConsAddress) Equals(ca2 Address) bool { return true } - return bytes.Equal(ca.Bytes(), ca2.Bytes()) + return strings.EqualFold(ca.String(), ca2.String()) } // Returns boolean for whether an ConsAddress is empty func (ca ConsAddress) Empty() bool { - if ca == nil { - return true - } - - ca2 := ConsAddress{} - return bytes.Equal(ca.Bytes(), ca2.Bytes()) + return ca == "" } // Marshal returns the raw address bytes. It is needed for protobuf // compatibility. func (ca ConsAddress) Marshal() ([]byte, error) { - return ca, nil + return []byte(ca), nil } // Unmarshal sets the address to the given data. It is needed for protobuf // compatibility. func (ca *ConsAddress) Unmarshal(data []byte) error { - *ca = data + *ca = ConsAddress(data) return nil } @@ -564,66 +555,33 @@ func (ca ConsAddress) MarshalYAML() (interface{}, error) { // UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. func (ca *ConsAddress) UnmarshalJSON(data []byte) error { var s string - err := json.Unmarshal(data, &s) if err != nil { return err } - if s == "" { - *ca = ConsAddress{} - return nil - } - - ca2, err := ConsAddressFromBech32(s) - if err != nil { - return err - } - - *ca = ca2 + *ca = ConsAddress(s) return nil } // UnmarshalYAML unmarshals from YAML assuming Bech32 encoding. func (ca *ConsAddress) UnmarshalYAML(data []byte) error { var s string - err := yaml.Unmarshal(data, &s) if err != nil { return err } - if s == "" { - *ca = ConsAddress{} - return nil - } - - ca2, err := ConsAddressFromBech32(s) - if err != nil { - return err - } - - *ca = ca2 + *ca = ConsAddress(s) return nil } // Bytes returns the raw address bytes. func (ca ConsAddress) Bytes() []byte { - return ca + return []byte(ca) } // String implements the Stringer interface. func (ca ConsAddress) String() string { - if ca.Empty() { - return "" - } - - bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix() - - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixConsAddr, ca.Bytes()) - if err != nil { - panic(err) - } - - return bech32Addr + return string(ca) } // Bech32ifyAddressBytes returns a bech32 representation of address bytes. diff --git a/types/address_test.go b/types/address_test.go index 8aca7ffafd..cdc7fe320f 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -49,25 +49,6 @@ func (s *addressTestSuite) testMarshal(original interface{}, res interface{}, ma s.Require().Equal(original, res) } -func (s *addressTestSuite) TestEmptyAddresses() { - s.T().Parallel() - s.Require().Equal((types.AccAddress{}).String(), "") - s.Require().Equal((types.ValAddress{}).String(), "") - s.Require().Equal((types.ConsAddress{}).String(), "") - - accAddr, err := types.AccAddressFromBech32("") - s.Require().True(accAddr.Empty()) - s.Require().Error(err) - - valAddr, err := types.ValAddressFromBech32("") - s.Require().True(valAddr.Empty()) - s.Require().Error(err) - - consAddr, err := types.ConsAddressFromBech32("") - s.Require().True(consAddr.Empty()) - s.Require().Error(err) -} - func (s *addressTestSuite) TestRandBech32PubkeyConsistency() { pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} @@ -113,9 +94,9 @@ func (s *addressTestSuite) TestRandBech32PubkeyConsistency() { func (s *addressTestSuite) TestYAMLMarshalers() { addr := secp256k1.GenPrivKey().PubKey().Address() - acc := types.AccAddress(addr) - val := types.ValAddress(addr) - cons := types.ConsAddress(addr) + acc := types.BytesToAccAddress(addr) + val := types.BytesToValAddress(addr) + cons := types.BytesToConsAddress(addr) got, _ := yaml.Marshal(&acc) s.Require().Equal(acc.String()+"\n", string(got)) @@ -134,18 +115,20 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { for i := 0; i < 1000; i++ { rand.Read(pub.Key) - acc := types.AccAddress(pub.Address()) - res := types.AccAddress{} + acc := types.BytesToAccAddress(pub.Address()) + res := types.AccAddress("") s.testMarshal(&acc, &res, acc.MarshalJSON, (&res).UnmarshalJSON) s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.AccAddressFromBech32(str) + err := types.ValidateAccAddress(str) s.Require().Nil(err) - s.Require().Equal(acc, res) + s.Require().Equal(acc, types.AccAddress(str)) - str = hex.EncodeToString(acc) + bytes, err := types.AccAddressToBytes(acc.String()) + s.Require().NoError(err) + str = hex.EncodeToString(bytes) res, err = types.AccAddressFromHex(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -155,11 +138,12 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { _, err := types.AccAddressFromHex(str) s.Require().NotNil(err) - _, err = types.AccAddressFromBech32(str) + err = types.ValidateAccAddress(str) s.Require().NotNil(err) - err = (*types.AccAddress)(nil).UnmarshalJSON([]byte("\"" + str + "\"")) - s.Require().NotNil(err) + addr := types.AccAddress("") + err = (&addr).UnmarshalJSON([]byte("\"" + str + "\"")) + s.Require().Nil(err) } _, err := types.AccAddressFromHex("") @@ -173,18 +157,19 @@ func (s *addressTestSuite) TestValAddr() { for i := 0; i < 20; i++ { rand.Read(pub.Key) - acc := types.ValAddress(pub.Address()) - res := types.ValAddress{} + acc := types.BytesToValAddress(pub.Address()) + res := types.ValAddress("") s.testMarshal(&acc, &res, acc.MarshalJSON, (&res).UnmarshalJSON) s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.ValAddressFromBech32(str) + res2, err := types.ValAddressToBytes(str) s.Require().Nil(err) - s.Require().Equal(acc, res) + s.Require().Equal(acc, types.BytesToValAddress(res2)) - str = hex.EncodeToString(acc) + bytes, _ := types.ValAddressToBytes(acc.String()) + str = hex.EncodeToString(bytes) res, err = types.ValAddressFromHex(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -195,11 +180,12 @@ func (s *addressTestSuite) TestValAddr() { _, err := types.ValAddressFromHex(str) s.Require().NotNil(err) - _, err = types.ValAddressFromBech32(str) + err = types.ValidateValAddress(str) s.Require().NotNil(err) - err = (*types.ValAddress)(nil).UnmarshalJSON([]byte("\"" + str + "\"")) - s.Require().NotNil(err) + addr := types.ValAddress("") + err = (&addr).UnmarshalJSON([]byte("\"" + str + "\"")) + s.Require().Nil(err) } // test empty string @@ -214,18 +200,19 @@ func (s *addressTestSuite) TestConsAddress() { for i := 0; i < 20; i++ { rand.Read(pub.Key[:]) - acc := types.ConsAddress(pub.Address()) - res := types.ConsAddress{} + acc := types.BytesToConsAddress(pub.Address()) + res := types.ConsAddress("") s.testMarshal(&acc, &res, acc.MarshalJSON, (&res).UnmarshalJSON) s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.ConsAddressFromBech32(str) + res2, err := types.ConsAddressToBytes(str) s.Require().Nil(err) - s.Require().Equal(acc, res) + s.Require().Equal(acc, types.BytesToConsAddress(res2)) - str = hex.EncodeToString(acc) + bytes, _ := types.ConsAddressToBytes(acc.String()) + str = hex.EncodeToString(bytes) res, err = types.ConsAddressFromHex(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -235,11 +222,12 @@ func (s *addressTestSuite) TestConsAddress() { _, err := types.ConsAddressFromHex(str) s.Require().NotNil(err) - _, err = types.ConsAddressFromBech32(str) + err = types.ValidateConsAddress(str) s.Require().NotNil(err) - err = (*types.ConsAddress)(nil).UnmarshalJSON([]byte("\"" + str + "\"")) - s.Require().NotNil(err) + consAddr := types.ConsAddress("") + err = (&consAddr).UnmarshalJSON([]byte("\"" + str + "\"")) + s.Require().Nil(err) } // test empty string @@ -272,7 +260,7 @@ func (s *addressTestSuite) TestConfiguredPrefix() { prefix+types.PrefixAccount, prefix+types.PrefixPublic) - acc := types.AccAddress(pub.Address()) + acc := types.BytesToAccAddress(pub.Address()) s.Require().True(strings.HasPrefix( acc.String(), prefix+types.PrefixAccount), acc.String()) @@ -286,7 +274,7 @@ func (s *addressTestSuite) TestConfiguredPrefix() { prefix+types.PrefixValidator+types.PrefixAddress, prefix+types.PrefixValidator+types.PrefixPublic) - val := types.ValAddress(pub.Address()) + val := types.BytesToValAddress(pub.Address()) s.Require().True(strings.HasPrefix( val.String(), prefix+types.PrefixValidator+types.PrefixAddress)) @@ -300,7 +288,7 @@ func (s *addressTestSuite) TestConfiguredPrefix() { prefix+types.PrefixConsensus+types.PrefixAddress, prefix+types.PrefixConsensus+types.PrefixPublic) - cons := types.ConsAddress(pub.Address()) + cons := types.BytesToConsAddress(pub.Address()) s.Require().True(strings.HasPrefix( cons.String(), prefix+types.PrefixConsensus+types.PrefixAddress)) @@ -319,21 +307,21 @@ func (s *addressTestSuite) TestAddressInterface() { rand.Read(pub.Key) addrs := []types.Address{ - types.ConsAddress(pub.Address()), - types.ValAddress(pub.Address()), - types.AccAddress(pub.Address()), + types.BytesToConsAddress(pub.Address()), + types.BytesToValAddress(pub.Address()), + types.BytesToAccAddress(pub.Address()), } for _, addr := range addrs { switch addr := addr.(type) { case types.AccAddress: - _, err := types.AccAddressFromBech32(addr.String()) + err := types.ValidateAccAddress(addr.String()) s.Require().Nil(err) case types.ValAddress: - _, err := types.ValAddressFromBech32(addr.String()) + err := types.ValidateValAddress(addr.String()) s.Require().Nil(err) case types.ConsAddress: - _, err := types.ConsAddressFromBech32(addr.String()) + err := types.ValidateConsAddress(addr.String()) s.Require().Nil(err) default: s.T().Fail() @@ -361,23 +349,26 @@ func (s *addressTestSuite) TestVerifyAddressFormat() { func (s *addressTestSuite) TestCustomAddressVerifier() { // Create a 10 byte address addr := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - accBech := types.AccAddress(addr).String() - valBech := types.ValAddress(addr).String() - consBech := types.ConsAddress(addr).String() + accBech := types.BytesToAccAddress(addr).String() + valBech := types.BytesToValAddress(addr).String() + consBech := types.BytesToConsAddress(addr).String() // Verifiy that the default logic rejects this 10 byte address err := types.VerifyAddressFormat(addr) s.Require().NotNil(err) - _, err = types.AccAddressFromBech32(accBech) + err = types.ValidateAccAddress(accBech) + if err == nil { + fmt.Printf("\n") + } s.Require().NotNil(err) - _, err = types.ValAddressFromBech32(valBech) + err = types.ValidateValAddress(valBech) s.Require().NotNil(err) - _, err = types.ConsAddressFromBech32(consBech) + err = types.ValidateConsAddress(consBech) s.Require().NotNil(err) // Set a custom address verifier that accepts 10 or 20 byte addresses types.GetConfig().SetAddressVerifier(func(bz []byte) error { n := len(bz) - if n == 10 || n == types.AddrLen { + if n == 10 || n == types.BytesAddrLen { return nil } return fmt.Errorf("incorrect address length %d", n) @@ -386,11 +377,11 @@ func (s *addressTestSuite) TestCustomAddressVerifier() { // Verifiy that the custom logic accepts this 10 byte address err = types.VerifyAddressFormat(addr) s.Require().Nil(err) - _, err = types.AccAddressFromBech32(accBech) + err = types.ValidateAccAddress(accBech) s.Require().Nil(err) - _, err = types.ValAddressFromBech32(valBech) + err = types.ValidateValAddress(valBech) s.Require().Nil(err) - _, err = types.ConsAddressFromBech32(consBech) + err = types.ValidateConsAddress(consBech) s.Require().Nil(err) } @@ -461,14 +452,14 @@ func (s *addressTestSuite) TestMustBech32ifyAddressBytes() { func (s *addressTestSuite) TestAddressTypesEquals() { addr1 := secp256k1.GenPrivKey().PubKey().Address() - accAddr1 := types.AccAddress(addr1) - consAddr1 := types.ConsAddress(addr1) - valAddr1 := types.ValAddress(addr1) + accAddr1 := types.BytesToAccAddress(addr1) + consAddr1 := types.BytesToConsAddress(addr1) + valAddr1 := types.BytesToValAddress(addr1) addr2 := secp256k1.GenPrivKey().PubKey().Address() - accAddr2 := types.AccAddress(addr2) - consAddr2 := types.ConsAddress(addr2) - valAddr2 := types.ValAddress(addr2) + accAddr2 := types.BytesToAccAddress(addr2) + consAddr2 := types.BytesToConsAddress(addr2) + valAddr2 := types.BytesToValAddress(addr2) // equality s.Require().True(accAddr1.Equals(accAddr1)) @@ -476,20 +467,9 @@ func (s *addressTestSuite) TestAddressTypesEquals() { s.Require().True(valAddr1.Equals(valAddr1)) // emptiness - s.Require().True(types.AccAddress{}.Equals(types.AccAddress{})) - s.Require().True(types.AccAddress{}.Equals(types.AccAddress(nil))) - s.Require().True(types.AccAddress(nil).Equals(types.AccAddress{})) - s.Require().True(types.AccAddress(nil).Equals(types.AccAddress(nil))) - - s.Require().True(types.ConsAddress{}.Equals(types.ConsAddress{})) - s.Require().True(types.ConsAddress{}.Equals(types.ConsAddress(nil))) - s.Require().True(types.ConsAddress(nil).Equals(types.ConsAddress{})) - s.Require().True(types.ConsAddress(nil).Equals(types.ConsAddress(nil))) - - s.Require().True(types.ValAddress{}.Equals(types.ValAddress{})) - s.Require().True(types.ValAddress{}.Equals(types.ValAddress(nil))) - s.Require().True(types.ValAddress(nil).Equals(types.ValAddress{})) - s.Require().True(types.ValAddress(nil).Equals(types.ValAddress(nil))) + s.Require().True(types.AccAddress("").Equals(types.AccAddress(""))) + s.Require().True(types.ConsAddress("").Equals(types.ConsAddress(""))) + s.Require().True(types.ValAddress("").Equals(types.ValAddress(""))) s.Require().False(accAddr1.Equals(accAddr2)) s.Require().Equal(accAddr1.Equals(accAddr2), accAddr2.Equals(accAddr1)) @@ -500,15 +480,16 @@ func (s *addressTestSuite) TestAddressTypesEquals() { } func (s *addressTestSuite) TestNilAddressTypesEmpty() { - s.Require().True(types.AccAddress(nil).Empty()) - s.Require().True(types.ConsAddress(nil).Empty()) - s.Require().True(types.ValAddress(nil).Empty()) + s.Require().True(types.AccAddress("").Empty()) + s.Require().True(types.ConsAddress("").Empty()) + s.Require().True(types.ValAddress("").Empty()) } func (s *addressTestSuite) TestGetConsAddress() { pk := secp256k1.GenPrivKey().PubKey() s.Require().NotEqual(types.GetConsAddress(pk), pk.Address()) - s.Require().True(bytes.Equal(types.GetConsAddress(pk).Bytes(), pk.Address().Bytes())) + consBytes, _ := types.ConsAddressToBytes(types.GetConsAddress(pk).String()) + s.Require().True(bytes.Equal(consBytes, pk.Address())) s.Require().Panics(func() { types.GetConsAddress(cryptotypes.PubKey(nil)) }) } @@ -528,27 +509,28 @@ func (s *addressTestSuite) TestBech32Cache() { s.T().Log("access bech32ToAddrCache before access addrToBech32Cache") { rand.Read(pub.Key) - addr := types.AccAddress(pub.Address()) + addr := types.BytesToAccAddress(pub.Address()) bech32Addr := addr.String() types.SetBech32Cache(types.DefaultBech32CacheSize) - rawAddr, err := types.AccAddressFromBech32(bech32Addr) + rawAddr, err := types.AccAddressToBytes(bech32Addr) s.Require().Nil(err) - require.Equal(s.T(), addr, rawAddr) + require.Equal(s.T(), addr, types.BytesToAccAddress(rawAddr)) require.Equal(s.T(), bech32Addr, addr.String()) } s.T().Log("access addrToBech32Cache before access bech32ToAddrCache") { rand.Read(pub.Key) - addr := types.AccAddress(pub.Address()) + addr := types.BytesToAccAddress(pub.Address()) bech32Addr := addr.String() types.SetBech32Cache(types.DefaultBech32CacheSize) require.Equal(s.T(), bech32Addr, addr.String()) - rawAddr, err := types.AccAddressFromBech32(bech32Addr) + rawAddr, err := types.AccAddressToBytes(bech32Addr) s.Require().Nil(err) - require.Equal(s.T(), addr, rawAddr) + require.Equal(s.T(), addr, types.BytesToAccAddress(rawAddr)) } + types.InvalidateBech32Cache() } diff --git a/types/query/filtered_pagination_test.go b/types/query/filtered_pagination_test.go index 37319ad074..5056849b0d 100644 --- a/types/query/filtered_pagination_test.go +++ b/types/query/filtered_pagination_test.go @@ -8,10 +8,11 @@ import ( sdk "github.com/line/lfb-sdk/types" "github.com/line/lfb-sdk/types/query" authtypes "github.com/line/lfb-sdk/x/auth/types" + "github.com/line/lfb-sdk/x/bank/keeper" "github.com/line/lfb-sdk/x/bank/types" ) -var addr1 = sdk.AccAddress([]byte("addr1")) +var addr1 = sdk.BytesToAccAddress([]byte("addr1")) func (s *paginationTestSuite) TestFilteredPaginations() { app, ctx, appCodec := setupTest() @@ -27,7 +28,7 @@ func (s *paginationTestSuite) TestFilteredPaginations() { balances = append(balances, sdk.NewInt64Coin(denom, 250)) } - addr1 := sdk.AccAddress([]byte("addr1")) + addr1 := sdk.BytesToAccAddress([]byte("addr1")) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) s.Require().NoError(app.BankKeeper.SetBalances(ctx, addr1, balances)) @@ -111,7 +112,7 @@ func ExampleFilteredPaginate() { pageReq := &query.PageRequest{Key: nil, Limit: 1, CountTotal: true} store := ctx.KVStore(app.GetKey(authtypes.StoreKey)) balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr1.Bytes()) + accountStore := prefix.NewStore(balancesStore, keeper.AddressToPrefixKey(addr1)) var balResult sdk.Coins pageRes, err := query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { @@ -143,7 +144,7 @@ func ExampleFilteredPaginate() { func execFilterPaginate(store sdk.KVStore, pageReq *query.PageRequest, appCodec codec.Marshaler) (balances sdk.Coins, res *query.PageResponse, err error) { balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr1.Bytes()) + accountStore := prefix.NewStore(balancesStore, keeper.AddressToPrefixKey(addr1)) var balResult sdk.Coins res, err = query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { diff --git a/types/query/pagination_test.go b/types/query/pagination_test.go index 7981dc1d09..20b62d5159 100644 --- a/types/query/pagination_test.go +++ b/types/query/pagination_test.go @@ -75,7 +75,7 @@ func (s *paginationTestSuite) TestPagination() { balances = append(balances, sdk.NewInt64Coin(denom, 100)) } - addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr1 := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) s.Require().NoError(app.BankKeeper.SetBalances(ctx, addr1, balances)) @@ -193,7 +193,7 @@ func ExamplePaginate() { balResult := sdk.NewCoins() authStore := ctx.KVStore(app.GetKey(authtypes.StoreKey)) balancesStore := prefix.NewStore(authStore, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr1.Bytes()) + accountStore := prefix.NewStore(balancesStore, bankkeeper.AddressToPrefixKey(addr1)) pageRes, err := query.Paginate(accountStore, request.Pagination, func(key []byte, value []byte) error { var tempRes sdk.Coin err := app.AppCodec().UnmarshalBinaryBare(value, &tempRes) diff --git a/types/rest/rest.go b/types/rest/rest.go index d87d6f79e5..292f51357d 100644 --- a/types/rest/rest.go +++ b/types/rest/rest.go @@ -124,7 +124,7 @@ func (br BaseReq) ValidateBasic(w http.ResponseWriter) bool { } } - if _, err := sdk.AccAddressFromBech32(br.From); err != nil || len(br.From) == 0 { + if err := sdk.ValidateAccAddress(br.From); err != nil || len(br.From) == 0 { WriteErrorResponse(w, http.StatusUnauthorized, fmt.Sprintf("invalid from address: %s", br.From)) return false } diff --git a/types/rest/rest_test.go b/types/rest/rest_test.go index a0bda34bf2..cf0abee573 100644 --- a/types/rest/rest_test.go +++ b/types/rest/rest_test.go @@ -180,10 +180,10 @@ func TestProcessPostResponse(t *testing.T) { t.Parallel() type mockAccount struct { - Address types.AccAddress `json:"address"` - Coins types.Coins `json:"coins"` - PubKey cryptotypes.PubKey `json:"public_key"` - Sequence uint64 `json:"sequence"` + Address types.AccAddress `json:"address"` + Coins types.Coins `json:"coins"` + PubKey cryptotypes.PubKey `json:"public_key"` + Sequence uint64 `json:"sequence"` } // setup diff --git a/types/simulation/account.go b/types/simulation/account.go index f8712c3c29..e99dd3146d 100644 --- a/types/simulation/account.go +++ b/types/simulation/account.go @@ -43,7 +43,7 @@ func RandomAccounts(r *rand.Rand, n int) []Account { accs[i].PrivKey = secp256k1.GenPrivKeyFromSecret(privkeySeed) accs[i].PubKey = accs[i].PrivKey.PubKey() - accs[i].Address = sdk.AccAddress(accs[i].PubKey.Address()) + accs[i].Address = sdk.BytesToAccAddress(accs[i].PubKey.Address()) accs[i].ConsKey = ed25519.GenPrivKeyFromSecret(privkeySeed) } diff --git a/types/simulation/account_test.go b/types/simulation/account_test.go index fb28b8c43b..0a102468ad 100644 --- a/types/simulation/account_test.go +++ b/types/simulation/account_test.go @@ -47,7 +47,7 @@ func TestFindAccountEmptySlice(t *testing.T) { require.Equal(t, 1, len(accs)) acc, found := simulation.FindAccount(nil, accs[0].Address) require.False(t, found) - require.Nil(t, acc.Address) + require.Equal(t, acc.Address, sdk.AccAddress("")) require.Nil(t, acc.PrivKey) require.Nil(t, acc.PubKey) } diff --git a/types/tx/tx.pb.go b/types/tx/tx.pb.go index 95298d2b2a..1b65656d0a 100644 --- a/types/tx/tx.pb.go +++ b/types/tx/tx.pb.go @@ -245,7 +245,7 @@ type TxBody struct { // is referred to as the primary signer and pays the fee for the whole // transaction. Messages []*types.Any `protobuf:"bytes,1,rep,name=messages,proto3" json:"messages,omitempty"` - // sig block height is available between current block height and current block height - `VALID_SIG_BLOCK_DURATION` + // sig block height is available between current block height and current block height - `VALID_SIG_BLOCK_PERIOD` // this is used for distinguish signatures instead of account number. this is mandatory. SigBlockHeight uint64 `protobuf:"varint,2,opt,name=sig_block_height,json=sigBlockHeight,proto3" json:"sig_block_height,omitempty"` // memo is any arbitrary memo to be added to the transaction diff --git a/types/tx/types.go b/types/tx/types.go index c6631c5e0f..72f6a4b12a 100644 --- a/types/tx/types.go +++ b/types/tx/types.go @@ -80,7 +80,7 @@ func (t *Tx) ValidateBasic() error { } if fee.Payer != "" { - _, err := sdk.AccAddressFromBech32(fee.Payer) + err := sdk.ValidateAccAddress(fee.Payer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid fee payer address (%s)", err) } @@ -121,11 +121,7 @@ func (t *Tx) GetSigners() []sdk.AccAddress { // ensure any specified fee payer is included in the required signers (at the end) feePayer := t.AuthInfo.Fee.Payer if feePayer != "" && !seen[feePayer] { - payerAddr, err := sdk.AccAddressFromBech32(feePayer) - if err != nil { - panic(err) - } - signers = append(signers, payerAddr) + signers = append(signers, sdk.AccAddress(feePayer)) seen[feePayer] = true } diff --git a/types/tx_msg_test.go b/types/tx_msg_test.go index 4732dedc26..31d6c85153 100644 --- a/types/tx_msg_test.go +++ b/types/tx_msg_test.go @@ -19,7 +19,7 @@ func TestMsgTestSuite(t *testing.T) { func (s *testMsgSuite) TestMsg() { addr := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19} - accAddr := sdk.AccAddress(addr) + accAddr := sdk.BytesToAccAddress(addr) msg := testdata.NewTestMsg(accAddr) s.Require().NotNil(msg) diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 411c6727a8..6b11478f3d 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -92,7 +92,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigErrors() { // Variable data per test case var ( privs []cryptotypes.PrivKey - sbh []uint64 + sbh []uint64 accSeqs []uint64 ) @@ -159,6 +159,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigErrors() { // Test logic around sig block height checking with one signer and many signers. func (suite *AnteTestSuite) TestAnteHandlerSigBlockHeight() { suite.SetupTest(false) // reset + suite.ctx = suite.ctx.WithBlockHeight(200) // init block height is 200 // Same data for every test cases @@ -168,7 +169,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigBlockHeight() { // Variable data per test case var ( - sbh []uint64 + sbh []uint64 msgs []sdk.Msg privs []cryptotypes.PrivKey accSeqs []uint64 diff --git a/x/auth/ante/fee.go b/x/auth/ante/fee.go index 0ce927ac4d..cd9702c536 100644 --- a/x/auth/ante/fee.go +++ b/x/auth/ante/fee.go @@ -76,7 +76,7 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bo return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx") } - if addr := dfd.ak.GetModuleAddress(types.FeeCollectorName); addr == nil { + if addr := dfd.ak.GetModuleAddress(types.FeeCollectorName); addr.Empty() { panic(fmt.Sprintf("%s module account has not been set", types.FeeCollectorName)) } diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index bb7e0fe827..cc8cd995c6 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -72,7 +72,7 @@ func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b pk = simSecp256k1Pubkey } // Only make check if simulate=false - if !simulate && !bytes.Equal(pk.Address(), signers[i]) { + if !simulate && !sdk.BytesToAccAddress(pk.Address()).Equals(signers[i]) { return ctx, sdkerrors.Wrapf(sdkerrors.ErrInvalidPubKey, "pubKey does not match signer address %s with signer index: %d", signers[i], i) } diff --git a/x/auth/ante/sigverify_test.go b/x/auth/ante/sigverify_test.go index bfa02f2273..63a7516f9f 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -299,7 +299,7 @@ func (suite *AnteTestSuite) runSigDecorators(params types.Params, _ bool, privs accSeqs := make([]uint64, len(privs)) // set accounts and create msg for each address for i, priv := range privs { - addr := sdk.AccAddress(priv.PubKey().Address()) + addr := sdk.BytesToAccAddress(priv.PubKey().Address()) acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) suite.app.AccountKeeper.SetAccount(suite.ctx, acc) msgs[i] = testdata.NewTestMsg(addr) @@ -340,7 +340,7 @@ func (suite *AnteTestSuite) TestIncrementSequenceDecorator() { msgs := []sdk.Msg{testdata.NewTestMsg(addr)} suite.Require().NoError(suite.txBuilder.SetMsgs(msgs...)) privs := []cryptotypes.PrivKey{priv} - sbh := []uint64{ 1 } + sbh := []uint64{1} accSeqs := []uint64{suite.app.AccountKeeper.GetAccount(suite.ctx, addr).GetSequence()} feeAmount := testdata.NewTestFeeAmount() gasLimit := testdata.NewTestGasLimit() diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index 6c59ce36e5..4f260e3189 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -110,8 +110,8 @@ func (suite *AnteTestSuite) CreateTestTx(privs []cryptotypes.PrivKey, sbh []uint sigsV2 = []signing.SignatureV2{} for i, priv := range privs { signerData := xauthsigning.SignerData{ - ChainID: chainID, - Sequence: accSeqs[i], + ChainID: chainID, + Sequence: accSeqs[i], } sigV2, err := tx.SignWithPrivKey( suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), signerData, diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 3f4bb17faa..448f663249 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -960,11 +960,12 @@ func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { // Create new file with tx builder := txCfg.NewTxBuilder() builder.SetGasLimit(200000) - from, err := sdk.AccAddressFromBech32("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") + fromBytes, err := sdk.AccAddressToBytes("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") require.NoError(t, err) - to, err := sdk.AccAddressFromBech32("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") + toBytes, err := sdk.AccAddressToBytes("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") require.NoError(t, err) - err = builder.SetMsgs(banktypes.NewMsgSend(from, to, sdk.Coins{sdk.NewInt64Coin("stake", 10000)})) + err = builder.SetMsgs(banktypes.NewMsgSend(sdk.BytesToAccAddress(fromBytes), + sdk.BytesToAccAddress(toBytes), sdk.Coins{sdk.NewInt64Coin("stake", 10000)})) require.NoError(t, err) txContents, err := txCfg.TxJSONEncoder()(builder.GetTx()) require.NoError(t, err) @@ -1202,7 +1203,7 @@ func (s *IntegrationTestSuite) TestNewEmptyTxCmd() { }, { "no from", - sdk.AccAddress{}, + sdk.AccAddress(""), []string{ fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 0b93b0b104..8644690815 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -84,11 +84,10 @@ func GetAccountCmd() *cobra.Command { if err != nil { return err } - key, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { + if err = sdk.ValidateAccAddress(args[0]); err != nil { return err } - + key := sdk.AccAddress(args[0]) queryClient := types.NewQueryClient(clientCtx) res, err := queryClient.Account(context.Background(), &types.QueryAccountRequest{Address: key.String()}) if err != nil { diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 66029022a7..2630ff9fdc 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -73,10 +73,7 @@ func makeSignBatchCmd() func(cmd *cobra.Command, args []string) error { // validate multisig address if there's any if ms, _ := cmd.Flags().GetString(flagMultisig); ms != "" { - multisigAddr, err = sdk.AccAddressFromBech32(ms) - if err != nil { - return err - } + multisigAddr = sdk.AccAddress(ms) } // prepare output document @@ -235,11 +232,7 @@ func makeSignCmd() func(cmd *cobra.Command, args []string) error { overwrite, _ := f.GetBool(flagOverwrite) if multisigAddrStr != "" { - var multisigAddr sdk.AccAddress - multisigAddr, err = sdk.AccAddressFromBech32(multisigAddrStr) - if err != nil { - return err - } + multisigAddr := sdk.AccAddress(multisigAddrStr) err = authclient.SignTxWithSignerAddress( txF, clientCtx, multisigAddr, fromName, txBuilder, clientCtx.Offline, overwrite) printSignatureOnly = true diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index e1156c2cfe..00d21e9e57 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -87,7 +87,7 @@ func printAndValidateSigs( pubKey = sig.PubKey multiSigHeader string multiSigMsg string - sigAddr = sdk.AccAddress(pubKey.Address()) + sigAddr = sdk.BytesToAccAddress(pubKey.Address()) sigSanity = "OK" ) diff --git a/x/auth/client/rest/query.go b/x/auth/client/rest/query.go index 3005d402eb..553786eec6 100644 --- a/x/auth/client/rest/query.go +++ b/x/auth/client/rest/query.go @@ -24,10 +24,7 @@ func QueryAccountRequestHandlerFn(storeName string, clientCtx client.Context) ht vars := mux.Vars(r) bech32addr := vars["address"] - addr, err := sdk.AccAddressFromBech32(bech32addr) - if rest.CheckInternalServerError(w, err) { - return - } + addr := sdk.AccAddress(bech32addr) clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 37cb889901..e3a6beb1e5 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -51,7 +51,7 @@ func SignTx(txFactory tx.Factory, clientCtx client.Context, name string, stdTx c if err != nil { return err } - addr := sdk.AccAddress(info.GetPubKey().Address()) + addr := sdk.BytesToAccAddress(info.GetPubKey().Address()) if !isTxSigner(addr, stdTx.GetTx().GetSigners()) { return fmt.Errorf("%s: %s", sdkerrors.ErrorInvalidSigner, name) } diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index afb3ffd88b..2a1f441c3c 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -22,7 +22,7 @@ import ( var ( priv = ed25519.GenPrivKey() - addr = sdk.AccAddress(priv.PubKey().Address()) + addr = sdk.BytesToAccAddress(priv.PubKey().Address()) ) func TestParseQueryResponse(t *testing.T) { diff --git a/x/auth/keeper/grpc_query.go b/x/auth/keeper/grpc_query.go index d6a541294e..876dd91951 100644 --- a/x/auth/keeper/grpc_query.go +++ b/x/auth/keeper/grpc_query.go @@ -24,12 +24,10 @@ func (ak AccountKeeper) Account(c context.Context, req *types.QueryAccountReques } ctx := sdk.UnwrapSDKContext(c) - addr, err := sdk.AccAddressFromBech32(req.Address) - - if err != nil { + if err := sdk.ValidateAccAddress(req.Address); err != nil { return nil, err } - account := ak.GetAccount(ctx, addr) + account := ak.GetAccount(ctx, sdk.AccAddress(req.Address)) if account == nil { return nil, status.Errorf(codes.NotFound, "account %s not found", req.Address) } diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index d0c7f2aa5b..a170453a94 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -119,7 +119,7 @@ func (ak AccountKeeper) ValidatePermissions(macc types.ModuleAccountI) error { func (ak AccountKeeper) GetModuleAddress(moduleName string) sdk.AccAddress { permAddr, ok := ak.permAddrs[moduleName] if !ok { - return nil + return "" } return permAddr.GetAddress() @@ -139,7 +139,7 @@ func (ak AccountKeeper) GetModuleAddressAndPermissions(moduleName string) (addr // registered permissions func (ak AccountKeeper) GetModuleAccountAndPermissions(ctx sdk.Context, moduleName string) (types.ModuleAccountI, []string) { addr, perms := ak.GetModuleAddressAndPermissions(moduleName) - if addr == nil { + if addr.Empty() { return nil, []string{} } diff --git a/x/auth/keeper/querier.go b/x/auth/keeper/querier.go index 1e80fb6063..f58507dd82 100644 --- a/x/auth/keeper/querier.go +++ b/x/auth/keeper/querier.go @@ -31,12 +31,12 @@ func queryAccount(ctx sdk.Context, req abci.RequestQuery, k AccountKeeper, legac return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - addr, err := sdk.AccAddressFromBech32(params.Address) + err := sdk.ValidateAccAddress(params.Address) if err != nil { return nil, err } - account := k.GetAccount(ctx, addr) + account := k.GetAccount(ctx, sdk.AccAddress(params.Address)) if account == nil { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", params.Address) } diff --git a/x/auth/legacy/legacytx/amino_signing_test.go b/x/auth/legacy/legacytx/amino_signing_test.go index 5ab4543f2a..bb2bd350d4 100644 --- a/x/auth/legacy/legacytx/amino_signing_test.go +++ b/x/auth/legacy/legacytx/amino_signing_test.go @@ -14,9 +14,9 @@ import ( func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) { priv1 := secp256k1.GenPrivKey() - addr1 := sdk.AccAddress(priv1.PubKey().Address()) + addr1 := sdk.BytesToAccAddress(priv1.PubKey().Address()) priv2 := secp256k1.GenPrivKey() - addr2 := sdk.AccAddress(priv2.PubKey().Address()) + addr2 := sdk.BytesToAccAddress(priv2.PubKey().Address()) coins := sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} @@ -47,8 +47,8 @@ func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) { handler := stdTxSignModeHandler{} signingData := signing.SignerData{ - ChainID: chainId, - Sequence: seqNum, + ChainID: chainId, + Sequence: seqNum, } signBz, err := handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signingData, tx) require.NoError(t, err) diff --git a/x/auth/legacy/legacytx/stdtx.go b/x/auth/legacy/legacytx/stdtx.go index f8b959cb05..f8447bcbe4 100644 --- a/x/auth/legacy/legacytx/stdtx.go +++ b/x/auth/legacy/legacytx/stdtx.go @@ -273,12 +273,12 @@ func (tx StdTx) FeePayer() sdk.AccAddress { if tx.GetSigners() != nil { return tx.GetSigners()[0] } - return sdk.AccAddress{} + return "" } // FeeGranter always returns nil for StdTx func (tx StdTx) FeeGranter() sdk.AccAddress { - return nil + return "" } func (tx StdTx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { diff --git a/x/auth/legacy/legacytx/stdtx_test.go b/x/auth/legacy/legacytx/stdtx_test.go index f0dabb4c79..9c802c3cdf 100644 --- a/x/auth/legacy/legacytx/stdtx_test.go +++ b/x/auth/legacy/legacytx/stdtx_test.go @@ -23,7 +23,7 @@ import ( var ( priv = ed25519.GenPrivKey() - addr = sdk.AccAddress(priv.PubKey().Address()) + addr = sdk.BytesToAccAddress(priv.PubKey().Address()) ) func init() { diff --git a/x/auth/signing/handler_map_test.go b/x/auth/signing/handler_map_test.go index 1577c33312..b8de391aec 100644 --- a/x/auth/signing/handler_map_test.go +++ b/x/auth/signing/handler_map_test.go @@ -24,9 +24,9 @@ func MakeTestHandlerMap() signing.SignModeHandler { func TestHandlerMap_GetSignBytes(t *testing.T) { priv1 := secp256k1.GenPrivKey() - addr1 := sdk.AccAddress(priv1.PubKey().Address()) + addr1 := sdk.BytesToAccAddress(priv1.PubKey().Address()) priv2 := secp256k1.GenPrivKey() - addr2 := sdk.AccAddress(priv2.PubKey().Address()) + addr2 := sdk.BytesToAccAddress(priv2.PubKey().Address()) coins := sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} @@ -61,8 +61,8 @@ func TestHandlerMap_GetSignBytes(t *testing.T) { aminoJSONHandler := legacytx.NewStdTxSignModeHandler() signingData := signing.SignerData{ - ChainID: chainId, - Sequence: seqNum, + ChainID: chainId, + Sequence: seqNum, } signBz, err := handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signingData, tx) require.NoError(t, err) diff --git a/x/auth/signing/verify_test.go b/x/auth/signing/verify_test.go index 8165f2536e..8606bcbfc2 100644 --- a/x/auth/signing/verify_test.go +++ b/x/auth/signing/verify_test.go @@ -48,8 +48,8 @@ func TestVerifySignature(t *testing.T) { sbh := uint64(1) fee := legacytx.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) signerData := signing.SignerData{ - ChainID: chainId, - Sequence: acc.GetSequence(), + ChainID: chainId, + Sequence: acc.GetSequence(), } signBytes := legacytx.StdSignBytes(signerData.ChainID, sbh, signerData.Sequence, 10, fee, msgs, memo) signature, err := priv.Sign(signBytes) diff --git a/x/auth/simulation/decoder_test.go b/x/auth/simulation/decoder_test.go index 7da1274869..a8cf11509d 100644 --- a/x/auth/simulation/decoder_test.go +++ b/x/auth/simulation/decoder_test.go @@ -16,7 +16,7 @@ import ( var ( delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) + delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) ) func TestDecodeStore(t *testing.T) { diff --git a/x/auth/testutil/suite.go b/x/auth/testutil/suite.go index 297286ed32..26f17bc89d 100644 --- a/x/auth/testutil/suite.go +++ b/x/auth/testutil/suite.go @@ -87,7 +87,7 @@ func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { // set test msg msg := testdata.NewTestMsg(addr) - msigAddr := sdk.AccAddress(multisigPk.Address()) + msigAddr := sdk.BytesToAccAddress(multisigPk.Address()) msg2 := testdata.NewTestMsg(msigAddr) err := txBuilder.SetMsgs(msg, msg2) s.Require().NoError(err) diff --git a/x/auth/tx/builder.go b/x/auth/tx/builder.go index a4d2f0046b..672d92c46b 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -131,11 +131,7 @@ func (w *wrapper) GetFee() sdk.Coins { func (w *wrapper) FeePayer() sdk.AccAddress { feePayer := w.tx.AuthInfo.Fee.Payer if feePayer != "" { - payerAddr, err := sdk.AccAddressFromBech32(feePayer) - if err != nil { - panic(err) - } - return payerAddr + return sdk.AccAddress(feePayer) } // use first signer as default if no payer specified return w.GetSigners()[0] @@ -144,13 +140,9 @@ func (w *wrapper) FeePayer() sdk.AccAddress { func (w *wrapper) FeeGranter() sdk.AccAddress { feePayer := w.tx.AuthInfo.Fee.Granter if feePayer != "" { - granterAddr, err := sdk.AccAddressFromBech32(feePayer) - if err != nil { - panic(err) - } - return granterAddr + return sdk.AccAddress(feePayer) } - return nil + return "" } func (w *wrapper) GetSigBlockHeight() uint64 { diff --git a/x/auth/tx/direct_test.go b/x/auth/tx/direct_test.go index ed951f9837..3d1a6017e8 100644 --- a/x/auth/tx/direct_test.go +++ b/x/auth/tx/direct_test.go @@ -69,7 +69,7 @@ func TestDirectModeHandler(t *testing.T) { require.Len(t, modeHandler.Modes(), 1) signingData := signing.SignerData{ - ChainID: "test-chain", + ChainID: "test-chain", } signBytes, err := modeHandler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_DIRECT, signingData, txBuilder.GetTx()) diff --git a/x/auth/tx/legacy_amino_json_test.go b/x/auth/tx/legacy_amino_json_test.go index 158ded4599..24a8330977 100644 --- a/x/auth/tx/legacy_amino_json_test.go +++ b/x/auth/tx/legacy_amino_json_test.go @@ -46,8 +46,8 @@ func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) { handler := signModeLegacyAminoJSONHandler{} signingData := signing.SignerData{ - ChainID: chainId, - Sequence: seqNum, + ChainID: chainId, + Sequence: seqNum, } signBz, err := handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signingData, tx) require.NoError(t, err) diff --git a/x/auth/types/account.go b/x/auth/types/account.go index 72f0c2285b..2b0819824e 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -1,7 +1,6 @@ package types import ( - "bytes" "encoding/json" "errors" "fmt" @@ -55,8 +54,7 @@ func NewBaseAccountWithAddress(addr sdk.AccAddress) *BaseAccount { // GetAddress - Implements sdk.AccountI. func (acc BaseAccount) GetAddress() sdk.AccAddress { - addr, _ := sdk.AccAddressFromBech32(acc.Address) - return addr + return sdk.AccAddress(acc.Address) } // SetAddress - Implements sdk.AccountI. @@ -111,12 +109,7 @@ func (acc BaseAccount) Validate() error { return nil } - accAddr, err := sdk.AccAddressFromBech32(acc.Address) - if err != nil { - return err - } - - if !bytes.Equal(acc.GetPubKey().Address().Bytes(), accAddr.Bytes()) { + if !sdk.AccAddress(acc.Address).Equals(sdk.BytesToAccAddress(acc.GetPubKey().Address())) { return errors.New("account address and pubkey address do not match") } @@ -148,7 +141,7 @@ func (acc BaseAccount) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { // NewModuleAddress creates an AccAddress from the hash of the module's name func NewModuleAddress(name string) sdk.AccAddress { - return sdk.AccAddress(crypto.AddressHash([]byte(name))) + return sdk.BytesToAccAddress(crypto.AddressHash([]byte(name))) } // NewEmptyModuleAccount creates a empty ModuleAccount from a string @@ -216,7 +209,7 @@ func (ma ModuleAccount) Validate() error { return errors.New("module account name cannot be blank") } - if ma.Address != sdk.AccAddress(crypto.AddressHash([]byte(ma.Name))).String() { + if ma.Address != sdk.BytesToAccAddress(crypto.AddressHash([]byte(ma.Name))).String() { return fmt.Errorf("address %s cannot be derived from the module name '%s'", ma.Address, ma.Name) } @@ -238,13 +231,13 @@ func (ma ModuleAccount) String() string { // MarshalYAML returns the YAML representation of a ModuleAccount. func (ma ModuleAccount) MarshalYAML() (interface{}, error) { - accAddr, err := sdk.AccAddressFromBech32(ma.Address) + err := sdk.ValidateAccAddress(ma.Address) if err != nil { return nil, err } bs, err := yaml.Marshal(moduleAccountPretty{ - Address: accAddr, + Address: sdk.AccAddress(ma.Address), PubKey: "", Sequence: ma.Sequence, Name: ma.Name, @@ -260,13 +253,13 @@ func (ma ModuleAccount) MarshalYAML() (interface{}, error) { // MarshalJSON returns the JSON representation of a ModuleAccount. func (ma ModuleAccount) MarshalJSON() ([]byte, error) { - accAddr, err := sdk.AccAddressFromBech32(ma.Address) + err := sdk.ValidateAccAddress(ma.Address) if err != nil { return nil, err } return json.Marshal(moduleAccountPretty{ - Address: accAddr, + Address: sdk.AccAddress(ma.Address), PubKey: "", Sequence: ma.Sequence, Name: ma.Name, diff --git a/x/auth/types/account_test.go b/x/auth/types/account_test.go index 9829e88f87..4adae0e8e9 100644 --- a/x/auth/types/account_test.go +++ b/x/auth/types/account_test.go @@ -83,7 +83,7 @@ func TestBaseAccountMarshal(t *testing.T) { func TestGenesisAccountValidate(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) baseAcc := types.NewBaseAccount(addr, pubkey, 0) tests := []struct { @@ -146,7 +146,7 @@ func TestHasPermissions(t *testing.T) { } func TestValidate(t *testing.T) { - addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) baseAcc := types.NewBaseAccount(addr, nil, 0) tests := []struct { name string @@ -180,7 +180,7 @@ func TestValidate(t *testing.T) { func TestModuleAccountJSON(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) baseAcc := types.NewBaseAccount(addr, nil, 50) acc := types.NewModuleAccount(baseAcc, "test", "burner") @@ -198,7 +198,7 @@ func TestModuleAccountJSON(t *testing.T) { func TestGenesisAccountsContains(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) acc := types.NewBaseAccount(addr, secp256k1.GenPrivKey().PubKey(), 0) genAccounts := types.GenesisAccounts{} diff --git a/x/auth/types/genesis_test.go b/x/auth/types/genesis_test.go index 233334c20a..08de21f871 100644 --- a/x/auth/types/genesis_test.go +++ b/x/auth/types/genesis_test.go @@ -14,10 +14,10 @@ import ( ) func TestSanitize(t *testing.T) { - addr1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + addr1 := sdk.BytesToAccAddress(ed25519.GenPrivKey().PubKey().Address()) authAcc1 := types.NewBaseAccountWithAddress(addr1) - addr2 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + addr2 := sdk.BytesToAccAddress(ed25519.GenPrivKey().PubKey().Address()) authAcc2 := types.NewBaseAccountWithAddress(addr2) genAccs := types.GenesisAccounts{authAcc1, authAcc2} @@ -30,8 +30,8 @@ func TestSanitize(t *testing.T) { var ( pk1 = ed25519.GenPrivKey().PubKey() pk2 = ed25519.GenPrivKey().PubKey() - addr1 = sdk.ValAddress(pk1.Address()) - addr2 = sdk.ValAddress(pk2.Address()) + addr1 = sdk.BytesToValAddress(pk1.Address()) + addr2 = sdk.BytesToValAddress(pk2.Address()) ) // require duplicate accounts fails validation diff --git a/x/auth/types/msgs.go b/x/auth/types/msgs.go index 28e14bc844..b9efb42d51 100644 --- a/x/auth/types/msgs.go +++ b/x/auth/types/msgs.go @@ -30,7 +30,7 @@ func (msg MsgEmpty) Route() string { return ModuleName } func (msg MsgEmpty) Type() string { return TypeMsgEmpty } func (msg MsgEmpty) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.FromAddress) + err := sdk.ValidateAccAddress(msg.FromAddress) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) } @@ -44,9 +44,9 @@ func (msg MsgEmpty) GetSignBytes() []byte { // GetSigners Implements Msg. func (msg MsgEmpty) GetSigners() []sdk.AccAddress { - from, err := sdk.AccAddressFromBech32(msg.FromAddress) + err := sdk.ValidateAccAddress(msg.FromAddress) if err != nil { panic(err) } - return []sdk.AccAddress{from} + return []sdk.AccAddress{sdk.AccAddress(msg.FromAddress)} } diff --git a/x/auth/types/msgs_test.go b/x/auth/types/msgs_test.go index df8282f5d8..ff576ecb08 100644 --- a/x/auth/types/msgs_test.go +++ b/x/auth/types/msgs_test.go @@ -1,6 +1,7 @@ package types import ( + "encoding/hex" "fmt" "testing" @@ -20,9 +21,9 @@ func TestMsgSendRoute(t *testing.T) { } func TestMsgSendValidation(t *testing.T) { - addr1 := sdk.AccAddress("from________________") - addrEmpty := sdk.AccAddress("") - addrTooLong := sdk.AccAddress("Accidentally used 33 bytes pubkey") + addr1 := sdk.BytesToAccAddress([]byte("from________________")) + addrEmpty := sdk.BytesToAccAddress([]byte("")) + addrTooLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) cases := []struct { expectedErr string // empty means no error expected @@ -44,17 +45,18 @@ func TestMsgSendValidation(t *testing.T) { } func TestMsgSendGetSignBytes(t *testing.T) { - res := NewMsgEmpty(sdk.AccAddress("input")).GetSignBytes() + res := NewMsgEmpty(sdk.BytesToAccAddress([]byte("input"))).GetSignBytes() expected := `{"type":"lfb-sdk/MsgEmpty","value":{"from_address":"link1d9h8qat5fnwd3e"}}` require.Equal(t, expected, string(res)) } func TestMsgSendGetSigners(t *testing.T) { - res := NewMsgEmpty(sdk.AccAddress("input111111111111111")).GetSigners() - require.Equal(t, fmt.Sprintf("%v", res), "[696E707574313131313131313131313131313131]") + res := NewMsgEmpty(sdk.BytesToAccAddress([]byte("input111111111111111"))).GetSigners() + bytes, _ := sdk.AccAddressToBytes(res[0].String()) + require.Equal(t, fmt.Sprintf("%v", hex.EncodeToString(bytes)), "696e707574313131313131313131313131313131") require.Panics(t, func() { - NewMsgEmpty(sdk.AccAddress("input")).GetSigners() + NewMsgEmpty(sdk.BytesToAccAddress([]byte("input"))).GetSigners() }) } diff --git a/x/auth/vesting/client/cli/cli_test.go b/x/auth/vesting/client/cli/cli_test.go index 77b189ebcd..bde74c713e 100644 --- a/x/auth/vesting/client/cli/cli_test.go +++ b/x/auth/vesting/client/cli/cli_test.go @@ -52,7 +52,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }{ "create a continuous vesting account": { args: []string{ - sdk.AccAddress("addr2_______________").String(), + sdk.BytesToAccAddress([]byte("addr2_______________")).String(), sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -66,7 +66,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "create a delayed vesting account": { args: []string{ - sdk.AccAddress("addr3_______________").String(), + sdk.BytesToAccAddress([]byte("addr3_______________")).String(), sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -81,7 +81,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "invalid address": { args: []string{ - sdk.AccAddress("addr4").String(), + sdk.BytesToAccAddress([]byte("addr4")).String(), sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -92,7 +92,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "invalid coins": { args: []string{ - sdk.AccAddress("addr4_______________").String(), + sdk.BytesToAccAddress([]byte("addr4_______________")).String(), "fooo", "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -103,7 +103,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "invalid end time": { args: []string{ - sdk.AccAddress("addr4_______________").String(), + sdk.BytesToAccAddress([]byte("addr4_______________")).String(), sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), "-4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), diff --git a/x/auth/vesting/client/cli/tx.go b/x/auth/vesting/client/cli/tx.go index e2ab48b13d..4db25eaaa8 100644 --- a/x/auth/vesting/client/cli/tx.go +++ b/x/auth/vesting/client/cli/tx.go @@ -51,10 +51,7 @@ timestamp.`, if err != nil { return err } - toAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } + toAddr := sdk.AccAddress(args[0]) amount, err := sdk.ParseCoinsNormalized(args[1]) if err != nil { diff --git a/x/auth/vesting/handler_test.go b/x/auth/vesting/handler_test.go index 26ddc44dd5..40567f127e 100644 --- a/x/auth/vesting/handler_test.go +++ b/x/auth/vesting/handler_test.go @@ -31,9 +31,9 @@ func (suite *HandlerTestSuite) TestMsgCreateVestingAccount() { ctx := suite.app.BaseApp.NewContext(false, ostproto.Header{Height: suite.app.LastBlockHeight() + 1}) balances := sdk.NewCoins(sdk.NewInt64Coin("test", 1000)) - addr1 := sdk.AccAddress([]byte("addr1_______________")) - addr2 := sdk.AccAddress([]byte("addr2_______________")) - addr3 := sdk.AccAddress([]byte("addr3_______________")) + addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) + addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) + addr3 := sdk.BytesToAccAddress([]byte("addr3_______________")) acc1 := suite.app.AccountKeeper.NewAccountWithAddress(ctx, addr1) suite.app.AccountKeeper.SetAccount(ctx, acc1) @@ -72,9 +72,9 @@ func (suite *HandlerTestSuite) TestMsgCreateVestingAccount() { suite.Require().NoError(err) suite.Require().NotNil(res) - toAddr, err := sdk.AccAddressFromBech32(tc.msg.ToAddress) + err := sdk.ValidateAccAddress(tc.msg.ToAddress) suite.Require().NoError(err) - accI := suite.app.AccountKeeper.GetAccount(ctx, toAddr) + accI := suite.app.AccountKeeper.GetAccount(ctx, sdk.AccAddress(tc.msg.ToAddress)) suite.Require().NotNil(accI) if tc.msg.Delayed { diff --git a/x/auth/vesting/msg_server.go b/x/auth/vesting/msg_server.go index 01a4b47ae2..5df359b3b1 100644 --- a/x/auth/vesting/msg_server.go +++ b/x/auth/vesting/msg_server.go @@ -36,14 +36,8 @@ func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCre return nil, err } - from, err := sdk.AccAddressFromBech32(msg.FromAddress) - if err != nil { - return nil, err - } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) - if err != nil { - return nil, err - } + from := sdk.AccAddress(msg.FromAddress) + to := sdk.AccAddress(msg.ToAddress) if bk.BlockedAddr(to) { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress) @@ -84,7 +78,7 @@ func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCre } }() - err = bk.SendCoins(ctx, from, to, msg.Amount) + err := bk.SendCoins(ctx, from, to, msg.Amount) if err != nil { return nil, err } diff --git a/x/auth/vesting/types/genesis_test.go b/x/auth/vesting/types/genesis_test.go index 294face436..b3f13cd433 100644 --- a/x/auth/vesting/types/genesis_test.go +++ b/x/auth/vesting/types/genesis_test.go @@ -13,8 +13,8 @@ import ( var ( pk1 = ed25519.GenPrivKey().PubKey() pk2 = ed25519.GenPrivKey().PubKey() - addr1 = sdk.ValAddress(pk1.Address()) - addr2 = sdk.ValAddress(pk2.Address()) + addr1 = sdk.BytesToValAddress(pk1.Address()) + addr2 = sdk.BytesToValAddress(pk2.Address()) ) // require invalid vesting account fails validation @@ -26,7 +26,7 @@ func TestValidateGenesisInvalidAccounts(t *testing.T) { // invalid delegated vesting baseVestingAcc.DelegatedVesting = acc1Balance.Add(acc1Balance...) - acc2 := authtypes.NewBaseAccountWithAddress(sdk.AccAddress(addr2)) + acc2 := authtypes.NewBaseAccountWithAddress(sdk.BytesToAccAddress(pk2.Address())) // acc2Balance := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 150)) genAccs := make([]authtypes.GenesisAccount, 2) diff --git a/x/auth/vesting/types/msgs.go b/x/auth/vesting/types/msgs.go index ef3c8ff6d6..51244eb282 100644 --- a/x/auth/vesting/types/msgs.go +++ b/x/auth/vesting/types/msgs.go @@ -30,11 +30,11 @@ func (msg MsgCreateVestingAccount) Type() string { return TypeMsgCreateVestingAc // ValidateBasic Implements Msg. func (msg MsgCreateVestingAccount) ValidateBasic() error { - from, err := sdk.AccAddressFromBech32(msg.FromAddress) + from, err := sdk.AccAddressToBytes(msg.FromAddress) if err != nil { return err } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) + to, err := sdk.AccAddressToBytes(msg.ToAddress) if err != nil { return err } @@ -69,9 +69,9 @@ func (msg MsgCreateVestingAccount) GetSignBytes() []byte { // GetSigners returns the expected signers for a MsgCreateVestingAccount. func (msg MsgCreateVestingAccount) GetSigners() []sdk.AccAddress { - from, err := sdk.AccAddressFromBech32(msg.FromAddress) + err := sdk.ValidateAccAddress(msg.FromAddress) if err != nil { panic(err) } - return []sdk.AccAddress{from} + return []sdk.AccAddress{sdk.AccAddress(msg.FromAddress)} } diff --git a/x/auth/vesting/types/test_common.go b/x/auth/vesting/types/test_common.go index 0ccf0b5c2d..dec1bab86f 100644 --- a/x/auth/vesting/types/test_common.go +++ b/x/auth/vesting/types/test_common.go @@ -24,6 +24,6 @@ func NewTestCoins() sdk.Coins { func KeyTestPubAddr() (cryptotypes.PrivKey, cryptotypes.PubKey, sdk.AccAddress) { key := secp256k1.GenPrivKey() pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) + addr := sdk.BytesToAccAddress(pub.Address()) return key, pub, addr } diff --git a/x/auth/vesting/types/vesting_account.go b/x/auth/vesting/types/vesting_account.go index 55f40c3b96..ec590d29d9 100644 --- a/x/auth/vesting/types/vesting_account.go +++ b/x/auth/vesting/types/vesting_account.go @@ -182,13 +182,8 @@ func (bva BaseVestingAccount) String() string { // MarshalYAML returns the YAML representation of a BaseVestingAccount. func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) { - accAddr, err := sdk.AccAddressFromBech32(bva.Address) - if err != nil { - return nil, err - } - alias := vestingAccountYAML{ - Address: accAddr, + Address: sdk.AccAddress(bva.Address), Sequence: bva.Sequence, OriginalVesting: bva.OriginalVesting, DelegatedFree: bva.DelegatedFree, @@ -309,13 +304,8 @@ func (cva ContinuousVestingAccount) String() string { // MarshalYAML returns the YAML representation of a ContinuousVestingAccount. func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) { - accAddr, err := sdk.AccAddressFromBech32(cva.Address) - if err != nil { - return nil, err - } - alias := vestingAccountYAML{ - Address: accAddr, + Address: sdk.AccAddress(cva.Address), Sequence: cva.Sequence, OriginalVesting: cva.OriginalVesting, DelegatedFree: cva.DelegatedFree, @@ -466,13 +456,8 @@ func (pva PeriodicVestingAccount) String() string { // MarshalYAML returns the YAML representation of a PeriodicVestingAccount. func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) { - accAddr, err := sdk.AccAddressFromBech32(pva.Address) - if err != nil { - return nil, err - } - alias := vestingAccountYAML{ - Address: accAddr, + Address: sdk.AccAddress(pva.Address), Sequence: pva.Sequence, OriginalVesting: pva.OriginalVesting, DelegatedFree: pva.DelegatedFree, diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index f7da227131..7aa0d10eea 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -580,7 +580,7 @@ func TestTrackUndelegationPeriodicVestingAcc(t *testing.T) { func TestGenesisAccountValidate(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) baseAcc := authtypes.NewBaseAccount(addr, pubkey, 0) initialVesting := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)) baseVestingWithCoins := types.NewBaseVestingAccount(baseAcc, initialVesting, 100) @@ -646,7 +646,7 @@ func TestGenesisAccountValidate(t *testing.T) { func TestContinuousVestingAccountMarshal(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5)) baseAcc := authtypes.NewBaseAccount(addr, pubkey, 50) @@ -668,7 +668,7 @@ func TestContinuousVestingAccountMarshal(t *testing.T) { func TestPeriodicVestingAccountMarshal(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5)) baseAcc := authtypes.NewBaseAccount(addr, pubkey, 50) @@ -689,7 +689,7 @@ func TestPeriodicVestingAccountMarshal(t *testing.T) { func TestDelayedVestingAccountMarshal(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.AccAddress(pubkey.Address()) + addr := sdk.BytesToAccAddress(pubkey.Address()) coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5)) baseAcc := authtypes.NewBaseAccount(addr, pubkey, 50) diff --git a/x/bank/app_test.go b/x/bank/app_test.go index f0568e7fc9..7e275ecb4b 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -34,12 +34,12 @@ type ( var ( priv1 = secp256k1.GenPrivKey() - addr1 = sdk.AccAddress(priv1.PubKey().Address()) + addr1 = sdk.BytesToAccAddress(priv1.PubKey().Address()) priv2 = secp256k1.GenPrivKey() - addr2 = sdk.AccAddress(priv2.PubKey().Address()) - addr3 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr2 = sdk.BytesToAccAddress(priv2.PubKey().Address()) + addr3 = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) priv4 = secp256k1.GenPrivKey() - addr4 = sdk.AccAddress(priv4.PubKey().Address()) + addr4 = sdk.BytesToAccAddress(priv4.PubKey().Address()) coins = sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} halfCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 5)} diff --git a/x/bank/client/cli/query.go b/x/bank/client/cli/query.go index 31458c9865..f72c811d0f 100644 --- a/x/bank/client/cli/query.go +++ b/x/bank/client/cli/query.go @@ -65,10 +65,7 @@ Example: queryClient := types.NewQueryClient(clientCtx) - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } + addr := sdk.AccAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index 7f8db26a5e..33b7e87de5 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -39,10 +39,7 @@ ignored as it is implied from [from_key_or_address].`, if err != nil { return err } - toAddr, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } + toAddr := sdk.AccAddress(args[1]) coins, err := sdk.ParseCoinsNormalized(args[2]) if err != nil { diff --git a/x/bank/client/rest/query.go b/x/bank/client/rest/query.go index 31b4e17b4a..7361d45c33 100644 --- a/x/bank/client/rest/query.go +++ b/x/bank/client/rest/query.go @@ -21,10 +21,7 @@ func QueryBalancesRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { vars := mux.Vars(r) bech32addr := vars["address"] - addr, err := sdk.AccAddressFromBech32(bech32addr) - if rest.CheckInternalServerError(w, err) { - return - } + addr := sdk.AccAddress(bech32addr) ctx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { diff --git a/x/bank/client/rest/tx.go b/x/bank/client/rest/tx.go index d334edc0f4..995026067f 100644 --- a/x/bank/client/rest/tx.go +++ b/x/bank/client/rest/tx.go @@ -25,10 +25,7 @@ func NewSendRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { vars := mux.Vars(r) bech32Addr := vars["address"] - toAddr, err := sdk.AccAddressFromBech32(bech32Addr) - if rest.CheckBadRequestError(w, err) { - return - } + toAddr := sdk.AccAddress(bech32Addr) var req SendReq if !rest.ReadRESTReq(w, r, clientCtx.LegacyAmino, &req) { @@ -40,10 +37,7 @@ func NewSendRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if rest.CheckBadRequestError(w, err) { - return - } + fromAddr := sdk.AccAddress(req.BaseReq.From) msg := types.NewMsgSend(fromAddr, toAddr, req.Amount) tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) diff --git a/x/bank/client/testutil/cli_helpers.go b/x/bank/client/testutil/cli_helpers.go index 4fba03ba34..23c9eedbf6 100644 --- a/x/bank/client/testutil/cli_helpers.go +++ b/x/bank/client/testutil/cli_helpers.go @@ -79,7 +79,7 @@ ignored as it is implied from [from_key_or_address].`, if err != nil { return err } - toAddr, err := sdk.AccAddressFromBech32(args[1]) + err = sdk.ValidateAccAddress(args[1]) if err != nil { return err } @@ -89,7 +89,7 @@ ignored as it is implied from [from_key_or_address].`, return err } - msg := types.NewMsgSend(clientCtx.GetFromAddress(), toAddr, coins) + msg := types.NewMsgSend(clientCtx.GetFromAddress(), sdk.AccAddress(args[1]), coins) svcMsgClientConn := &serviceMsgClientConn{} bankMsgClient := types.NewMsgClient(svcMsgClientConn) _, err = bankMsgClient.Send(context.Background(), msg) diff --git a/x/bank/handler_test.go b/x/bank/handler_test.go index e28883c607..19d58d7e32 100644 --- a/x/bank/handler_test.go +++ b/x/bank/handler_test.go @@ -33,7 +33,7 @@ func TestInvalidMsg(t *testing.T) { // A module account cannot be the recipient of bank sends unless it has been marked as such func TestSendToModuleAccount(t *testing.T) { priv1 := secp256k1.GenPrivKey() - addr1 := sdk.AccAddress(priv1.PubKey().Address()) + addr1 := sdk.BytesToAccAddress(priv1.PubKey().Address()) moduleAccAddr := authtypes.NewModuleAddress(stakingtypes.BondedPoolName) coins := sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} diff --git a/x/bank/keeper/genesis.go b/x/bank/keeper/genesis.go index f2ef5e1a5d..7285f25d37 100644 --- a/x/bank/keeper/genesis.go +++ b/x/bank/keeper/genesis.go @@ -15,12 +15,7 @@ func (k BaseKeeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) { genState.Balances = types.SanitizeGenesisBalances(genState.Balances) for _, balance := range genState.Balances { - addr, err := sdk.AccAddressFromBech32(balance.Address) - if err != nil { - panic(err) - } - - if err := k.SetBalances(ctx, addr, balance.Coins); err != nil { + if err := k.SetBalances(ctx, sdk.AccAddress(balance.Address), balance.Coins); err != nil { panic(fmt.Errorf("error on setting balances %w", err)) } diff --git a/x/bank/keeper/genesis_test.go b/x/bank/keeper/genesis_test.go index c1b537a582..fecf5c999f 100644 --- a/x/bank/keeper/genesis_test.go +++ b/x/bank/keeper/genesis_test.go @@ -12,11 +12,11 @@ func (suite *IntegrationTestSuite) TestExportGenesis() { expectedBalances := suite.getTestBalances() for i := range []int{1, 2} { app.BankKeeper.SetDenomMetaData(ctx, expectedMetadata[i]) - accAddr, err1 := sdk.AccAddressFromBech32(expectedBalances[i].Address) + err1 := sdk.ValidateAccAddress(expectedBalances[i].Address) if err1 != nil { panic(err1) } - err := app.BankKeeper.SetBalances(ctx, accAddr, expectedBalances[i].Coins) + err := app.BankKeeper.SetBalances(ctx, sdk.AccAddress(expectedBalances[i].Address), expectedBalances[i].Coins) suite.Require().NoError(err) } @@ -34,11 +34,11 @@ func (suite *IntegrationTestSuite) TestExportGenesis() { } func (suite *IntegrationTestSuite) getTestBalances() []types.Balance { - addr2, _ := sdk.AccAddressFromBech32("link15klks9yty6rwvnqk47q4cg92r38qj4gsvxdfj8") - addr1, _ := sdk.AccAddressFromBech32("link14uxsrqf2cakphyw9ywwy9a9fv7yjspku4lkrny") + addr2 := sdk.AccAddress("link15klks9yty6rwvnqk47q4cg92r38qj4gsvxdfj8") + addr1 := sdk.AccAddress("link14uxsrqf2cakphyw9ywwy9a9fv7yjspku4lkrny") return []types.Balance{ - {Address: addr2.String(), Coins: sdk.Coins{sdk.NewInt64Coin("testcoin1", 32), sdk.NewInt64Coin("testcoin2", 34)}}, {Address: addr1.String(), Coins: sdk.Coins{sdk.NewInt64Coin("testcoin3", 10)}}, + {Address: addr2.String(), Coins: sdk.Coins{sdk.NewInt64Coin("testcoin1", 32), sdk.NewInt64Coin("testcoin2", 34)}}, } } diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index 6dc795b34b..270cd519a6 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -29,12 +29,7 @@ func (k BaseKeeper) Balance(ctx context.Context, req *types.QueryBalanceRequest) } sdkCtx := sdk.UnwrapSDKContext(ctx) - address, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error()) - } - - balance := k.GetBalance(sdkCtx, address, req.Denom) + balance := k.GetBalance(sdkCtx, sdk.AccAddress(req.Address), req.Denom) return &types.QueryBalanceResponse{Balance: &balance}, nil } @@ -49,17 +44,12 @@ func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalances return nil, status.Error(codes.InvalidArgument, "address cannot be empty") } - addr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error()) - } - sdkCtx := sdk.UnwrapSDKContext(ctx) balances := sdk.NewCoins() store := sdkCtx.KVStore(k.storeKey) balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr.Bytes()) + accountStore := prefix.NewStore(balancesStore, sdk.AccAddress(req.Address).Bytes()) pageRes, err := query.Paginate(accountStore, req.Pagination, func(_, value []byte) error { var result sdk.Coin diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 617a7c14f4..87aa7c10e7 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -242,7 +242,7 @@ func (k BaseKeeper) SendCoinsFromModuleToAccount( ) error { senderAddr := k.ak.GetModuleAddress(senderModule) - if senderAddr == nil { + if senderAddr.Empty() { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) } @@ -256,7 +256,7 @@ func (k BaseKeeper) SendCoinsFromModuleToModule( ) error { senderAddr := k.ak.GetModuleAddress(senderModule) - if senderAddr == nil { + if senderAddr.Empty() { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) } diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index b73480dc4c..f8061f04be 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -297,7 +297,7 @@ func (suite *IntegrationTestSuite) TestInputOutputNewAccount() { app, ctx := suite.app, suite.ctx balances := sdk.NewCoins(newFooCoin(100), newBarCoin(50)) - addr1 := sdk.AccAddress([]byte("addr1_______________")) + addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) suite.Require().NoError(app.BankKeeper.SetBalances(ctx, addr1, balances)) @@ -305,7 +305,7 @@ func (suite *IntegrationTestSuite) TestInputOutputNewAccount() { acc1Balances := app.BankKeeper.GetAllBalances(ctx, addr1) suite.Require().Equal(balances, acc1Balances) - addr2 := sdk.AccAddress([]byte("addr2_______________")) + addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) suite.Require().Nil(app.AccountKeeper.GetAccount(ctx, addr2)) suite.Require().Empty(app.BankKeeper.GetAllBalances(ctx, addr2)) @@ -329,15 +329,15 @@ func (suite *IntegrationTestSuite) TestInputOutputCoins() { app, ctx := suite.app, suite.ctx balances := sdk.NewCoins(newFooCoin(90), newBarCoin(30)) - addr1 := sdk.AccAddress([]byte("addr1_______________")) + addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) - addr2 := sdk.AccAddress([]byte("addr2_______________")) + addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) app.AccountKeeper.SetAccount(ctx, acc2) - addr3 := sdk.AccAddress([]byte("addr3_______________")) + addr3 := sdk.BytesToAccAddress([]byte("addr3_______________")) acc3 := app.AccountKeeper.NewAccountWithAddress(ctx, addr3) app.AccountKeeper.SetAccount(ctx, acc3) @@ -576,10 +576,10 @@ func (suite *IntegrationTestSuite) TestMsgMultiSendEvents() { app.BankKeeper.SetParams(ctx, types.DefaultParams()) - addr := sdk.AccAddress([]byte("addr1_______________")) - addr2 := sdk.AccAddress([]byte("addr2_______________")) - addr3 := sdk.AccAddress([]byte("addr3_______________")) - addr4 := sdk.AccAddress([]byte("addr4_______________")) + addr := sdk.BytesToAccAddress([]byte("addr1_______________")) + addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) + addr3 := sdk.BytesToAccAddress([]byte("addr3_______________")) + addr4 := sdk.BytesToAccAddress([]byte("addr4_______________")) acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) diff --git a/x/bank/keeper/msg_server.go b/x/bank/keeper/msg_server.go index 66132e4325..3501bdc8be 100644 --- a/x/bank/keeper/msg_server.go +++ b/x/bank/keeper/msg_server.go @@ -26,23 +26,17 @@ var _ types.MsgServer = msgServer{} func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSendResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) + // NOTICE: We omit the bech32 validation of `from`, `to` for performance in this function. + if err := k.SendEnabledCoins(ctx, msg.Amount...); err != nil { return nil, err } - from, err := sdk.AccAddressFromBech32(msg.FromAddress) - if err != nil { - return nil, err - } - to, err := sdk.AccAddressFromBech32(msg.ToAddress) - if err != nil { - return nil, err - } - if k.BlockedAddr(to) { + if k.BlockedAddr(sdk.AccAddress(msg.ToAddress)) { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress) } - err = k.SendCoins(ctx, from, to, msg.Amount) + err := k.SendCoins(ctx, sdk.AccAddress(msg.FromAddress), sdk.AccAddress(msg.ToAddress), msg.Amount) if err != nil { return nil, err } @@ -80,11 +74,7 @@ func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*t } for _, out := range msg.Outputs { - accAddr, err := sdk.AccAddressFromBech32(out.Address) - if err != nil { - panic(err) - } - if k.BlockedAddr(accAddr) { + if k.BlockedAddr(sdk.AccAddress(out.Address)) { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive transactions", out.Address) } } diff --git a/x/bank/keeper/querier.go b/x/bank/keeper/querier.go index afaa4ad7d0..7346eb5ade 100644 --- a/x/bank/keeper/querier.go +++ b/x/bank/keeper/querier.go @@ -39,12 +39,7 @@ func queryBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerie return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, err - } - - balance := k.GetBalance(ctx, address, params.Denom) + balance := k.GetBalance(ctx, sdk.AccAddress(params.Address), params.Denom) bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, balance) if err != nil { @@ -61,12 +56,7 @@ func queryAllBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - address, err := sdk.AccAddressFromBech32(params.Address) - if err != nil { - return nil, err - } - - balances := k.GetAllBalances(ctx, address) + balances := k.GetAllBalances(ctx, sdk.AccAddress(params.Address)) bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, balances) if err != nil { diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index be6eef6be1..fb1f3531fe 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -63,6 +63,10 @@ func NewBaseSendKeeper( } } +func AddressToPrefixKey(addr sdk.AccAddress) []byte { + return []byte(addr.String() + types.AddressDenomDelimiter) +} + // GetParams returns the total set of bank parameters. func (k BaseSendKeeper) GetParams(ctx sdk.Context) (params types.Params) { k.paramSpace.GetParamSet(ctx, ¶ms) @@ -85,12 +89,9 @@ func (k BaseSendKeeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, } for _, in := range inputs { - inAddress, err := sdk.AccAddressFromBech32(in.Address) - if err != nil { - return err - } + inAddress := sdk.AccAddress(in.Address) - err = k.SubtractCoins(ctx, inAddress, in.Coins) + err := k.SubtractCoins(ctx, inAddress, in.Coins) if err != nil { return err } @@ -104,11 +105,8 @@ func (k BaseSendKeeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, } for _, out := range outputs { - outAddress, err := sdk.AccAddressFromBech32(out.Address) - if err != nil { - return err - } - err = k.AddCoins(ctx, outAddress, out.Coins) + outAddress := sdk.AccAddress(out.Address) + err := k.AddCoins(ctx, outAddress, out.Coins) if err != nil { return err } @@ -235,7 +233,7 @@ func (k BaseSendKeeper) ClearBalances(ctx sdk.Context, addr sdk.AccAddress) { store := ctx.KVStore(k.storeKey) balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr.Bytes()) + accountStore := prefix.NewStore(balancesStore, AddressToPrefixKey(addr)) for _, key := range keys { accountStore.Delete(key) @@ -266,7 +264,7 @@ func (k BaseSendKeeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, balance store := ctx.KVStore(k.storeKey) balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr.Bytes()) + accountStore := prefix.NewStore(balancesStore, AddressToPrefixKey(addr)) bz := k.cdc.MustMarshalBinaryBare(&balance) accountStore.Set([]byte(balance.Denom), bz) diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index 695d0d9249..2fee87a1b8 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -99,7 +99,7 @@ func (k BaseViewKeeper) GetAccountsBalances(ctx sdk.Context) []types.Balance { func (k BaseViewKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { store := ctx.KVStore(k.storeKey) balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr.Bytes()) + accountStore := prefix.NewStore(balancesStore, AddressToPrefixKey(addr)) bz := accountStore.Get([]byte(denom)) if bz == nil { @@ -118,7 +118,7 @@ func (k BaseViewKeeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom s func (k BaseViewKeeper) IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) { store := ctx.KVStore(k.storeKey) balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, addr.Bytes()) + accountStore := prefix.NewStore(balancesStore, AddressToPrefixKey(addr)) iterator := accountStore.Iterator(nil, nil) defer iterator.Close() diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 3732f3fac3..39158fbfed 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -92,10 +92,7 @@ func sendMsgSend( err error ) - from, err := sdk.AccAddressFromBech32(msg.FromAddress) - if err != nil { - return err - } + from := sdk.AccAddress(msg.FromAddress) account := ak.GetAccount(ctx, from) spendable := bk.SpendableCoins(ctx, account.GetAddress()) @@ -233,10 +230,7 @@ func sendMsgMultiSend( sequenceNumbers := make([]uint64, len(msg.Inputs)) for i := 0; i < len(msg.Inputs); i++ { - addr, err := sdk.AccAddressFromBech32(msg.Inputs[i].Address) - if err != nil { - panic(err) - } + addr := sdk.AccAddress(msg.Inputs[i].Address) acc := ak.GetAccount(ctx, addr) sbh[i] = 0 sequenceNumbers[i] = acc.GetSequence() @@ -247,10 +241,7 @@ func sendMsgMultiSend( err error ) - addr, err := sdk.AccAddressFromBech32(msg.Inputs[0].Address) - if err != nil { - panic(err) - } + addr := sdk.AccAddress(msg.Inputs[0].Address) // feePayer is the first signer, i.e. first input address feePayer := ak.GetAccount(ctx, addr) diff --git a/x/bank/types/balance.go b/x/bank/types/balance.go index 96fcdf4189..bc54ead227 100644 --- a/x/bank/types/balance.go +++ b/x/bank/types/balance.go @@ -1,10 +1,10 @@ package types import ( - "bytes" "encoding/json" fmt "fmt" "sort" + "strings" "github.com/line/lfb-sdk/codec" sdk "github.com/line/lfb-sdk/types" @@ -15,12 +15,7 @@ var _ exported.GenesisBalance = (*Balance)(nil) // GetAddress returns the account address of the Balance object. func (b Balance) GetAddress() sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(b.Address) - if err != nil { - panic(fmt.Errorf("couldn't convert %q to account address: %v", b.Address, err)) - } - - return addr + return sdk.AccAddress(b.Address) } // GetCoins returns the account coins of the Balance object. @@ -30,7 +25,7 @@ func (b Balance) GetCoins() sdk.Coins { // Validate checks for address and coins correctness. func (b Balance) Validate() error { - _, err := sdk.AccAddressFromBech32(b.Address) + err := sdk.ValidateAccAddress(b.Address) if err != nil { return err } @@ -79,15 +74,14 @@ func SanitizeGenesisBalances(balances []Balance) []Balance { // We use a pointer here to avoid averse effects of value copying // wasting RAM all around. balance *Balance - accAddr []byte + accAddr sdk.AccAddress } adL := make([]*addrToBalance, 0, len(balances)) for _, balance := range balances { balance := balance - addr, _ := sdk.AccAddressFromBech32(balance.Address) adL = append(adL, &addrToBalance{ balance: &balance, - accAddr: []byte(addr), + accAddr: sdk.AccAddress(balance.Address), }) } @@ -95,7 +89,7 @@ func SanitizeGenesisBalances(balances []Balance) []Balance { // already accAddr bytes values which is a cheaper operation. sort.Slice(adL, func(i, j int) bool { ai, aj := adL[i], adL[j] - return bytes.Compare(ai.accAddr, aj.accAddr) < 0 + return strings.Compare(string(ai.accAddr), string(aj.accAddr)) < 0 }) // 3. To complete the sorting, we have to now just insert diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go index 8edf16c322..537863ab69 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -1,7 +1,7 @@ package types_test import ( - "bytes" + "strings" "testing" "github.com/stretchr/testify/require" @@ -87,10 +87,11 @@ func TestBalance_GetAddress(t *testing.T) { Address string wantPanic bool }{ - {"empty address", "", true}, - {"malformed address", "invalid", true}, + {"empty address", "", false}, + {"malformed address", "invalid", false}, {"valid address", "link1qz9c0r2jvpkccx67d5svg8kms6eu3k832hdc6p", false}, } + // Balance.GetAddress() does not validate the address. for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { @@ -98,7 +99,7 @@ func TestBalance_GetAddress(t *testing.T) { if tt.wantPanic { require.Panics(t, func() { b.GetAddress() }) } else { - require.False(t, b.GetAddress().Empty()) + require.True(t, b.GetAddress().Equals(sdk.AccAddress(tt.Address))) } }) } @@ -130,7 +131,7 @@ func TestSanitizeBalances(t *testing.T) { for j := i + 1; j < len(sorted); j++ { aj := sorted[j] - if got := bytes.Compare(ai.GetAddress(), aj.GetAddress()); got > 0 { + if got := strings.Compare(ai.GetAddress().String(), aj.GetAddress().String()); got > 0 { t.Errorf("Balance(%d) > Balance(%d)", i, j) } } @@ -141,7 +142,7 @@ func makeRandomAddressesAndPublicKeys(n int) (accL []sdk.AccAddress, pkL []*ed25 for i := 0; i < n; i++ { pk := ed25519.GenPrivKey().PubKey().(*ed25519.PubKey) pkL = append(pkL, pk) - accL = append(accL, sdk.AccAddress(pk.Address())) + accL = append(accL, sdk.BytesToAccAddress(pk.Address())) } return accL, pkL } diff --git a/x/bank/types/key.go b/x/bank/types/key.go index 20336b882d..0bc481c64d 100644 --- a/x/bank/types/key.go +++ b/x/bank/types/key.go @@ -2,6 +2,7 @@ package types import ( "fmt" + "strings" sdk "github.com/line/lfb-sdk/types" ) @@ -25,6 +26,9 @@ var ( BalancesPrefix = []byte("balances") SupplyKey = []byte{0x00} DenomMetadataPrefix = []byte{0x1} + + // Contract: Address must not contain this character + AddressDenomDelimiter = "," ) // DenomMetadataKey returns the denomination metadata key. @@ -37,10 +41,14 @@ func DenomMetadataKey(denom string) []byte { // store. The key must not contain the perfix BalancesPrefix as the prefix store // iterator discards the actual prefix. func AddressFromBalancesStore(key []byte) sdk.AccAddress { - addr := key[:sdk.AddrLen] - if len(addr) != sdk.AddrLen { - panic(fmt.Sprintf("unexpected account address key length; got: %d, expected: %d", len(addr), sdk.AddrLen)) + addr := string(key) + if !strings.Contains(addr, sdk.Bech32MainPrefix) { + panic(fmt.Sprintf("unexpected account address key; key does not start with (%s): %s", + sdk.Bech32MainPrefix, addr)) } - - return sdk.AccAddress(addr) + index := strings.Index(addr, AddressDenomDelimiter) + if index <= 0 { + panic(fmt.Sprintf("AddressBalance store key does not contain the delimiter(,): %s", addr)) + } + return sdk.AccAddress(addr[:index]) } diff --git a/x/bank/types/key_test.go b/x/bank/types/key_test.go index c545aeac70..534d11d1cf 100644 --- a/x/bank/types/key_test.go +++ b/x/bank/types/key_test.go @@ -3,6 +3,7 @@ package types_test import ( "testing" + "github.com/line/lfb-sdk/x/bank/keeper" "github.com/stretchr/testify/require" sdk "github.com/line/lfb-sdk/types" @@ -17,10 +18,11 @@ func cloneAppend(bz []byte, tail []byte) (res []byte) { } func TestAddressFromBalancesStore(t *testing.T) { - addr, err := sdk.AccAddressFromBech32("link19tzp7e489drh9qfs9m84k2qe5a5yyknzen48tz") + addr := sdk.AccAddress("link19tzp7e489drh9qfs9m84k2qe5a5yyknzen48tz") + err := sdk.ValidateAccAddress(addr.String()) require.NoError(t, err) - key := cloneAppend(addr.Bytes(), []byte("stake")) + key := cloneAppend(keeper.AddressToPrefixKey(addr), []byte("stake")) res := types.AddressFromBalancesStore(key) require.Equal(t, res, addr) } diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index d8a19c4dca..846c251a33 100644 --- a/x/bank/types/msgs.go +++ b/x/bank/types/msgs.go @@ -27,12 +27,12 @@ func (msg MsgSend) Type() string { return TypeMsgSend } // ValidateBasic Implements Msg. func (msg MsgSend) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.FromAddress) + err := sdk.ValidateAccAddress(msg.FromAddress) // TODO: Is this really required? if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) } - _, err = sdk.AccAddressFromBech32(msg.ToAddress) + err = sdk.ValidateAccAddress(msg.ToAddress) // TODO: Is this really required? if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid recipient address (%s)", err) } @@ -55,11 +55,7 @@ func (msg MsgSend) GetSignBytes() []byte { // GetSigners Implements Msg. func (msg MsgSend) GetSigners() []sdk.AccAddress { - from, err := sdk.AccAddressFromBech32(msg.FromAddress) - if err != nil { - panic(err) - } - return []sdk.AccAddress{from} + return []sdk.AccAddress{sdk.AccAddress(msg.FromAddress)} } var _ sdk.Msg = &MsgMultiSend{} @@ -99,8 +95,7 @@ func (msg MsgMultiSend) GetSignBytes() []byte { func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { addrs := make([]sdk.AccAddress, len(msg.Inputs)) for i, in := range msg.Inputs { - addr, _ := sdk.AccAddressFromBech32(in.Address) - addrs[i] = addr + addrs[i] = sdk.AccAddress(in.Address) } return addrs @@ -108,7 +103,7 @@ func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { // ValidateBasic - validate transaction input func (in Input) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(in.Address) + err := sdk.ValidateAccAddress(in.Address) if err != nil { return err } @@ -135,7 +130,7 @@ func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { // ValidateBasic - validate transaction output func (out Output) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(out.Address) + err := sdk.ValidateAccAddress(out.Address) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid output address (%s)", err) } diff --git a/x/bank/types/msgs_test.go b/x/bank/types/msgs_test.go index a8c1c17add..65069f11c4 100644 --- a/x/bank/types/msgs_test.go +++ b/x/bank/types/msgs_test.go @@ -10,8 +10,8 @@ import ( ) func TestMsgSendRoute(t *testing.T) { - addr1 := sdk.AccAddress([]byte("from")) - addr2 := sdk.AccAddress([]byte("to")) + addr1 := sdk.BytesToAccAddress([]byte("from")) + addr2 := sdk.BytesToAccAddress([]byte("to")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) var msg = NewMsgSend(addr1, addr2, coins) @@ -20,10 +20,10 @@ func TestMsgSendRoute(t *testing.T) { } func TestMsgSendValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("from________________")) - addr2 := sdk.AccAddress([]byte("to__________________")) - addrEmpty := sdk.AccAddress([]byte("")) - addrTooLong := sdk.AccAddress([]byte("Accidentally used 33 bytes pubkey")) + addr1 := sdk.BytesToAccAddress([]byte("from________________")) + addr2 := sdk.BytesToAccAddress([]byte("to__________________")) + addrEmpty := sdk.BytesToAccAddress([]byte("")) + addrTooLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) atom123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) atom0 := sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) @@ -55,8 +55,8 @@ func TestMsgSendValidation(t *testing.T) { } func TestMsgSendGetSignBytes(t *testing.T) { - addr1 := sdk.AccAddress([]byte("input")) - addr2 := sdk.AccAddress([]byte("output")) + addr1 := sdk.BytesToAccAddress([]byte("input")) + addr2 := sdk.BytesToAccAddress([]byte("output")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) var msg = NewMsgSend(addr1, addr2, coins) res := msg.GetSignBytes() @@ -66,7 +66,7 @@ func TestMsgSendGetSignBytes(t *testing.T) { } func TestMsgSendGetSigners(t *testing.T) { - var msg = NewMsgSend(sdk.AccAddress([]byte("input111111111111111")), sdk.AccAddress{}, sdk.NewCoins()) + var msg = NewMsgSend(sdk.AccAddress([]byte("input111111111111111")), "", sdk.NewCoins()) res := msg.GetSigners() // TODO: fix this ! require.Equal(t, fmt.Sprintf("%v", res), "[696E707574313131313131313131313131313131]") @@ -74,8 +74,8 @@ func TestMsgSendGetSigners(t *testing.T) { func TestMsgMultiSendRoute(t *testing.T) { // Construct a MsgSend - addr1 := sdk.AccAddress([]byte("input")) - addr2 := sdk.AccAddress([]byte("output")) + addr1 := sdk.BytesToAccAddress([]byte("input")) + addr2 := sdk.BytesToAccAddress([]byte("output")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) var msg = MsgMultiSend{ Inputs: []Input{NewInput(addr1, coins)}, @@ -88,10 +88,10 @@ func TestMsgMultiSendRoute(t *testing.T) { } func TestInputValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("_______alice________")) - addr2 := sdk.AccAddress([]byte("________bob_________")) - addrEmpty := sdk.AccAddress([]byte("")) - addrTooLong := sdk.AccAddress([]byte("Accidentally used 33 bytes pubkey")) + addr1 := sdk.BytesToAccAddress([]byte("_______alice________")) + addr2 := sdk.BytesToAccAddress([]byte("________bob_________")) + addrEmpty := sdk.BytesToAccAddress([]byte("")) + addrTooLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) someCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) multiCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 20)) @@ -129,10 +129,10 @@ func TestInputValidation(t *testing.T) { } func TestOutputValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("_______alice________")) - addr2 := sdk.AccAddress([]byte("________bob_________")) - addrEmpty := sdk.AccAddress([]byte("")) - addrTooLong := sdk.AccAddress([]byte("Accidentally used 33 bytes pubkey")) + addr1 := sdk.BytesToAccAddress([]byte("_______alice________")) + addr2 := sdk.BytesToAccAddress([]byte("________bob_________")) + addrEmpty := sdk.BytesToAccAddress([]byte("")) + addrTooLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) someCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) multiCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 20)) @@ -170,8 +170,8 @@ func TestOutputValidation(t *testing.T) { } func TestMsgMultiSendValidation(t *testing.T) { - addr1 := sdk.AccAddress([]byte("_______alice________")) - addr2 := sdk.AccAddress([]byte("________bob_________")) + addr1 := sdk.BytesToAccAddress([]byte("_______alice________")) + addr2 := sdk.BytesToAccAddress([]byte("________bob_________")) atom123 := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) atom124 := sdk.NewCoins(sdk.NewInt64Coin("atom", 124)) eth123 := sdk.NewCoins(sdk.NewInt64Coin("eth", 123)) @@ -224,8 +224,8 @@ func TestMsgMultiSendValidation(t *testing.T) { } func TestMsgMultiSendGetSignBytes(t *testing.T) { - addr1 := sdk.AccAddress([]byte("input")) - addr2 := sdk.AccAddress([]byte("output")) + addr1 := sdk.BytesToAccAddress([]byte("input")) + addr2 := sdk.BytesToAccAddress([]byte("output")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) var msg = MsgMultiSend{ Inputs: []Input{NewInput(addr1, coins)}, diff --git a/x/crisis/keeper/msg_server.go b/x/crisis/keeper/msg_server.go index a525efe9ae..f80a06c5e7 100644 --- a/x/crisis/keeper/msg_server.go +++ b/x/crisis/keeper/msg_server.go @@ -13,11 +13,7 @@ func (k Keeper) VerifyInvariant(goCtx context.Context, msg *types.MsgVerifyInvar ctx := sdk.UnwrapSDKContext(goCtx) constantFee := sdk.NewCoins(k.GetConstantFee(ctx)) - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - if err := k.SendCoinsFromAccountToFeeCollector(ctx, sender, constantFee); err != nil { + if err := k.SendCoinsFromAccountToFeeCollector(ctx, sdk.AccAddress(msg.Sender), constantFee); err != nil { return nil, err } diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index 08a93a0dcd..c90c0ff33b 100644 --- a/x/crisis/types/msgs.go +++ b/x/crisis/types/msgs.go @@ -2,6 +2,7 @@ package types import ( sdk "github.com/line/lfb-sdk/types" + "github.com/line/lfb-sdk/types/errors" ) // ensure Msg interface compliance at compile time @@ -22,8 +23,7 @@ func (msg MsgVerifyInvariant) Type() string { return "verify_invariant" } // get the bytes for the message signer to sign on func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { - sender, _ := sdk.AccAddressFromBech32(msg.Sender) - return []sdk.AccAddress{sender} + return []sdk.AccAddress{sdk.AccAddress(msg.Sender)} } // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant @@ -37,6 +37,9 @@ func (msg MsgVerifyInvariant) ValidateBasic() error { if msg.Sender == "" { return ErrNoSender } + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + return errors.Wrapf(errors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } return nil } diff --git a/x/distribution/abci.go b/x/distribution/abci.go index 9c7c3bea0d..34698cc90a 100644 --- a/x/distribution/abci.go +++ b/x/distribution/abci.go @@ -33,6 +33,6 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) } // record the proposer for when we payout on the next block - consAddr := sdk.ConsAddress(req.Header.ProposerAddress) + consAddr := sdk.BytesToConsAddress(req.Header.ProposerAddress) k.SetPreviousProposerConsAddr(ctx, consAddr) } diff --git a/x/distribution/client/cli/cli_test.go b/x/distribution/client/cli/cli_test.go index 42c26a8af7..5ffd431bbd 100644 --- a/x/distribution/client/cli/cli_test.go +++ b/x/distribution/client/cli/cli_test.go @@ -130,7 +130,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorOutstandingRewards() { "json output", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), + val.Address.ToValAddress().String(), fmt.Sprintf("--%s=json", ostcli.OutputFlag), }, false, @@ -141,7 +141,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorOutstandingRewards() { []string{ fmt.Sprintf("--%s=text", ostcli.OutputFlag), fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), + val.Address.ToValAddress().String(), }, false, `rewards: @@ -193,7 +193,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorCommission() { "json output", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), + val.Address.ToValAddress().String(), fmt.Sprintf("--%s=json", ostcli.OutputFlag), }, false, @@ -204,7 +204,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorCommission() { []string{ fmt.Sprintf("--%s=text", ostcli.OutputFlag), fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), + val.Address.ToValAddress().String(), }, false, `commission: @@ -256,7 +256,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { "invalid start height", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), "-1", "3", + val.Address.ToValAddress().String(), "-1", "3", }, true, "", @@ -265,7 +265,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { "invalid end height", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), "1", "-3", + val.Address.ToValAddress().String(), "1", "-3", }, true, "", @@ -274,7 +274,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { "json output", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), "1", "3", + val.Address.ToValAddress().String(), "1", "3", fmt.Sprintf("--%s=json", ostcli.OutputFlag), }, false, @@ -285,7 +285,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { []string{ fmt.Sprintf("--%s=text", ostcli.OutputFlag), fmt.Sprintf("--%s=3", flags.FlagHeight), - sdk.ValAddress(val.Address).String(), "1", "3", + val.Address.ToValAddress().String(), "1", "3", }, false, "pagination:\n next_key: null\n total: \"0\"\nslashes: []", @@ -313,7 +313,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { func (s *IntegrationTestSuite) TestGetCmdQueryDelegatorRewards() { val := s.network.Validators[0] addr := val.Address - valAddr := sdk.ValAddress(addr) + valAddr := sdk.AccAddress(addr).ToValAddress() _, err := s.network.WaitForHeightWithTimeout(11, time.Minute) s.Require().NoError(err) @@ -474,7 +474,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { }, { "valid transaction", - sdk.ValAddress(val.Address), + val.Address.ToValAddress(), []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -485,7 +485,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { }, { "valid transaction (with commission)", - sdk.ValAddress(val.Address), + val.Address.ToValAddress(), []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index c58ac967ef..40e2acad0b 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -88,14 +88,14 @@ $ %s query distribution validator-outstanding-rewards %s1lwjmdnks33xwnmfayc64ycp } queryClient := types.NewQueryClient(clientCtx) - validatorAddr, err := sdk.ValAddressFromBech32(args[0]) + err = sdk.ValidateValAddress(args[0]) if err != nil { return err } res, err := queryClient.ValidatorOutstandingRewards( context.Background(), - &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: validatorAddr.String()}, + &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: args[0]}, ) if err != nil { return err @@ -133,14 +133,14 @@ $ %s query distribution commission %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - validatorAddr, err := sdk.ValAddressFromBech32(args[0]) + err = sdk.ValidateValAddress(args[0]) if err != nil { return err } res, err := queryClient.ValidatorCommission( context.Background(), - &types.QueryValidatorCommissionRequest{ValidatorAddress: validatorAddr.String()}, + &types.QueryValidatorCommissionRequest{ValidatorAddress: args[0]}, ) if err != nil { return err @@ -178,7 +178,7 @@ $ %s query distribution slashes %svaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - validatorAddr, err := sdk.ValAddressFromBech32(args[0]) + err = sdk.ValidateValAddress(args[0]) if err != nil { return err } @@ -201,7 +201,7 @@ $ %s query distribution slashes %svaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj res, err := queryClient.ValidatorSlashes( context.Background(), &types.QueryValidatorSlashesRequest{ - ValidatorAddress: validatorAddr.String(), + ValidatorAddress: args[0], StartingHeight: startHeight, EndingHeight: endHeight, Pagination: pageReq, @@ -246,21 +246,21 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh } queryClient := types.NewQueryClient(clientCtx) - delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) + err = sdk.ValidateAccAddress(args[0]) if err != nil { return err } // query for rewards from a particular delegation if len(args) == 2 { - validatorAddr, err := sdk.ValAddressFromBech32(args[1]) + err := sdk.ValidateValAddress(args[1]) if err != nil { return err } res, err := queryClient.DelegationRewards( context.Background(), - &types.QueryDelegationRewardsRequest{DelegatorAddress: delegatorAddr.String(), ValidatorAddress: validatorAddr.String()}, + &types.QueryDelegationRewardsRequest{DelegatorAddress: args[0], ValidatorAddress: args[1]}, ) if err != nil { return err @@ -271,7 +271,7 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh res, err := queryClient.DelegationTotalRewards( context.Background(), - &types.QueryDelegationTotalRewardsRequest{DelegatorAddress: delegatorAddr.String()}, + &types.QueryDelegationTotalRewardsRequest{DelegatorAddress: args[0]}, ) if err != nil { return err diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index b2979ff83a..fbbc998336 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -100,15 +100,15 @@ $ %s tx distribution withdraw-rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj return err } delAddr := clientCtx.GetFromAddress() - valAddr, err := sdk.ValAddressFromBech32(args[0]) + err = sdk.ValidateValAddress(args[0]) if err != nil { return err } - msgs := []sdk.Msg{types.NewMsgWithdrawDelegatorReward(delAddr, valAddr)} + msgs := []sdk.Msg{types.NewMsgWithdrawDelegatorReward(delAddr, sdk.ValAddress(args[0]))} if commission, _ := cmd.Flags().GetBool(FlagCommission); commission { - msgs = append(msgs, types.NewMsgWithdrawValidatorCommission(valAddr)) + msgs = append(msgs, types.NewMsgWithdrawValidatorCommission(sdk.ValAddress(args[0]))) } for _, msg := range msgs { @@ -164,12 +164,12 @@ $ %s tx distribution withdraw-all-rewards --from mykey // build multi-message transaction msgs := make([]sdk.Msg, 0, len(validators)) for _, valAddr := range validators { - val, err := sdk.ValAddressFromBech32(valAddr) + err := sdk.ValidateValAddress(valAddr) if err != nil { return err } - msg := types.NewMsgWithdrawDelegatorReward(delAddr, val) + msg := types.NewMsgWithdrawDelegatorReward(delAddr, sdk.ValAddress(valAddr)) if err := msg.ValidateBasic(); err != nil { return err } @@ -209,12 +209,12 @@ $ %s tx distribution set-withdraw-addr %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } delAddr := clientCtx.GetFromAddress() - withdrawAddr, err := sdk.AccAddressFromBech32(args[0]) + err = sdk.ValidateAccAddress(args[0]) if err != nil { return err } - msg := types.NewMsgSetWithdrawAddress(delAddr, withdrawAddr) + msg := types.NewMsgSetWithdrawAddress(delAddr, sdk.AccAddress(args[0])) if err := msg.ValidateBasic(); err != nil { return err } @@ -316,11 +316,12 @@ Where proposal.json contains: } from := clientCtx.GetFromAddress() - recpAddr, err := sdk.AccAddressFromBech32(proposal.Recipient) + err = sdk.ValidateAccAddress(proposal.Recipient) if err != nil { return err } - content := types.NewCommunityPoolSpendProposal(proposal.Title, proposal.Description, recpAddr, amount) + content := types.NewCommunityPoolSpendProposal(proposal.Title, proposal.Description, + sdk.AccAddress(proposal.Recipient), amount) msg, err := govtypes.NewMsgSubmitProposal(content, deposit, from) if err != nil { diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index 7dbe2433e6..8fccb9b75a 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -28,7 +28,7 @@ func Test_splitAndCall_NoMessages(t *testing.T) { func Test_splitAndCall_Splitting(t *testing.T) { clientCtx := client.Context{} - addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) // Add five messages msgs := []sdk.Msg{ diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index 9fc547659e..453afd3d9f 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -11,17 +11,17 @@ import ( // QueryDelegationRewards queries a delegation rewards between a delegator and a // validator. func QueryDelegationRewards(clientCtx client.Context, delAddr, valAddr string) ([]byte, int64, error) { - delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) + err := sdk.ValidateAccAddress(delAddr) if err != nil { return nil, 0, err } - validatorAddr, err := sdk.ValAddressFromBech32(valAddr) + err = sdk.ValidateValAddress(valAddr) if err != nil { return nil, 0, err } - params := types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr) + params := types.NewQueryDelegationRewardsParams(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)) bz, err := clientCtx.LegacyAmino.MarshalJSON(params) if err != nil { return nil, 0, fmt.Errorf("failed to marshal params: %w", err) diff --git a/x/distribution/client/rest/tx.go b/x/distribution/client/rest/tx.go index b4215799ec..4121447674 100644 --- a/x/distribution/client/rest/tx.go +++ b/x/distribution/client/rest/tx.go @@ -187,12 +187,12 @@ func newFundCommunityPoolHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + err := sdk.ValidateAccAddress(req.BaseReq.From) if rest.CheckBadRequestError(w, err) { return } - msg := types.NewMsgFundCommunityPool(req.Amount, fromAddr) + msg := types.NewMsgFundCommunityPool(req.Amount, sdk.AccAddress(req.BaseReq.From)) if rest.CheckBadRequestError(w, msg.ValidateBasic()) { return } @@ -204,19 +204,21 @@ func newFundCommunityPoolHandlerFn(clientCtx client.Context) http.HandlerFunc { // Auxiliary func checkDelegatorAddressVar(w http.ResponseWriter, r *http.Request) (sdk.AccAddress, bool) { - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["delegatorAddr"]) + addr := mux.Vars(r)["delegatorAddr"] + err := sdk.ValidateAccAddress(addr) if rest.CheckBadRequestError(w, err) { - return nil, false + return "", false } - return addr, true + return sdk.AccAddress(addr), true } func checkValidatorAddressVar(w http.ResponseWriter, r *http.Request) (sdk.ValAddress, bool) { - addr, err := sdk.ValAddressFromBech32(mux.Vars(r)["validatorAddr"]) + addr := mux.Vars(r)["validatorAddr"] + err := sdk.ValidateValAddress(addr) if rest.CheckBadRequestError(w, err) { - return nil, false + return "", false } - return addr, true + return sdk.ValAddress(addr), true } diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go index 21605e6ac3..57bf16557e 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -84,7 +84,7 @@ func (k Keeper) AllocateTokens( // allocate tokens proportionally to voting power // TODO consider parallelizing later, ref https://github.com/cosmos/cosmos-sdk/pull/3099#discussion_r246276376 for _, vote := range previousVotes { - validator := k.stakingKeeper.ValidatorByConsAddr(ctx, vote.Validator.Address) + validator := k.stakingKeeper.ValidatorByConsAddr(ctx, sdk.BytesToConsAddress(vote.Validator.Address)) // TODO consider microslashing for missing votes. // ref https://github.com/cosmos/cosmos-sdk/issues/2525#issuecomment-430838701 diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 6fbafe2b1e..229f448602 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -24,7 +24,7 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { // create validator with 50% commission tstaking.Commission = stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - tstaking.CreateValidator(sdk.ValAddress(addrs[0]), valConsPk1, sdk.NewInt(100), true) + tstaking.CreateValidator(addrs[0].ToValAddress(), valConsPk1, sdk.NewInt(100), true) val := app.StakingKeeper.Validator(ctx, valAddrs[0]) // allocate tokens @@ -181,7 +181,7 @@ func TestAllocateTokensTruncation(t *testing.T) { SignedLastBlock: true, }, } - app.DistrKeeper.AllocateTokens(ctx, 31, 31, sdk.ConsAddress(valConsPk2.Address()), votes) + app.DistrKeeper.AllocateTokens(ctx, 31, 31, sdk.BytesToConsAddress(valConsPk2.Address()), votes) require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsValid()) require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsValid()) diff --git a/x/distribution/keeper/common_test.go b/x/distribution/keeper/common_test.go index 02031c89f4..7d7b6d52ab 100644 --- a/x/distribution/keeper/common_test.go +++ b/x/distribution/keeper/common_test.go @@ -14,8 +14,8 @@ var ( valConsPk2 = PKS[1] valConsPk3 = PKS[2] - valConsAddr1 = sdk.ConsAddress(valConsPk1.Address()) - valConsAddr2 = sdk.ConsAddress(valConsPk2.Address()) + valConsAddr1 = sdk.BytesToConsAddress(valConsPk1.Address()) + valConsAddr2 = sdk.BytesToConsAddress(valConsPk2.Address()) distrAcc = authtypes.NewEmptyModuleAccount(types.ModuleName) ) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 0c3a98628c..3a8947750d 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -32,7 +32,7 @@ func TestCalculateRewardsBasic(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) // historical count should be 2 (once for validator init, once for delegation init) require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) @@ -88,7 +88,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) // end period endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) @@ -151,7 +151,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) // end period endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) @@ -225,7 +225,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) // allocate some rewards initial := int64(20) @@ -234,8 +234,8 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // second delegation tstaking.Ctx = ctx - tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewInt(100)) - del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + tstaking.Delegate(valAddrs[1].ToAccAddress(), valAddrs[0], sdk.NewInt(100)) + del2 := app.StakingKeeper.Delegation(ctx, valAddrs[1].ToAccAddress(), valAddrs[0]) // fetch updated validator val = app.StakingKeeper.Validator(ctx, valAddrs[0]) @@ -292,7 +292,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { expTokens := balanceTokens.Sub(valTokens) require.Equal(t, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)}, - app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), + app.BankKeeper.GetAllBalances(ctx, valAddrs[0].ToAccAddress()), ) // end block to bond validator @@ -314,7 +314,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // withdraw rewards - _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) require.Nil(t, err) // historical count should still be 2 (added one record, cleared one) @@ -324,7 +324,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { exp := balanceTokens.Sub(valTokens).Add(initial.QuoRaw(2)) require.Equal(t, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), + app.BankKeeper.GetAllBalances(ctx, valAddrs[0].ToAccAddress()), ) // withdraw commission @@ -335,7 +335,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { exp = balanceTokens.Sub(valTokens).Add(initial) require.Equal(t, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), + app.BankKeeper.GetAllBalances(ctx, valAddrs[0].ToAccAddress()), ) } @@ -360,7 +360,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) // end period endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) @@ -428,7 +428,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) // allocate some rewards initial := sdk.TokensFromConsensusPower(30).ToDec() @@ -441,9 +441,9 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // second delegation - tstaking.DelegateWithPower(sdk.AccAddress(valAddrs[1]), valAddrs[0], 100) + tstaking.DelegateWithPower(valAddrs[1].ToAccAddress(), valAddrs[0], 100) - del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + del2 := app.StakingKeeper.Delegation(ctx, valAddrs[1].ToAccAddress(), valAddrs[0]) // end block staking.EndBlocker(ctx, app.StakingKeeper) @@ -510,7 +510,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) // allocate some rewards app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) @@ -519,14 +519,14 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // second delegation - tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewInt(100)) + tstaking.Delegate(valAddrs[1].ToAccAddress(), valAddrs[0], sdk.NewInt(100)) // historical count should be 3 (second delegation init) require.Equal(t, uint64(3), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // fetch updated validator val = app.StakingKeeper.Validator(ctx, valAddrs[0]) - del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + del2 := app.StakingKeeper.Delegation(ctx, valAddrs[1].ToAccAddress(), valAddrs[0]) // end block staking.EndBlocker(ctx, app.StakingKeeper) @@ -538,11 +538,11 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // first delegator withdraws - _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) require.NoError(t, err) // second delegator withdraws - _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, valAddrs[1].ToAccAddress(), valAddrs[0]) require.NoError(t, err) // historical count should be 3 (validator init + two delegations) @@ -577,7 +577,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // first delegator withdraws again - _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) require.NoError(t, err) // end period diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go index 57166fa3ff..9bad005b3c 100644 --- a/x/distribution/keeper/genesis.go +++ b/x/distribution/keeper/genesis.go @@ -15,74 +15,43 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data types.GenesisState) { k.SetParams(ctx, data.Params) for _, dwi := range data.DelegatorWithdrawInfos { - delegatorAddress, err := sdk.AccAddressFromBech32(dwi.DelegatorAddress) - if err != nil { - panic(err) - } - withdrawAddress, err := sdk.AccAddressFromBech32(dwi.WithdrawAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(dwi.DelegatorAddress) + withdrawAddress := sdk.AccAddress(dwi.WithdrawAddress) k.SetDelegatorWithdrawAddr(ctx, delegatorAddress, withdrawAddress) } var previousProposer sdk.ConsAddress if data.PreviousProposer != "" { - var err error - previousProposer, err = sdk.ConsAddressFromBech32(data.PreviousProposer) - if err != nil { - panic(err) - } + previousProposer = sdk.ConsAddress(data.PreviousProposer) } k.SetPreviousProposerConsAddr(ctx, previousProposer) for _, rew := range data.OutstandingRewards { - valAddr, err := sdk.ValAddressFromBech32(rew.ValidatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(rew.ValidatorAddress) k.SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: rew.OutstandingRewards}) - moduleHoldings = moduleHoldings.Add(rew.OutstandingRewards...) + moduleHoldings = rew.OutstandingRewards } for _, acc := range data.ValidatorAccumulatedCommissions { - valAddr, err := sdk.ValAddressFromBech32(acc.ValidatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(acc.ValidatorAddress) k.SetValidatorAccumulatedCommission(ctx, valAddr, acc.Accumulated) } for _, his := range data.ValidatorHistoricalRewards { - valAddr, err := sdk.ValAddressFromBech32(his.ValidatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(his.ValidatorAddress) k.SetValidatorHistoricalRewards(ctx, valAddr, his.Period, his.Rewards) } for _, cur := range data.ValidatorCurrentRewards { - valAddr, err := sdk.ValAddressFromBech32(cur.ValidatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(cur.ValidatorAddress) k.SetValidatorCurrentRewards(ctx, valAddr, cur.Rewards) } for _, del := range data.DelegatorStartingInfos { - valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) - if err != nil { - panic(err) - } - delegatorAddress, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(del.ValidatorAddress) + delegatorAddress := sdk.AccAddress(del.DelegatorAddress) k.SetDelegatorStartingInfo(ctx, valAddr, delegatorAddress, del.StartingInfo) } for _, evt := range data.ValidatorSlashEvents { - valAddr, err := sdk.ValAddressFromBech32(evt.ValidatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(evt.ValidatorAddress) k.SetValidatorSlashEvent(ctx, valAddr, evt.Height, evt.Period, evt.ValidatorSlashEvent) } diff --git a/x/distribution/keeper/grpc_query.go b/x/distribution/keeper/grpc_query.go index b70300f729..4f62f92e38 100644 --- a/x/distribution/keeper/grpc_query.go +++ b/x/distribution/keeper/grpc_query.go @@ -37,11 +37,11 @@ func (k Keeper) ValidatorOutstandingRewards(c context.Context, req *types.QueryV ctx := sdk.UnwrapSDKContext(c) - valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) + err := sdk.ValidateValAddress(req.ValidatorAddress) if err != nil { return nil, err } - rewards := k.GetValidatorOutstandingRewards(ctx, valAdr) + rewards := k.GetValidatorOutstandingRewards(ctx, sdk.ValAddress(req.ValidatorAddress)) return &types.QueryValidatorOutstandingRewardsResponse{Rewards: rewards}, nil } @@ -58,11 +58,11 @@ func (k Keeper) ValidatorCommission(c context.Context, req *types.QueryValidator ctx := sdk.UnwrapSDKContext(c) - valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) + err := sdk.ValidateValAddress(req.ValidatorAddress) if err != nil { return nil, err } - commission := k.GetValidatorAccumulatedCommission(ctx, valAdr) + commission := k.GetValidatorAccumulatedCommission(ctx, sdk.ValAddress(req.ValidatorAddress)) return &types.QueryValidatorCommissionResponse{Commission: commission}, nil } @@ -84,11 +84,11 @@ func (k Keeper) ValidatorSlashes(c context.Context, req *types.QueryValidatorSla ctx := sdk.UnwrapSDKContext(c) events := make([]types.ValidatorSlashEvent, 0) store := ctx.KVStore(k.storeKey) - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) + err := sdk.ValidateValAddress(req.ValidatorAddress) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid validator address") } - slashesStore := prefix.NewStore(store, types.GetValidatorSlashEventPrefix(valAddr)) + slashesStore := prefix.NewStore(store, types.GetValidatorSlashEventPrefix(sdk.ValAddress(req.ValidatorAddress))) pageRes, err := query.FilteredPaginate(slashesStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { var result types.ValidatorSlashEvent @@ -131,21 +131,21 @@ func (k Keeper) DelegationRewards(c context.Context, req *types.QueryDelegationR ctx := sdk.UnwrapSDKContext(c) - valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) + err := sdk.ValidateValAddress(req.ValidatorAddress) if err != nil { return nil, err } - val := k.stakingKeeper.Validator(ctx, valAdr) + val := k.stakingKeeper.Validator(ctx, sdk.ValAddress(req.ValidatorAddress)) if val == nil { return nil, sdkerrors.Wrap(types.ErrNoValidatorExists, req.ValidatorAddress) } - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + err = sdk.ValidateAccAddress(req.DelegatorAddress) if err != nil { return nil, err } - del := k.stakingKeeper.Delegation(ctx, delAdr, valAdr) + del := k.stakingKeeper.Delegation(ctx, sdk.AccAddress(req.DelegatorAddress), sdk.ValAddress(req.ValidatorAddress)) if del == nil { return nil, types.ErrNoDelegationExists } @@ -171,13 +171,13 @@ func (k Keeper) DelegationTotalRewards(c context.Context, req *types.QueryDelega total := sdk.DecCoins{} var delRewards []types.DelegationDelegatorReward - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + err := sdk.ValidateAccAddress(req.DelegatorAddress) if err != nil { return nil, err } k.stakingKeeper.IterateDelegations( - ctx, delAdr, + ctx, sdk.AccAddress(req.DelegatorAddress), func(_ int64, del stakingtypes.DelegationI) (stop bool) { valAddr := del.GetValidatorAddr() val := k.stakingKeeper.Validator(ctx, valAddr) @@ -204,14 +204,14 @@ func (k Keeper) DelegatorValidators(c context.Context, req *types.QueryDelegator } ctx := sdk.UnwrapSDKContext(c) - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + err := sdk.ValidateAccAddress(req.DelegatorAddress) if err != nil { return nil, err } var validators []string k.stakingKeeper.IterateDelegations( - ctx, delAdr, + ctx, sdk.AccAddress(req.DelegatorAddress), func(_ int64, del stakingtypes.DelegationI) (stop bool) { validators = append(validators, del.GetValidatorAddr().String()) return false @@ -230,13 +230,13 @@ func (k Keeper) DelegatorWithdrawAddress(c context.Context, req *types.QueryDele if req.DelegatorAddress == "" { return nil, status.Error(codes.InvalidArgument, "empty delegator address") } - delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) + err := sdk.ValidateAccAddress(req.DelegatorAddress) if err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) - withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, delAdr) + withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, sdk.AccAddress(req.DelegatorAddress)) return &types.QueryDelegatorWithdrawAddressResponse{WithdrawAddress: withdrawAddr.String()}, nil } diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 2a73678d1c..133b659a7b 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -34,7 +34,7 @@ func NewKeeper( ) Keeper { // ensure distribution module account is set - if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { + if addr := ak.GetModuleAddress(types.ModuleName); addr.Empty() { panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) } @@ -128,7 +128,7 @@ func (k Keeper) WithdrawValidatorCommission(ctx sdk.Context, valAddr sdk.ValAddr k.SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: outstanding.Sub(sdk.NewDecCoinsFromCoins(commission...))}) if !commission.IsZero() { - accAddr := sdk.AccAddress(valAddr) + accAddr := valAddr.ToAccAddress() withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, accAddr) err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, commission) if err != nil { diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index 00be96db62..0f5e6943cd 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -56,7 +56,7 @@ func TestWithdrawValidatorCommission(t *testing.T) { app.AccountKeeper.SetModuleAccount(ctx, distrAcc) // check initial balance - balance := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) + balance := app.BankKeeper.GetAllBalances(ctx, valAddrs[0].ToAccAddress()) expTokens := sdk.TokensFromConsensusPower(1000) expCoins := sdk.NewCoins(sdk.NewCoin("stake", expTokens)) require.Equal(t, expCoins, balance) @@ -72,7 +72,7 @@ func TestWithdrawValidatorCommission(t *testing.T) { require.NoError(t, err) // check balance increase - balance = app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) + balance = app.BankKeeper.GetAllBalances(ctx, valAddrs[0].ToAccAddress()) require.Equal(t, sdk.NewCoins( sdk.NewCoin("mytoken", sdk.NewInt(1)), sdk.NewCoin("stake", expTokens.AddRaw(1)), diff --git a/x/distribution/keeper/msg_server.go b/x/distribution/keeper/msg_server.go index 47200446ed..7b9d572a6d 100644 --- a/x/distribution/keeper/msg_server.go +++ b/x/distribution/keeper/msg_server.go @@ -25,15 +25,15 @@ var _ types.MsgServer = msgServer{} func (k msgServer) SetWithdrawAddress(goCtx context.Context, msg *types.MsgSetWithdrawAddress) (*types.MsgSetWithdrawAddressResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + err := sdk.ValidateAccAddress(msg.DelegatorAddress) if err != nil { return nil, err } - withdrawAddress, err := sdk.AccAddressFromBech32(msg.WithdrawAddress) + err = sdk.ValidateAccAddress(msg.WithdrawAddress) if err != nil { return nil, err } - err = k.SetWithdrawAddr(ctx, delegatorAddress, withdrawAddress) + err = k.SetWithdrawAddr(ctx, sdk.AccAddress(msg.DelegatorAddress), sdk.AccAddress(msg.WithdrawAddress)) if err != nil { return nil, err } @@ -52,15 +52,16 @@ func (k msgServer) SetWithdrawAddress(goCtx context.Context, msg *types.MsgSetWi func (k msgServer) WithdrawDelegatorReward(goCtx context.Context, msg *types.MsgWithdrawDelegatorReward) (*types.MsgWithdrawDelegatorRewardResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + err := sdk.ValidateValAddress(msg.ValidatorAddress) if err != nil { return nil, err } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + err = sdk.ValidateAccAddress(msg.DelegatorAddress) if err != nil { return nil, err } - amount, err := k.WithdrawDelegationRewards(ctx, delegatorAddress, valAddr) + amount, err := k.WithdrawDelegationRewards(ctx, sdk.AccAddress(msg.DelegatorAddress), + sdk.ValAddress(msg.ValidatorAddress)) if err != nil { return nil, err } @@ -90,11 +91,11 @@ func (k msgServer) WithdrawDelegatorReward(goCtx context.Context, msg *types.Msg func (k msgServer) WithdrawValidatorCommission(goCtx context.Context, msg *types.MsgWithdrawValidatorCommission) (*types.MsgWithdrawValidatorCommissionResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + err := sdk.ValidateValAddress(msg.ValidatorAddress) if err != nil { return nil, err } - amount, err := k.Keeper.WithdrawValidatorCommission(ctx, valAddr) + amount, err := k.Keeper.WithdrawValidatorCommission(ctx, sdk.ValAddress(msg.ValidatorAddress)) if err != nil { return nil, err } @@ -125,11 +126,11 @@ func (k msgServer) WithdrawValidatorCommission(goCtx context.Context, msg *types func (k msgServer) FundCommunityPool(goCtx context.Context, msg *types.MsgFundCommunityPool) (*types.MsgFundCommunityPoolResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - depositer, err := sdk.AccAddressFromBech32(msg.Depositor) + err := sdk.ValidateAccAddress(msg.Depositor) if err != nil { return nil, err } - if err := k.Keeper.FundCommunityPool(ctx, msg.Amount, depositer); err != nil { + if err := k.Keeper.FundCommunityPool(ctx, msg.Amount, sdk.AccAddress(msg.Depositor)); err != nil { return nil, err } diff --git a/x/distribution/keeper/proposal_handler.go b/x/distribution/keeper/proposal_handler.go index 7ca1c7cba9..d1d23f290a 100644 --- a/x/distribution/keeper/proposal_handler.go +++ b/x/distribution/keeper/proposal_handler.go @@ -12,12 +12,12 @@ func HandleCommunityPoolSpendProposal(ctx sdk.Context, k Keeper, p *types.Commun return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive external funds", p.Recipient) } - recipient, addrErr := sdk.AccAddressFromBech32(p.Recipient) + addrErr := sdk.ValidateAccAddress(p.Recipient) if addrErr != nil { return addrErr } - err := k.DistributeFromFeePool(ctx, p.Amount, recipient) + err := k.DistributeFromFeePool(ctx, p.Amount, sdk.AccAddress(p.Recipient)) if err != nil { return err } diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index 10cc4a7dbb..92bbb3403b 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -154,7 +154,7 @@ func TestQueries(t *testing.T) { require.Equal(t, commission, retCommission) // test delegator's total rewards query - delRewards := getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1)) + delRewards := getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, valOpAddr1.ToAccAddress()) require.Equal(t, types.QueryDelegatorTotalRewardsResponse{}, delRewards) // test validator slashes query with height range @@ -177,17 +177,17 @@ func TestQueries(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) val := app.StakingKeeper.Validator(ctx, valOpAddr1) - rewards := getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) + rewards := getQueriedDelegationRewards(t, ctx, cdc, querier, valOpAddr1.ToAccAddress(), valOpAddr1) require.True(t, rewards.IsZero()) initial := int64(10) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) - rewards = getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) + rewards = getQueriedDelegationRewards(t, ctx, cdc, querier, valOpAddr1.ToAccAddress(), valOpAddr1) require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) // test delegator's total rewards query - delRewards = getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1)) + delRewards = getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, valOpAddr1.ToAccAddress()) expectedDelReward := types.NewDelegationDelegatorReward(valOpAddr1, sdk.DecCoins{sdk.NewInt64DecCoin("stake", 5)}) wantDelRewards := types.NewQueryDelegatorTotalRewardsResponse( diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go index c8fd9bd5ae..f78939ee79 100644 --- a/x/distribution/keeper/store.go +++ b/x/distribution/keeper/store.go @@ -72,13 +72,13 @@ func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) sdk.ConsAddress { addrValue := gogotypes.BytesValue{} k.cdc.MustUnmarshalBinaryBare(bz, &addrValue) - return addrValue.GetValue() + return sdk.ConsAddress(string(addrValue.GetValue())) } // set the proposer public key for this block func (k Keeper) SetPreviousProposerConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryBare(&gogotypes.BytesValue{Value: consAddr}) + bz := k.cdc.MustMarshalBinaryBare(&gogotypes.BytesValue{Value: consAddr.Bytes()}) store.Set(types.ProposerKey, bz) } diff --git a/x/distribution/proposal_handler_test.go b/x/distribution/proposal_handler_test.go index 294a106f82..826550e910 100644 --- a/x/distribution/proposal_handler_test.go +++ b/x/distribution/proposal_handler_test.go @@ -15,7 +15,7 @@ import ( var ( delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) + delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) amount = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))) ) diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index ebace48f79..3409f97cc9 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -16,9 +16,9 @@ import ( var ( delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) + delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) + valAddr1 = sdk.BytesToValAddress(delPk1.Address()) + consAddr1 = sdk.BytesToConsAddress(delPk1.Address()) ) func TestDecodeDistributionStore(t *testing.T) { diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index a1a6f6329f..f46744d4be 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -192,7 +192,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgWithdrawValidatorCommission, "validator commission is zero"), nil, nil } - simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, validator.GetOperator().ToAccAddress()) if !found { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgWithdrawValidatorCommission, "could not find account"), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go index dcf3335236..bf2401c0bf 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -246,7 +246,7 @@ func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, comm require := suite.Require() account := accounts[n] valPubKey := account.PubKey - valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(account.PubKey.Address()) validator, err := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes. Description{}) require.NoError(err) diff --git a/x/distribution/types/common_test.go b/x/distribution/types/common_test.go index 3aff0fe707..4b09478c05 100644 --- a/x/distribution/types/common_test.go +++ b/x/distribution/types/common_test.go @@ -11,17 +11,17 @@ var ( delPk1 = ed25519.GenPrivKey().PubKey() delPk2 = ed25519.GenPrivKey().PubKey() delPk3 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - delAddr2 = sdk.AccAddress(delPk2.Address()) - delAddr3 = sdk.AccAddress(delPk3.Address()) + delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) + delAddr2 = sdk.BytesToAccAddress(delPk2.Address()) + delAddr3 = sdk.BytesToAccAddress(delPk3.Address()) emptyDelAddr sdk.AccAddress valPk1 = ed25519.GenPrivKey().PubKey() valPk2 = ed25519.GenPrivKey().PubKey() valPk3 = ed25519.GenPrivKey().PubKey() - valAddr1 = sdk.ValAddress(valPk1.Address()) - valAddr2 = sdk.ValAddress(valPk2.Address()) - valAddr3 = sdk.ValAddress(valPk3.Address()) + valAddr1 = sdk.BytesToValAddress(valPk1.Address()) + valAddr2 = sdk.BytesToValAddress(valPk2.Address()) + valAddr3 = sdk.BytesToValAddress(valPk3.Address()) emptyValAddr sdk.ValAddress emptyPubkey cryptotypes.PubKey diff --git a/x/distribution/types/keys.go b/x/distribution/types/keys.go index 479bd8812b..e5c865dc86 100644 --- a/x/distribution/types/keys.go +++ b/x/distribution/types/keys.go @@ -2,6 +2,7 @@ package types import ( "encoding/binary" + "strings" sdk "github.com/line/lfb-sdk/types" ) @@ -51,52 +52,36 @@ var ( ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction + + AddressDelimiter = "," ) // gets an address from a validator's outstanding rewards key func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) { addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } return sdk.ValAddress(addr) } // gets an address from a delegator's withdraw info key func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) { addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } return sdk.AccAddress(addr) } // gets the addresses from a delegator starting info key func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) { - addr := key[1 : 1+sdk.AddrLen] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - valAddr = sdk.ValAddress(addr) - addr = key[1+sdk.AddrLen:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - delAddr = sdk.AccAddress(addr) + addrsStr := string(key[1:]) + addrs := strings.Split(addrsStr, AddressDelimiter) + valAddr = sdk.ValAddress(addrs[0]) + delAddr = sdk.AccAddress(addrs[1]) return } // gets the address & period from a validator's historical rewards key func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddress, period uint64) { - addr := key[1 : 1+sdk.AddrLen] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } + addr := key[1 : len(key)-8] valAddr = sdk.ValAddress(addr) - b := key[1+sdk.AddrLen:] - if len(b) != 8 { - panic("unexpected key length") - } + b := key[len(key)-8:] period = binary.LittleEndian.Uint64(b) return } @@ -104,30 +89,20 @@ func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddr // gets the address from a validator's current rewards key func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) { addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } return sdk.ValAddress(addr) } // gets the address from a validator's accumulated commission key func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) { addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } return sdk.ValAddress(addr) } // gets the height from a validator's slash event key func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) { - addr := key[1 : 1+sdk.AddrLen] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } + addr := key[1 : len(key)-8] valAddr = sdk.ValAddress(addr) - startB := 1 + sdk.AddrLen - b := key[startB : startB+8] // the next 8 bytes represent the height + b := key[len(key)-8:] // the next 8 bytes represent the height height = binary.BigEndian.Uint64(b) return } @@ -144,7 +119,7 @@ func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte { // gets the key for a delegator's starting info func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte { - return append(append(DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...) + return append(append(append(DelegatorStartingInfoPrefix, v.Bytes()...), AddressDelimiter...), d.Bytes()...) } // gets the prefix key for a validator's historical rewards diff --git a/x/distribution/types/msg.go b/x/distribution/types/msg.go index d3a65b2fcf..5507e22e1b 100644 --- a/x/distribution/types/msg.go +++ b/x/distribution/types/msg.go @@ -29,11 +29,7 @@ func (msg MsgSetWithdrawAddress) Type() string { return TypeMsgSetWithdrawAddre // Return address that must sign over msg.GetSignBytes() func (msg MsgSetWithdrawAddress) GetSigners() []sdk.AccAddress { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - panic(err) - } - return []sdk.AccAddress{delAddr} + return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} } // get the bytes for the message signer to sign on @@ -50,7 +46,12 @@ func (msg MsgSetWithdrawAddress) ValidateBasic() error { if msg.WithdrawAddress == "" { return ErrEmptyWithdrawAddr } - + if err := sdk.ValidateAccAddress(msg.DelegatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid delegator address (%s)", err) + } + if err := sdk.ValidateAccAddress(msg.WithdrawAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid withdraw address (%s)", err) + } return nil } @@ -66,10 +67,7 @@ func (msg MsgWithdrawDelegatorReward) Type() string { return TypeMsgWithdrawDel // Return address that must sign over msg.GetSignBytes() func (msg MsgWithdrawDelegatorReward) GetSigners() []sdk.AccAddress { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - panic(err) - } + delAddr := sdk.AccAddress(msg.DelegatorAddress) return []sdk.AccAddress{delAddr} } @@ -87,6 +85,12 @@ func (msg MsgWithdrawDelegatorReward) ValidateBasic() error { if msg.ValidatorAddress == "" { return ErrEmptyValidatorAddr } + if err := sdk.ValidateAccAddress(msg.DelegatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid delegator address (%s)", err) + } + if err := sdk.ValidateValAddress(msg.ValidatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid validator address (%s)", err) + } return nil } @@ -101,11 +105,11 @@ func (msg MsgWithdrawValidatorCommission) Type() string { return TypeMsgWithdra // Return address that must sign over msg.GetSignBytes() func (msg MsgWithdrawValidatorCommission) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + valAddrBytes, err := sdk.ValAddressToBytes(msg.ValidatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{valAddr.Bytes()} + return []sdk.AccAddress{sdk.BytesToAccAddress(valAddrBytes)} } // get the bytes for the message signer to sign on @@ -119,6 +123,9 @@ func (msg MsgWithdrawValidatorCommission) ValidateBasic() error { if msg.ValidatorAddress == "" { return ErrEmptyValidatorAddr } + if err := sdk.ValidateValAddress(msg.ValidatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid validator address (%s)", err) + } return nil } @@ -140,10 +147,7 @@ func (msg MsgFundCommunityPool) Type() string { return TypeMsgFundCommunityPool // GetSigners returns the signer addresses that are expected to sign the result // of GetSignBytes. func (msg MsgFundCommunityPool) GetSigners() []sdk.AccAddress { - depoAddr, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } + depoAddr := sdk.AccAddress(msg.Depositor) return []sdk.AccAddress{depoAddr} } @@ -162,6 +166,9 @@ func (msg MsgFundCommunityPool) ValidateBasic() error { if msg.Depositor == "" { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Depositor) } + if err := sdk.ValidateAccAddress(msg.Depositor); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid depositor address (%s)", err) + } return nil } diff --git a/x/distribution/types/msg_test.go b/x/distribution/types/msg_test.go index 4f5d8afead..1bdd0ad6ec 100644 --- a/x/distribution/types/msg_test.go +++ b/x/distribution/types/msg_test.go @@ -80,7 +80,7 @@ func TestMsgDepositIntoCommunityPool(t *testing.T) { depositor sdk.AccAddress expectPass bool }{ - {sdk.NewCoins(sdk.NewInt64Coin("uatom", 10000)), sdk.AccAddress{}, false}, + {sdk.NewCoins(sdk.NewInt64Coin("uatom", 10000)), "", false}, {sdk.Coins{sdk.NewInt64Coin("uatom", 10), sdk.NewInt64Coin("uatom", 10)}, delAddr1, false}, {sdk.NewCoins(sdk.NewInt64Coin("uatom", 1000)), delAddr1, true}, } diff --git a/x/evidence/keeper/infraction.go b/x/evidence/keeper/infraction.go index 34a9c20931..c6f9b4c1e3 100644 --- a/x/evidence/keeper/infraction.go +++ b/x/evidence/keeper/infraction.go @@ -25,8 +25,8 @@ import ( func (k Keeper) HandleEquivocationEvidence(ctx sdk.Context, evidence *types.Equivocation) { logger := k.Logger(ctx) consAddr := evidence.GetConsensusAddress() - - if _, err := k.slashingKeeper.GetPubkey(ctx, consAddr.Bytes()); err != nil { + consAddrBytes, _ := sdk.ConsAddressToBytes(consAddr.String()) + if _, err := k.slashingKeeper.GetPubkey(ctx, consAddrBytes); err != nil { // Ignore evidence that cannot be handled. // // NOTE: We used to panic with: diff --git a/x/evidence/keeper/infraction_test.go b/x/evidence/keeper/infraction_test.go index 6b495463d5..90a14ada08 100644 --- a/x/evidence/keeper/infraction_test.go +++ b/x/evidence/keeper/infraction_test.go @@ -23,7 +23,7 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign() { // execute end-blocker and verify validator attributes staking.EndBlocker(ctx, suite.app.StakingKeeper) suite.Equal( - suite.app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(operatorAddr)).String(), + suite.app.BankKeeper.GetAllBalances(ctx, operatorAddr.ToAccAddress()).String(), sdk.NewCoins(sdk.NewCoin(stakingParams.BondDenom, initAmt.Sub(selfDelegation))).String(), ) suite.Equal(selfDelegation, suite.app.StakingKeeper.Validator(ctx, operatorAddr).GetBondedTokens()) @@ -37,13 +37,13 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign() { Height: 0, Time: time.Unix(0, 0), Power: power, - ConsensusAddress: sdk.ConsAddress(val.Address()).String(), + ConsensusAddress: sdk.BytesToConsAddress(val.Address()).String(), } suite.app.EvidenceKeeper.HandleEquivocationEvidence(ctx, evidence) // should be jailed and tombstoned suite.True(suite.app.StakingKeeper.Validator(ctx, operatorAddr).IsJailed()) - suite.True(suite.app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(val.Address()))) + suite.True(suite.app.SlashingKeeper.IsTombstoned(ctx, sdk.BytesToConsAddress(val.Address()))) // tokens should be decreased newTokens := suite.app.StakingKeeper.Validator(ctx, operatorAddr).GetTokens() @@ -63,12 +63,12 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign() { // require we be able to unbond now ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - del, _ := suite.app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(operatorAddr), operatorAddr) + del, _ := suite.app.StakingKeeper.GetDelegation(ctx, operatorAddr.ToAccAddress(), operatorAddr) validator, _ := suite.app.StakingKeeper.GetValidator(ctx, operatorAddr) totalBond := validator.TokensFromShares(del.GetShares()).TruncateInt() tstaking.Ctx = ctx tstaking.Denom = stakingParams.BondDenom - tstaking.Undelegate(sdk.AccAddress(operatorAddr), operatorAddr, totalBond, true) + tstaking.Undelegate(operatorAddr.ToAccAddress(), operatorAddr, totalBond, true) } func (suite *KeeperTestSuite) TestHandleDoubleSign_TooOld() { @@ -85,7 +85,7 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign_TooOld() { // execute end-blocker and verify validator attributes staking.EndBlocker(ctx, suite.app.StakingKeeper) suite.Equal( - suite.app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(operatorAddr)), + suite.app.BankKeeper.GetAllBalances(ctx, operatorAddr.ToAccAddress()), sdk.NewCoins(sdk.NewCoin(stakingParams.BondDenom, initAmt.Sub(amt))), ) suite.Equal(amt, suite.app.StakingKeeper.Validator(ctx, operatorAddr).GetBondedTokens()) @@ -94,7 +94,7 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign_TooOld() { Height: 0, Time: ctx.BlockTime(), Power: power, - ConsensusAddress: sdk.ConsAddress(val.Address()).String(), + ConsensusAddress: sdk.BytesToConsAddress(val.Address()).String(), } cp := suite.app.BaseApp.GetConsensusParams(ctx) @@ -105,5 +105,5 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign_TooOld() { suite.app.EvidenceKeeper.HandleEquivocationEvidence(ctx, evidence) suite.False(suite.app.StakingKeeper.Validator(ctx, operatorAddr).IsJailed()) - suite.False(suite.app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(val.Address()))) + suite.False(suite.app.SlashingKeeper.IsTombstoned(ctx, sdk.BytesToConsAddress(val.Address()))) } diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index aed555b3ed..36d6c86f49 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -29,9 +29,9 @@ var ( } valAddresses = []sdk.ValAddress{ - sdk.ValAddress(pubkeys[0].Address()), - sdk.ValAddress(pubkeys[1].Address()), - sdk.ValAddress(pubkeys[2].Address()), + sdk.BytesToValAddress(pubkeys[0].Address()), + sdk.BytesToValAddress(pubkeys[1].Address()), + sdk.BytesToValAddress(pubkeys[2].Address()), } initAmt = sdk.TokensFromConsensusPower(200) @@ -97,7 +97,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.app = app for i, addr := range valAddresses { - addr := sdk.AccAddress(addr) + addr := addr.ToAccAddress() app.AccountKeeper.SetAccount(suite.ctx, authtypes.NewBaseAccount(addr, pubkeys[i], 0)) } @@ -117,7 +117,7 @@ func (suite *KeeperTestSuite) populateEvidence(ctx sdk.Context, numEvidence int) Height: 11, Power: 100, Time: time.Now().UTC(), - ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).String(), + ConsensusAddress: sdk.BytesToConsAddress(pk.PubKey().Address()).String(), } suite.Nil(suite.app.EvidenceKeeper.SubmitEvidence(ctx, evidence[i])) @@ -133,7 +133,7 @@ func (suite *KeeperTestSuite) populateValidators(ctx sdk.Context) { suite.app.BankKeeper.SetSupply(ctx, banktypes.NewSupply(totalSupply)) for _, addr := range valAddresses { - err := suite.app.BankKeeper.AddCoins(ctx, sdk.AccAddress(addr), initCoins) + err := suite.app.BankKeeper.AddCoins(ctx, addr.ToAccAddress(), initCoins) suite.NoError(err) } } @@ -146,7 +146,7 @@ func (suite *KeeperTestSuite) TestSubmitValidEvidence() { Height: 1, Power: 100, Time: time.Now().UTC(), - ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).String(), + ConsensusAddress: sdk.BytesToConsAddress(pk.PubKey().Address()).String(), } suite.Nil(suite.app.EvidenceKeeper.SubmitEvidence(ctx, e)) @@ -164,7 +164,7 @@ func (suite *KeeperTestSuite) TestSubmitValidEvidence_Duplicate() { Height: 1, Power: 100, Time: time.Now().UTC(), - ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).String(), + ConsensusAddress: sdk.BytesToConsAddress(pk.PubKey().Address()).String(), } suite.Nil(suite.app.EvidenceKeeper.SubmitEvidence(ctx, e)) @@ -182,7 +182,7 @@ func (suite *KeeperTestSuite) TestSubmitInvalidEvidence() { Height: 0, Power: 100, Time: time.Now().UTC(), - ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).String(), + ConsensusAddress: sdk.BytesToConsAddress(pk.PubKey().Address()).String(), } suite.Error(suite.app.EvidenceKeeper.SubmitEvidence(ctx, e)) diff --git a/x/evidence/simulation/decoder_test.go b/x/evidence/simulation/decoder_test.go index 765e152fa2..b90c37ad29 100644 --- a/x/evidence/simulation/decoder_test.go +++ b/x/evidence/simulation/decoder_test.go @@ -25,7 +25,7 @@ func TestDecodeStore(t *testing.T) { Height: 10, Time: time.Now().UTC(), Power: 1000, - ConsensusAddress: sdk.ConsAddress(delPk1.Address()).String(), + ConsensusAddress: sdk.BytesToConsAddress(delPk1.Address()).String(), } evBz, err := app.EvidenceKeeper.MarshalEvidence(ev) diff --git a/x/evidence/types/evidence.go b/x/evidence/types/evidence.go index 384a6c6018..f08601d9dd 100644 --- a/x/evidence/types/evidence.go +++ b/x/evidence/types/evidence.go @@ -62,8 +62,7 @@ func (e *Equivocation) ValidateBasic() error { // GetConsensusAddress returns the validator's consensus address at time of the // Equivocation infraction. func (e Equivocation) GetConsensusAddress() sdk.ConsAddress { - addr, _ := sdk.ConsAddressFromBech32(e.ConsensusAddress) - return addr + return sdk.ConsAddress(e.ConsensusAddress) } // GetHeight returns the height at time of the Equivocation infraction. diff --git a/x/evidence/types/evidence_test.go b/x/evidence/types/evidence_test.go index 8ba6578a42..040501ddb6 100644 --- a/x/evidence/types/evidence_test.go +++ b/x/evidence/types/evidence_test.go @@ -13,7 +13,7 @@ import ( func TestEquivocation_Valid(t *testing.T) { n, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") - addr := sdk.ConsAddress("foo_________________") + addr := sdk.BytesToConsAddress([]byte("foo_________________")) e := types.Equivocation{ Height: 100, @@ -36,7 +36,7 @@ func TestEquivocation_Valid(t *testing.T) { func TestEquivocationValidateBasic(t *testing.T) { var zeroTime time.Time - addr := sdk.ConsAddress("foo_________________") + addr := sdk.BytesToConsAddress([]byte("foo_________________")) n, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") testCases := []struct { @@ -74,6 +74,7 @@ func TestEvidenceAddressConversion(t *testing.T) { evidence := types.FromABCIEvidence(tmEvidence).(*types.Equivocation) consAddr := evidence.GetConsensusAddress() // Check the address is the same after conversion - require.Equal(t, tmEvidence.Validator.Address, consAddr.Bytes()) + consAddrBytes, _ := sdk.ConsAddressToBytes(consAddr.String()) + require.Equal(t, tmEvidence.Validator.Address, consAddrBytes) sdk.GetConfig().SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) } diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index 7c5b41b240..58aa9c3281 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -47,6 +47,9 @@ func (m MsgSubmitEvidence) ValidateBasic() error { if m.Submitter == "" { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, m.Submitter) } + if err := sdk.ValidateAccAddress(m.Submitter); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid submitter address (%s)", err) + } evi := m.GetEvidence() if evi == nil { @@ -67,12 +70,7 @@ func (m MsgSubmitEvidence) GetSignBytes() []byte { // GetSigners returns the single expected signer for a MsgSubmitEvidence. func (m MsgSubmitEvidence) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(m.Submitter) - if err != nil { - return nil - } - - return []sdk.AccAddress{accAddr} + return []sdk.AccAddress{sdk.AccAddress(m.Submitter)} } func (m MsgSubmitEvidence) GetEvidence() exported.Evidence { @@ -84,11 +82,7 @@ func (m MsgSubmitEvidence) GetEvidence() exported.Evidence { } func (m MsgSubmitEvidence) GetSubmitter() sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(m.Submitter) - if err != nil { - return nil - } - return accAddr + return sdk.AccAddress(m.Submitter) } func (m MsgSubmitEvidence) UnpackInterfaces(ctx types.AnyUnpacker) error { diff --git a/x/evidence/types/msgs_test.go b/x/evidence/types/msgs_test.go index 119265a6d1..34fe7ee9ba 100644 --- a/x/evidence/types/msgs_test.go +++ b/x/evidence/types/msgs_test.go @@ -20,7 +20,7 @@ func testMsgSubmitEvidence(t *testing.T, e exported.Evidence, s sdk.AccAddress) func TestMsgSubmitEvidence(t *testing.T) { pk := ed25519.GenPrivKey() - submitter := sdk.AccAddress("test________________") + submitter := sdk.BytesToAccAddress([]byte("test________________")) testCases := []struct { msg sdk.Msg diff --git a/x/genutil/collect.go b/x/genutil/collect.go index 78f921d786..4a4f62c832 100644 --- a/x/genutil/collect.go +++ b/x/genutil/collect.go @@ -143,7 +143,7 @@ func CollectTxs(cdc codec.JSONMarshaler, txJSONDecoder sdk.TxDecoder, moniker, g // validate delegator and validator addresses and funds against the accounts in the state delAddr := msg.DelegatorAddress - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + valAddr, err := sdk.ValAddressToBytes(msg.ValidatorAddress) if err != nil { return appGenTxs, persistentPeers, err } @@ -158,11 +158,11 @@ func CollectTxs(cdc codec.JSONMarshaler, txJSONDecoder sdk.TxDecoder, moniker, g return appGenTxs, persistentPeers, fmt.Errorf("account %s balance not in genesis state: %+v", delAddr, balancesMap) } - _, valOk := balancesMap[sdk.AccAddress(valAddr).String()] + _, valOk := balancesMap[sdk.BytesToAccAddress(valAddr).String()] if !valOk { _, file, no, ok := runtime.Caller(1) if ok { - fmt.Printf("CollectTxs-2, called from %s#%d - %s\n", file, no, sdk.AccAddress(msg.ValidatorAddress).String()) + fmt.Printf("CollectTxs-2, called from %s#%d - %s\n", file, no, sdk.BytesToAccAddress(valAddr).String()) } return appGenTxs, persistentPeers, fmt.Errorf("account %s balance not in genesis state: %+v", valAddr, balancesMap) } diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index 05b2ac8322..8b63e75f50 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -25,8 +25,8 @@ var ( priv2 = secp256k1.GenPrivKey() pk1 = priv1.PubKey() pk2 = priv2.PubKey() - addr1 = sdk.AccAddress(pk1.Address()) - addr2 = sdk.AccAddress(pk2.Address()) + addr1 = sdk.BytesToAccAddress(pk1.Address()) + addr2 = sdk.BytesToAccAddress(pk2.Address()) desc = stakingtypes.NewDescription("testname", "", "", "", "") comm = stakingtypes.CommissionRates{} ) @@ -53,10 +53,10 @@ func (suite *GenTxTestSuite) SetupTest() { amount := sdk.NewInt64Coin(sdk.DefaultBondDenom, 50) one := sdk.OneInt() suite.msg1, err = stakingtypes.NewMsgCreateValidator( - sdk.ValAddress(pk1.Address()), pk1, amount, desc, comm, one) + sdk.BytesToValAddress(pk1.Address()), pk1, amount, desc, comm, one) suite.NoError(err) suite.msg2, err = stakingtypes.NewMsgCreateValidator( - sdk.ValAddress(pk2.Address()), pk1, amount, desc, comm, one) + sdk.BytesToValAddress(pk2.Address()), pk1, amount, desc, comm, one) suite.NoError(err) } diff --git a/x/genutil/types/genesis_state_test.go b/x/genutil/types/genesis_state_test.go index f93b058199..6983adf076 100644 --- a/x/genutil/types/genesis_state_test.go +++ b/x/genutil/types/genesis_state_test.go @@ -37,11 +37,11 @@ func TestValidateGenesisMultipleMessages(t *testing.T) { desc := stakingtypes.NewDescription("testname", "", "", "", "") comm := stakingtypes.CommissionRates{} - msg1, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk1.Address()), pk1, + msg1, err := stakingtypes.NewMsgCreateValidator(sdk.BytesToValAddress(pk1.Address()), pk1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, sdk.OneInt()) require.NoError(t, err) - msg2, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk2.Address()), pk2, + msg2, err := stakingtypes.NewMsgCreateValidator(sdk.BytesToValAddress(pk2.Address()), pk2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, sdk.OneInt()) require.NoError(t, err) @@ -59,7 +59,7 @@ func TestValidateGenesisMultipleMessages(t *testing.T) { func TestValidateGenesisBadMessage(t *testing.T) { desc := stakingtypes.NewDescription("testname", "", "", "", "") - msg1 := stakingtypes.NewMsgEditValidator(sdk.ValAddress(pk1.Address()), desc, nil, nil) + msg1 := stakingtypes.NewMsgEditValidator(sdk.BytesToValAddress(pk1.Address()), desc, nil, nil) txGen := simapp.MakeTestEncodingConfig().TxConfig txBuilder := txGen.NewTxBuilder() diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 0d99b38079..f866b0f1a7 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -283,7 +283,7 @@ func TestProposalPassedEndblocker(t *testing.T) { header := ostproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - valAddr := sdk.ValAddress(addrs[0]) + valAddr := addrs[0].ToValAddress() createValidators(t, stakingHandler, ctx, []sdk.ValAddress{valAddr}, []int64{10}) staking.EndBlocker(ctx, app.StakingKeeper) @@ -332,7 +332,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { header := ostproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - valAddr := sdk.ValAddress(addrs[0]) + valAddr := addrs[0].ToValAddress() createValidators(t, stakingHandler, ctx, []sdk.ValAddress{valAddr}, []int64{10}) staking.EndBlocker(ctx, app.StakingKeeper) diff --git a/x/gov/client/cli/cli_test.go b/x/gov/client/cli/cli_test.go index 75678cae04..bfe3bab22a 100644 --- a/x/gov/client/cli/cli_test.go +++ b/x/gov/client/cli/cli_test.go @@ -7,9 +7,8 @@ import ( "strings" "testing" - "github.com/line/lfb-sdk/testutil" - "github.com/gogo/protobuf/proto" + "github.com/line/lfb-sdk/testutil" "github.com/stretchr/testify/suite" ostcli "github.com/line/ostracon/libs/cli" diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 6bfbd613e4..d8a22fa5e7 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -115,20 +115,6 @@ $ %s query gov proposals --page=2 --limit=100 var proposalStatus types.ProposalStatus - if len(bechDepositorAddr) != 0 { - _, err := sdk.AccAddressFromBech32(bechDepositorAddr) - if err != nil { - return err - } - } - - if len(bechVoterAddr) != 0 { - _, err := sdk.AccAddressFromBech32(bechVoterAddr) - if err != nil { - return err - } - } - if len(strProposalStatus) != 0 { proposalStatus1, err := types.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) proposalStatus = proposalStatus1 @@ -216,10 +202,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } - voterAddr, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } + voterAddr := sdk.AccAddress(args[1]) res, err := queryClient.Vote( context.Background(), @@ -372,10 +355,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } - depositorAddr, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return err - } + depositorAddr := sdk.AccAddress(args[1]) res, err := queryClient.Deposit( context.Background(), diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go index bffe910b01..319b1aca49 100644 --- a/x/gov/client/rest/query.go +++ b/x/gov/client/rest/query.go @@ -180,11 +180,13 @@ func queryDepositHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) - if rest.CheckBadRequestError(w, err) { + if err := sdk.ValidateAccAddress(bechDepositorAddr); err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } + depositorAddr := sdk.AccAddress(bechDepositorAddr) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return @@ -256,12 +258,13 @@ func queryVoteHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) - if err != nil { + if err := sdk.ValidateAccAddress(bechVoterAddr); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } + voterAddr := sdk.AccAddress(bechVoterAddr) + clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return @@ -396,17 +399,11 @@ func queryProposalsWithParameterFn(clientCtx client.Context) http.HandlerFunc { ) if v := r.URL.Query().Get(RestVoter); len(v) != 0 { - voterAddr, err = sdk.AccAddressFromBech32(v) - if rest.CheckBadRequestError(w, err) { - return - } + voterAddr = sdk.AccAddress(v) } if v := r.URL.Query().Get(RestDepositor); len(v) != 0 { - depositorAddr, err = sdk.AccAddressFromBech32(v) - if rest.CheckBadRequestError(w, err) { - return - } + depositorAddr = sdk.AccAddress(v) } if v := r.URL.Query().Get(RestProposalStatus); len(v) != 0 { diff --git a/x/gov/client/rest/rest_test.go b/x/gov/client/rest/rest_test.go index 38c601c01c..acd1568b81 100644 --- a/x/gov/client/rest/rest_test.go +++ b/x/gov/client/rest/rest_test.go @@ -101,7 +101,6 @@ func (s *IntegrationTestSuite) TestLegacyGetVote() { if tc.expErr { var errResp rest.ErrorResponse s.Require().NoError(val.ClientCtx.LegacyAmino.UnmarshalJSON(respJSON, &errResp)) - s.Require().Equal(errResp.Error, tc.expErrMsg) } else { var resp = rest.ResponseWithHeight{} diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 283a8c2689..eba36f1374 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -130,7 +130,7 @@ func QueryVoteByTxQuery(clientCtx client.Context, params types.QueryVoteParams) events := []string{ fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgVote), fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), - fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, []byte(params.Voter.String())), + fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, params.Voter.String()), } // NOTE: SearchTxs is used to facilitate the txs query which does not currently diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index d2a99cbe1a..e586c7ad83 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -65,10 +65,12 @@ func TestGetPaginatedVotes(t *testing.T) { msgs [][]sdk.Msg votes []types.Vote } - acc1 := make(sdk.AccAddress, 20) - acc1[0] = 1 - acc2 := make(sdk.AccAddress, 20) - acc2[0] = 2 + acc1Bytes := make([]byte, 20) + acc1Bytes[0] = 1 + acc2Bytes := make([]byte, 20) + acc2Bytes[0] = 2 + acc1 := sdk.BytesToAccAddress(acc1Bytes) + acc2 := sdk.BytesToAccAddress(acc2Bytes) acc1Msgs := []sdk.Msg{ types.NewMsgVote(acc1, 0, types.OptionYes), types.NewMsgVote(acc1, 0, types.OptionYes), diff --git a/x/gov/common_test.go b/x/gov/common_test.go index 6c1ce83287..67b93c5758 100644 --- a/x/gov/common_test.go +++ b/x/gov/common_test.go @@ -33,7 +33,7 @@ func SortAddresses(addrs []sdk.AccAddress) { SortByteArrays(byteAddrs) for i, byteAddr := range byteAddrs { - addrs[i] = byteAddr + addrs[i] = sdk.AccAddress(string(byteAddr)) } } diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index 9d4ca78c57..e374003f44 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -25,10 +25,7 @@ func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAdd func (keeper Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryBare(&deposit) - depositor, err := sdk.AccAddressFromBech32(deposit.Depositor) - if err != nil { - panic(err) - } + depositor := sdk.AccAddress(deposit.Depositor) store.Set(types.DepositKey(deposit.ProposalId, depositor), bz) } @@ -63,10 +60,7 @@ func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID uint64) { panic(err) } - depositor, err := sdk.AccAddressFromBech32(deposit.Depositor) - if err != nil { - panic(err) - } + depositor := sdk.AccAddress(deposit.Depositor) store.Delete(types.DepositKey(proposalID, depositor)) return false }) @@ -168,12 +162,9 @@ func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) keeper.IterateDeposits(ctx, proposalID, func(deposit types.Deposit) bool { - depositor, err := sdk.AccAddressFromBech32(deposit.Depositor) - if err != nil { - panic(err) - } + depositor := sdk.AccAddress(deposit.Depositor) - err = keeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, depositor, deposit.Amount) + err := keeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, depositor, deposit.Amount) if err != nil { panic(err) } diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index ae72f329dc..49fd284ed8 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -57,20 +57,14 @@ func (q Keeper) Proposals(c context.Context, req *types.QueryProposalsRequest) ( // match voter address (if supplied) if len(req.Voter) > 0 { - voter, err := sdk.AccAddressFromBech32(req.Voter) - if err != nil { - return false, err - } + voter := sdk.AccAddress(req.Voter) _, matchVoter = q.GetVote(ctx, p.ProposalId, voter) } // match depositor (if supplied) if len(req.Depositor) > 0 { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return false, err - } + depositor := sdk.AccAddress(req.Depositor) _, matchDepositor = q.GetDeposit(ctx, p.ProposalId, depositor) } @@ -108,10 +102,7 @@ func (q Keeper) Vote(c context.Context, req *types.QueryVoteRequest) (*types.Que ctx := sdk.UnwrapSDKContext(c) - voter, err := sdk.AccAddressFromBech32(req.Voter) - if err != nil { - return nil, err - } + voter := sdk.AccAddress(req.Voter) vote, found := q.GetVote(ctx, req.ProposalId, voter) if !found { return nil, status.Errorf(codes.InvalidArgument, @@ -197,10 +188,7 @@ func (q Keeper) Deposit(c context.Context, req *types.QueryDepositRequest) (*typ ctx := sdk.UnwrapSDKContext(c) - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return nil, err - } + depositor := sdk.AccAddress(req.Depositor) deposit, found := q.GetDeposit(ctx, req.ProposalId, depositor) if !found { return nil, status.Errorf(codes.InvalidArgument, diff --git a/x/gov/keeper/grpc_query_test.go b/x/gov/keeper/grpc_query_test.go index 1c52c7d6dc..f7284a9943 100644 --- a/x/gov/keeper/grpc_query_test.go +++ b/x/gov/keeper/grpc_query_test.go @@ -398,12 +398,14 @@ func (suite *KeeperTestSuite) TestGRPCQueryVotes() { {proposal.ProposalId, addrs[0].String(), types.OptionAbstain}, {proposal.ProposalId, addrs[1].String(), types.OptionYes}, } - accAddr1, err1 := sdk.AccAddressFromBech32(votes[0].Voter) - accAddr2, err2 := sdk.AccAddressFromBech32(votes[1].Voter) + err1 := sdk.ValidateAccAddress(votes[0].Voter) + err2 := sdk.ValidateAccAddress(votes[1].Voter) suite.Require().NoError(err1) suite.Require().NoError(err2) - suite.Require().NoError(app.GovKeeper.AddVote(ctx, proposal.ProposalId, accAddr1, votes[0].Option)) - suite.Require().NoError(app.GovKeeper.AddVote(ctx, proposal.ProposalId, accAddr2, votes[1].Option)) + suite.Require().NoError(app.GovKeeper.AddVote(ctx, proposal.ProposalId, sdk.AccAddress(votes[0].Voter), + votes[0].Option)) + suite.Require().NoError(app.GovKeeper.AddVote(ctx, proposal.ProposalId, sdk.AccAddress(votes[1].Voter), + votes[1].Option)) req = &types.QueryVotesRequest{ ProposalId: proposal.ProposalId, diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index c8feafdd43..8d112a70ff 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -46,7 +46,7 @@ func NewKeeper( ) Keeper { // ensure governance module account is set - if addr := authKeeper.GetModuleAddress(types.ModuleName); addr == nil { + if addr := authKeeper.GetModuleAddress(types.ModuleName); addr.Empty() { panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) } diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 17a291b804..9d6028bc4a 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -61,10 +61,7 @@ func (k msgServer) SubmitProposal(goCtx context.Context, msg *types.MsgSubmitPro func (k msgServer) Vote(goCtx context.Context, msg *types.MsgVote) (*types.MsgVoteResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - accAddr, accErr := sdk.AccAddressFromBech32(msg.Voter) - if accErr != nil { - return nil, accErr - } + accAddr := sdk.AccAddress(msg.Voter) err := k.Keeper.AddVote(ctx, msg.ProposalId, accAddr, msg.Option) if err != nil { return nil, err @@ -91,10 +88,7 @@ func (k msgServer) Vote(goCtx context.Context, msg *types.MsgVote) (*types.MsgVo func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - accAddr, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } + accAddr := sdk.AccAddress(msg.Depositor) votingStarted, err := k.Keeper.AddDeposit(ctx, msg.ProposalId, accAddr, msg.Amount) if err != nil { return nil, err diff --git a/x/gov/keeper/proposal_test.go b/x/gov/keeper/proposal_test.go index 421129b50a..15642309cd 100644 --- a/x/gov/keeper/proposal_test.go +++ b/x/gov/keeper/proposal_test.go @@ -115,18 +115,18 @@ func TestGetProposalsFiltered(t *testing.T) { params types.QueryProposalsParams expectedNumResults int }{ - {types.NewQueryProposalsParams(1, 50, types.StatusNil, nil, nil), 50}, - {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, nil, nil), 50}, - {types.NewQueryProposalsParams(1, 50, types.StatusVotingPeriod, nil, nil), 50}, - {types.NewQueryProposalsParams(1, 25, types.StatusNil, nil, nil), 25}, - {types.NewQueryProposalsParams(2, 25, types.StatusNil, nil, nil), 25}, - {types.NewQueryProposalsParams(1, 50, types.StatusRejected, nil, nil), 0}, - {types.NewQueryProposalsParams(1, 50, types.StatusNil, addr1, nil), 50}, - {types.NewQueryProposalsParams(1, 50, types.StatusNil, nil, addr1), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusNil, "", ""), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, "", ""), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusVotingPeriod, "", ""), 50}, + {types.NewQueryProposalsParams(1, 25, types.StatusNil, "", ""), 25}, + {types.NewQueryProposalsParams(2, 25, types.StatusNil, "", ""), 25}, + {types.NewQueryProposalsParams(1, 50, types.StatusRejected, "", ""), 0}, + {types.NewQueryProposalsParams(1, 50, types.StatusNil, addr1, ""), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusNil, "", addr1), 50}, {types.NewQueryProposalsParams(1, 50, types.StatusNil, addr1, addr1), 50}, {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, addr1, addr1), 25}, - {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, nil, nil), 50}, - {types.NewQueryProposalsParams(1, 50, types.StatusVotingPeriod, nil, nil), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, "", ""), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusVotingPeriod, "", ""), 50}, } for i, tc := range testCases { diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 88c596f918..297eb58b81 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -163,9 +163,9 @@ func TestQueries(t *testing.T) { proposal1, err := app.GovKeeper.SubmitProposal(ctx, tp) require.NoError(t, err) deposit1 := types.NewDeposit(proposal1.ProposalId, TestAddrs[0], oneCoins) - depositer1, err := sdk.AccAddressFromBech32(deposit1.Depositor) + err = sdk.ValidateAccAddress(deposit1.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit1.ProposalId, depositer1, deposit1.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit1.ProposalId, sdk.AccAddress(deposit1.Depositor), deposit1.Amount) require.NoError(t, err) proposal1.TotalDeposit = proposal1.TotalDeposit.Add(deposit1.Amount...) @@ -173,9 +173,9 @@ func TestQueries(t *testing.T) { proposal2, err := app.GovKeeper.SubmitProposal(ctx, tp) require.NoError(t, err) deposit2 := types.NewDeposit(proposal2.ProposalId, TestAddrs[0], consCoins) - depositer2, err := sdk.AccAddressFromBech32(deposit2.Depositor) + err = sdk.ValidateAccAddress(deposit2.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit2.ProposalId, depositer2, deposit2.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit2.ProposalId, sdk.AccAddress(deposit2.Depositor), deposit2.Amount) require.NoError(t, err) proposal2.TotalDeposit = proposal2.TotalDeposit.Add(deposit2.Amount...) @@ -184,19 +184,19 @@ func TestQueries(t *testing.T) { proposal3, err := app.GovKeeper.SubmitProposal(ctx, tp) require.NoError(t, err) deposit3 := types.NewDeposit(proposal3.ProposalId, TestAddrs[1], oneCoins) - depositer3, err := sdk.AccAddressFromBech32(deposit3.Depositor) + err = sdk.ValidateAccAddress(deposit3.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit3.ProposalId, depositer3, deposit3.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit3.ProposalId, sdk.AccAddress(deposit3.Depositor), deposit3.Amount) require.NoError(t, err) proposal3.TotalDeposit = proposal3.TotalDeposit.Add(deposit3.Amount...) // TestAddrs[1] deposits on proposals #2 & #3 deposit4 := types.NewDeposit(proposal2.ProposalId, TestAddrs[1], depositParams.MinDeposit) - depositer4, err := sdk.AccAddressFromBech32(deposit4.Depositor) + err = sdk.ValidateAccAddress(deposit4.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit4.ProposalId, depositer4, deposit4.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit4.ProposalId, sdk.AccAddress(deposit4.Depositor), deposit4.Amount) require.NoError(t, err) proposal2.TotalDeposit = proposal2.TotalDeposit.Add(deposit4.Amount...) @@ -204,9 +204,9 @@ func TestQueries(t *testing.T) { proposal2.VotingEndTime = proposal2.VotingEndTime.Add(types.DefaultPeriod) deposit5 := types.NewDeposit(proposal3.ProposalId, TestAddrs[1], depositParams.MinDeposit) - depositer5, err := sdk.AccAddressFromBech32(deposit5.Depositor) + err = sdk.ValidateAccAddress(deposit5.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit5.ProposalId, depositer5, deposit5.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit5.ProposalId, sdk.AccAddress(deposit5.Depositor), deposit5.Amount) require.NoError(t, err) proposal3.TotalDeposit = proposal3.TotalDeposit.Add(deposit5.Amount...) @@ -240,12 +240,13 @@ func TestQueries(t *testing.T) { require.Equal(t, deposit5, deposit) // Only proposal #1 should be in types.Deposit Period - proposals := getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, types.StatusDepositPeriod, 1, 0) + proposals := getQueriedProposals(t, ctx, legacyQuerierCdc, querier, "", "", types.StatusDepositPeriod, 1, 0) + require.Len(t, proposals, 1) require.Equal(t, proposal1, proposals[0]) // Only proposals #2 and #3 should be in Voting Period - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, types.StatusVotingPeriod, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, "", "", types.StatusVotingPeriod, 1, 0) require.Len(t, proposals, 2) require.Equal(t, proposal2, proposals[0]) require.Equal(t, proposal3, proposals[1]) @@ -261,7 +262,7 @@ func TestQueries(t *testing.T) { app.GovKeeper.SetVote(ctx, vote3) // Test query voted by TestAddrs[0] - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, TestAddrs[0], types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, "", TestAddrs[0], types.StatusNil, 1, 0) require.Equal(t, proposal2, proposals[0]) require.Equal(t, proposal3, proposals[1]) @@ -280,21 +281,21 @@ func TestQueries(t *testing.T) { require.Equal(t, vote3, votes[1]) // Test query all proposals - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, "", "", types.StatusNil, 1, 0) require.Equal(t, proposal1, proposals[0]) require.Equal(t, proposal2, proposals[1]) require.Equal(t, proposal3, proposals[2]) // Test query voted by TestAddrs[1] - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, TestAddrs[1], types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, "", TestAddrs[1], types.StatusNil, 1, 0) require.Equal(t, proposal3.ProposalId, proposals[0].ProposalId) // Test query deposited by TestAddrs[0] - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[0], nil, types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[0], "", types.StatusNil, 1, 0) require.Equal(t, proposal1.ProposalId, proposals[0].ProposalId) // Test query deposited by addr2 - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[1], nil, types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[1], "", types.StatusNil, 1, 0) require.Equal(t, proposal2.ProposalId, proposals[0].ProposalId) require.Equal(t, proposal3.ProposalId, proposals[1].ProposalId) @@ -317,12 +318,12 @@ func TestPaginatedVotesQuery(t *testing.T) { votes := make([]types.Vote, 20) rand := rand.New(rand.NewSource(time.Now().UnixNano())) - addr := make(sdk.AccAddress, 20) + addrBytes := make([]byte, 20) for i := range votes { - rand.Read(addr) + rand.Read(addrBytes) vote := types.Vote{ ProposalId: proposal.ProposalId, - Voter: addr.String(), + Voter: sdk.BytesToAccAddress(addrBytes).String(), Option: types.OptionYes, } votes[i] = vote diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index c11603efdc..84557e2381 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -35,20 +35,21 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes boo keeper.IterateVotes(ctx, proposal.ProposalId, func(vote types.Vote) bool { // if validator, just record it in the map - voter, err := sdk.AccAddressFromBech32(vote.Voter) + voterBytes, err := sdk.AccAddressToBytes(vote.Voter) if err != nil { panic(err) } - valAddrStr := sdk.ValAddress(voter.Bytes()).String() + valAddrStr := sdk.BytesToValAddress(voterBytes).String() if val, ok := currValidators[valAddrStr]; ok { val.Vote = vote.Option currValidators[valAddrStr] = val } // iterate over all delegations from voter, deduct from any delegated-to validators - keeper.sk.IterateDelegations(ctx, voter, func(index int64, delegation stakingtypes.DelegationI) (stop bool) { + keeper.sk.IterateDelegations(ctx, sdk.AccAddress(vote.Voter), func(index int64, + delegation stakingtypes.DelegationI) (stop bool) { valAddrStr := delegation.GetValidatorAddr().String() if val, ok := currValidators[valAddrStr]; ok { @@ -67,7 +68,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes boo return false }) - keeper.deleteVote(ctx, vote.ProposalId, voter) + keeper.deleteVote(ctx, vote.ProposalId, sdk.AccAddress(vote.Voter)) return false }) diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index fa9424e56f..5622733c28 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -39,7 +39,7 @@ func TestTallyNoQuorum(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, ostproto.Header{}) - createValidators(t, ctx, app, []int64{2, 5, 0}) + createValidators(t, ctx, app, []int64{5, 2, 0}) // validators order was changed since using address string addrs := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.NewInt(10000000)) @@ -90,7 +90,7 @@ func TestTallyOnlyValidators51No(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, ostproto.Header{}) - valAccAddrs, _ := createValidators(t, ctx, app, []int64{5, 6, 0}) + valAccAddrs, _ := createValidators(t, ctx, app, []int64{6, 5, 0}) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp) @@ -99,8 +99,8 @@ func TestTallyOnlyValidators51No(t *testing.T) { proposal.Status = types.StatusVotingPeriod app.GovKeeper.SetProposal(ctx, proposal) - require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[0], types.OptionYes)) - require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.OptionNo)) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[0], types.OptionNo)) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.OptionYes)) proposal, ok := app.GovKeeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -114,7 +114,7 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, ostproto.Header{}) - valAccAddrs, _ := createValidators(t, ctx, app, []int64{5, 6, 0}) + valAccAddrs, _ := createValidators(t, ctx, app, []int64{6, 5, 0}) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp) @@ -123,8 +123,8 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { proposal.Status = types.StatusVotingPeriod app.GovKeeper.SetProposal(ctx, proposal) - require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[0], types.OptionNo)) - require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.OptionYes)) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[0], types.OptionYes)) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.OptionNo)) proposal, ok := app.GovKeeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -412,7 +412,7 @@ func TestTallyJailedValidator(t *testing.T) { consAddr, err := val2.GetConsAddr() require.NoError(t, err) - app.StakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr.Bytes())) + app.StakingKeeper.Jail(ctx, consAddr) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp) diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index cdc8dfcdef..96a2c41f4a 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -70,10 +70,7 @@ func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A func (keeper Keeper) SetVote(ctx sdk.Context, vote types.Vote) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryBare(&vote) - addr, err := sdk.AccAddressFromBech32(vote.Voter) - if err != nil { - panic(err) - } + addr := sdk.AccAddress(vote.Voter) store.Set(types.VoteKey(vote.ProposalId, addr), bz) } diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 4c53ec6542..2303ac99f3 100644 --- a/x/gov/simulation/decoder_test.go +++ b/x/gov/simulation/decoder_test.go @@ -18,7 +18,7 @@ import ( var ( delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) + delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) ) func TestDecodeStore(t *testing.T) { diff --git a/x/gov/types/keys.go b/x/gov/types/keys.go index da1f048c37..b30b5a8d79 100644 --- a/x/gov/types/keys.go +++ b/x/gov/types/keys.go @@ -154,10 +154,6 @@ func splitKeyWithTime(key []byte) (proposalID uint64, endTime time.Time) { } func splitKeyWithAddress(key []byte) (proposalID uint64, addr sdk.AccAddress) { - if len(key[1:]) != 8+sdk.AddrLen { - panic(fmt.Sprintf("unexpected key length (%d ≠ %d)", len(key), 8+sdk.AddrLen)) - } - proposalID = GetProposalIDFromBytes(key[1:9]) addr = sdk.AccAddress(key[9:]) return diff --git a/x/gov/types/keys_test.go b/x/gov/types/keys_test.go index 7f375dd89b..9805d6e466 100644 --- a/x/gov/types/keys_test.go +++ b/x/gov/types/keys_test.go @@ -10,7 +10,7 @@ import ( sdk "github.com/line/lfb-sdk/types" ) -var addr = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) +var addr = sdk.BytesToAccAddress(ed25519.GenPrivKey().PubKey().Address()) func TestProposalKeys(t *testing.T) { // key proposal @@ -50,7 +50,8 @@ func TestDepositKeys(t *testing.T) { // invalid key addr2 := sdk.AccAddress("test1") key = DepositKey(5, addr2) - require.Panics(t, func() { SplitKeyDeposit(key) }) + // SplitKeyDeposit does not check key length + require.NotPanics(t, func() { SplitKeyDeposit(key) }) } func TestVoteKeys(t *testing.T) { @@ -67,5 +68,6 @@ func TestVoteKeys(t *testing.T) { // invalid key addr2 := sdk.AccAddress("test1") key = VoteKey(5, addr2) - require.Panics(t, func() { SplitKeyVote(key) }) + // SplitKeyVote does not check key length + require.NotPanics(t, func() { SplitKeyVote(key) }) } diff --git a/x/gov/types/msgs.go b/x/gov/types/msgs.go index 16f82ac723..ec3fe232fb 100644 --- a/x/gov/types/msgs.go +++ b/x/gov/types/msgs.go @@ -41,8 +41,7 @@ func NewMsgSubmitProposal(content Content, initialDeposit sdk.Coins, proposer sd func (m *MsgSubmitProposal) GetInitialDeposit() sdk.Coins { return m.InitialDeposit } func (m *MsgSubmitProposal) GetProposer() sdk.AccAddress { - proposer, _ := sdk.AccAddressFromBech32(m.Proposer) - return proposer + return sdk.AccAddress(m.Proposer) } func (m *MsgSubmitProposal) GetContent() Content { @@ -91,6 +90,9 @@ func (m MsgSubmitProposal) ValidateBasic() error { if m.InitialDeposit.IsAnyNegative() { return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, m.InitialDeposit.String()) } + if err := sdk.ValidateAccAddress(m.Proposer); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid proposer address (%s)", err) + } content := m.GetContent() if content == nil { @@ -114,8 +116,7 @@ func (m MsgSubmitProposal) GetSignBytes() []byte { // GetSigners implements Msg func (m MsgSubmitProposal) GetSigners() []sdk.AccAddress { - proposer, _ := sdk.AccAddressFromBech32(m.Proposer) - return []sdk.AccAddress{proposer} + return []sdk.AccAddress{sdk.AccAddress(m.Proposer)} } // String implements the Stringer interface @@ -147,6 +148,9 @@ func (msg MsgDeposit) ValidateBasic() error { if msg.Depositor == "" { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Depositor) } + if err := sdk.ValidateAccAddress(msg.Depositor); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid depositor address (%s)", err) + } if !msg.Amount.IsValid() { return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String()) } @@ -171,8 +175,7 @@ func (msg MsgDeposit) GetSignBytes() []byte { // GetSigners implements Msg func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} + return []sdk.AccAddress{sdk.AccAddress(msg.Depositor)} } // NewMsgVote creates a message to cast a vote on an active proposal @@ -192,6 +195,12 @@ func (msg MsgVote) ValidateBasic() error { if msg.Voter == "" { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Voter) } + if err := sdk.ValidateAccAddress(msg.Voter); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid voter address (%s)", err) + } + if err := sdk.ValidateAccAddress(msg.Voter); err != nil { + return sdkerrors.Wrap(err, msg.Voter) + } if !ValidVoteOption(msg.Option) { return sdkerrors.Wrap(ErrInvalidVote, msg.Option.String()) } @@ -213,6 +222,5 @@ func (msg MsgVote) GetSignBytes() []byte { // GetSigners implements Msg func (msg MsgVote) GetSigners() []sdk.AccAddress { - voter, _ := sdk.AccAddressFromBech32(msg.Voter) - return []sdk.AccAddress{voter} + return []sdk.AccAddress{sdk.AccAddress(msg.Voter)} } diff --git a/x/gov/types/msgs_test.go b/x/gov/types/msgs_test.go index b27b4bc0ae..6c82d83c0c 100644 --- a/x/gov/types/msgs_test.go +++ b/x/gov/types/msgs_test.go @@ -14,8 +14,8 @@ var ( coinsZero = sdk.NewCoins() coinsMulti = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)) addrs = []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), + sdk.BytesToAccAddress([]byte(" test1")), + sdk.BytesToAccAddress([]byte(" test2")), } ) @@ -35,7 +35,7 @@ func TestMsgSubmitProposal(t *testing.T) { {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsPos, true}, {"", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsPos, false}, {"Test Proposal", "", ProposalTypeText, addrs[0], coinsPos, false}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, sdk.AccAddress{}, coinsPos, false}, + {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, "", coinsPos, false}, {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsZero, true}, {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsMulti, true}, {strings.Repeat("#", MaxTitleLength*2), "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsMulti, false}, @@ -60,7 +60,7 @@ func TestMsgSubmitProposal(t *testing.T) { } func TestMsgDepositGetSignBytes(t *testing.T) { - addr := sdk.AccAddress("addr1") + addr := sdk.BytesToAccAddress([]byte("addr1")) msg := NewMsgDeposit(addr, 0, coinsPos) res := msg.GetSignBytes() @@ -77,7 +77,7 @@ func TestMsgDeposit(t *testing.T) { expectPass bool }{ {0, addrs[0], coinsPos, true}, - {1, sdk.AccAddress{}, coinsPos, false}, + {1, "", coinsPos, false}, {1, addrs[0], coinsZero, true}, {1, addrs[0], coinsMulti, true}, } @@ -101,7 +101,7 @@ func TestMsgVote(t *testing.T) { expectPass bool }{ {0, addrs[0], OptionYes, true}, - {0, sdk.AccAddress{}, OptionYes, false}, + {0, "", OptionYes, false}, {0, addrs[0], OptionNo, true}, {0, addrs[0], OptionNoWithVeto, true}, {0, addrs[0], OptionAbstain, true}, @@ -120,7 +120,7 @@ func TestMsgVote(t *testing.T) { // this tests that Amino JSON MsgSubmitProposal.GetSignBytes() still works with Content as Any using the ModuleCdc func TestMsgSubmitProposal_GetSignBytes(t *testing.T) { - msg, err := NewMsgSubmitProposal(NewTextProposal("test", "abcd"), sdk.NewCoins(), sdk.AccAddress{}) + msg, err := NewMsgSubmitProposal(NewTextProposal("test", "abcd"), sdk.NewCoins(), "") require.NoError(t, err) var bz []byte require.NotPanics(t, func() { diff --git a/x/ibc/applications/transfer/keeper/keeper.go b/x/ibc/applications/transfer/keeper/keeper.go index d1d0d6d0c9..a1eee1a901 100644 --- a/x/ibc/applications/transfer/keeper/keeper.go +++ b/x/ibc/applications/transfer/keeper/keeper.go @@ -38,7 +38,7 @@ func NewKeeper( ) Keeper { // ensure ibc transfer module account is set - if addr := authKeeper.GetModuleAddress(types.ModuleName); addr == nil { + if addr := authKeeper.GetModuleAddress(types.ModuleName); addr.Empty() { panic("the IBC transfer module account has not been set") } diff --git a/x/ibc/applications/transfer/keeper/keeper_test.go b/x/ibc/applications/transfer/keeper/keeper_test.go index f1c7c12d9d..a3527f3a92 100644 --- a/x/ibc/applications/transfer/keeper/keeper_test.go +++ b/x/ibc/applications/transfer/keeper/keeper_test.go @@ -37,7 +37,7 @@ func (suite *KeeperTestSuite) SetupTest() { } func (suite *KeeperTestSuite) TestGetTransferAccount() { - expectedMaccAddr := sdk.AccAddress(crypto.AddressHash([]byte(types.ModuleName))) + expectedMaccAddr := sdk.BytesToAccAddress(crypto.AddressHash([]byte(types.ModuleName))) macc := suite.chainA.App.TransferKeeper.GetTransferAccount(suite.chainA.GetContext()) diff --git a/x/ibc/applications/transfer/keeper/mbt_relay_test.go b/x/ibc/applications/transfer/keeper/mbt_relay_test.go index 00bfca9208..0aa6cc15cb 100644 --- a/x/ibc/applications/transfer/keeper/mbt_relay_test.go +++ b/x/ibc/applications/transfer/keeper/mbt_relay_test.go @@ -91,7 +91,7 @@ type Balance struct { } func AddressFromString(address string) string { - return sdk.AccAddress(crypto.AddressHash([]byte(address))).String() + return sdk.BytesToAccAddress(crypto.AddressHash([]byte(address))).String() } func AddressFromTla(addr []string) string { @@ -265,12 +265,13 @@ func BankOfChain(chain *ibctesting.TestChain) Bank { // Set balances of the chain bank for balances present in the bank func (suite *KeeperTestSuite) SetChainBankBalances(chain *ibctesting.TestChain, bank *Bank) error { for coin, amount := range bank.balances { - address, err := sdk.AccAddressFromBech32(coin.Address) + err := sdk.ValidateAccAddress(coin.Address) if err != nil { return err } trace := types.ParseDenomTrace(coin.Denom) - err = chain.App.BankKeeper.SetBalance(chain.GetContext(), address, sdk.NewCoin(trace.IBCDenom(), amount)) + err = chain.App.BankKeeper.SetBalance(chain.GetContext(), sdk.AccAddress(coin.Address), + sdk.NewCoin(trace.IBCDenom(), amount)) if err != nil { return err } @@ -340,8 +341,7 @@ func (suite *KeeperTestSuite) TestModelBasedRelay() { } switch tc.handler { case "SendTransfer": - var sender sdk.AccAddress - sender, err = sdk.AccAddressFromBech32(tc.packet.Data.Sender) + err = sdk.ValidateAccAddress(tc.packet.Data.Sender) if err != nil { panic("MBT failed to convert sender address") } @@ -355,7 +355,7 @@ func (suite *KeeperTestSuite) TestModelBasedRelay() { tc.packet.SourcePort, tc.packet.SourceChannel, sdk.NewCoin(denom, sdk.NewIntFromUint64(tc.packet.Data.Amount)), - sender, + sdk.AccAddress(tc.packet.Data.Sender), tc.packet.Data.Receiver, clienttypes.NewHeight(0, 110), 0) diff --git a/x/ibc/applications/transfer/keeper/msg_server.go b/x/ibc/applications/transfer/keeper/msg_server.go index fd6f7432cc..86a2bc671f 100644 --- a/x/ibc/applications/transfer/keeper/msg_server.go +++ b/x/ibc/applications/transfer/keeper/msg_server.go @@ -15,12 +15,13 @@ var _ types.MsgServer = Keeper{} func (k Keeper) Transfer(goCtx context.Context, msg *types.MsgTransfer) (*types.MsgTransferResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - sender, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, err } if err := k.SendTransfer( - ctx, msg.SourcePort, msg.SourceChannel, msg.Token, sender, msg.Receiver, msg.TimeoutHeight, msg.TimeoutTimestamp, + ctx, msg.SourcePort, msg.SourceChannel, msg.Token, sdk.AccAddress(msg.Sender), + msg.Receiver, msg.TimeoutHeight, msg.TimeoutTimestamp, ); err != nil { return nil, err } diff --git a/x/ibc/applications/transfer/keeper/relay.go b/x/ibc/applications/transfer/keeper/relay.go index 7c7cb80717..1211b3f9af 100644 --- a/x/ibc/applications/transfer/keeper/relay.go +++ b/x/ibc/applications/transfer/keeper/relay.go @@ -194,7 +194,7 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t } // decode the receiver address - receiver, err := sdk.AccAddressFromBech32(data.Receiver) + err := sdk.ValidateAccAddress(data.Receiver) if err != nil { return err } @@ -232,7 +232,7 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t // unescrow tokens escrowAddress := types.GetEscrowAddress(packet.GetDestPort(), packet.GetDestChannel()) - if err := k.bankKeeper.SendCoins(ctx, escrowAddress, receiver, sdk.NewCoins(token)); err != nil { + if err := k.bankKeeper.SendCoins(ctx, escrowAddress, sdk.AccAddress(data.Receiver), sdk.NewCoins(token)); err != nil { // NOTE: this error is only expected to occur given an unexpected bug or a malicious // counterparty module. The bug may occur in bank or any part of the code that allows // the escrow address to be drained. A malicious counterparty module could drain the @@ -294,7 +294,7 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t // send to receiver if err := k.bankKeeper.SendCoinsFromModuleToAccount( - ctx, types.ModuleName, receiver, sdk.NewCoins(voucher), + ctx, types.ModuleName, sdk.AccAddress(data.Receiver), sdk.NewCoins(voucher), ); err != nil { panic(fmt.Sprintf("unable to send coins from module to account despite previously minting coins to module account: %v", err)) } @@ -352,7 +352,7 @@ func (k Keeper) refundPacketToken(ctx sdk.Context, packet channeltypes.Packet, d token := sdk.NewCoin(trace.IBCDenom(), sdk.NewIntFromUint64(data.Amount)) // decode the sender address - sender, err := sdk.AccAddressFromBech32(data.Sender) + err := sdk.ValidateAccAddress(data.Sender) if err != nil { return err } @@ -360,7 +360,7 @@ func (k Keeper) refundPacketToken(ctx sdk.Context, packet channeltypes.Packet, d if types.SenderChainIsSource(packet.GetSourcePort(), packet.GetSourceChannel(), data.Denom) { // unescrow tokens back to sender escrowAddress := types.GetEscrowAddress(packet.GetSourcePort(), packet.GetSourceChannel()) - if err := k.bankKeeper.SendCoins(ctx, escrowAddress, sender, sdk.NewCoins(token)); err != nil { + if err := k.bankKeeper.SendCoins(ctx, escrowAddress, sdk.AccAddress(data.Sender), sdk.NewCoins(token)); err != nil { // NOTE: this error is only expected to occur given an unexpected bug or a malicious // counterparty module. The bug may occur in bank or any part of the code that allows // the escrow address to be drained. A malicious counterparty module could drain the @@ -378,7 +378,7 @@ func (k Keeper) refundPacketToken(ctx sdk.Context, packet channeltypes.Packet, d return err } - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, sender, sdk.NewCoins(token)); err != nil { + if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, sdk.AccAddress(data.Sender), sdk.NewCoins(token)); err != nil { panic(fmt.Sprintf("unable to send coins from module to account despite previously minting coins to module account: %v", err)) } diff --git a/x/ibc/applications/transfer/types/keys.go b/x/ibc/applications/transfer/types/keys.go index fc010d7b89..1e068b43b3 100644 --- a/x/ibc/applications/transfer/types/keys.go +++ b/x/ibc/applications/transfer/types/keys.go @@ -51,5 +51,5 @@ func GetEscrowAddress(portID, channelID string) sdk.AccAddress { preImage = append(preImage, 0) preImage = append(preImage, contents...) hash := sha256.Sum256(preImage) - return hash[:20] + return sdk.BytesToAccAddress(hash[:20]) } diff --git a/x/ibc/applications/transfer/types/msgs.go b/x/ibc/applications/transfer/types/msgs.go index c7f391ca2c..6cd3829aa0 100644 --- a/x/ibc/applications/transfer/types/msgs.go +++ b/x/ibc/applications/transfer/types/msgs.go @@ -60,7 +60,7 @@ func (msg MsgTransfer) ValidateBasic() error { return sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, msg.Token.String()) } // NOTE: sender format must be validated as it is required by the GetSigners function. - _, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -77,9 +77,6 @@ func (msg MsgTransfer) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgTransfer) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } + valAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{valAddr} } diff --git a/x/ibc/applications/transfer/types/msgs_test.go b/x/ibc/applications/transfer/types/msgs_test.go index def04e6690..5b5f32541b 100644 --- a/x/ibc/applications/transfer/types/msgs_test.go +++ b/x/ibc/applications/transfer/types/msgs_test.go @@ -25,7 +25,7 @@ const ( ) var ( - addr1 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr1 = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) addr2 = sdk.AccAddress("testaddr2").String() emptyAddr sdk.AccAddress diff --git a/x/ibc/core/02-client/keeper/keeper_test.go b/x/ibc/core/02-client/keeper/keeper_test.go index c5e7bc5883..c1a507160d 100644 --- a/x/ibc/core/02-client/keeper/keeper_test.go +++ b/x/ibc/core/02-client/keeper/keeper_test.go @@ -104,7 +104,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.Require().NoError(err) pk, err := cryptocodec.FromTmPubKeyInterface(tmPk) suite.Require().NoError(err) - val, err := stakingtypes.NewValidator(sdk.ValAddress(pk.Address()), pk, stakingtypes.Description{}) + val, err := stakingtypes.NewValidator(sdk.BytesToValAddress(pk.Address()), pk, stakingtypes.Description{}) suite.Require().NoError(err) val.Status = stakingtypes.Bonded diff --git a/x/ibc/core/02-client/types/msgs.go b/x/ibc/core/02-client/types/msgs.go index f3a35ec8e9..1866f0debd 100644 --- a/x/ibc/core/02-client/types/msgs.go +++ b/x/ibc/core/02-client/types/msgs.go @@ -63,10 +63,6 @@ func (msg MsgCreateClient) Type() string { // ValidateBasic implements sdk.Msg func (msg MsgCreateClient) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) - } clientState, err := UnpackClientState(msg.ClientState) if err != nil { return err @@ -87,6 +83,9 @@ func (msg MsgCreateClient) ValidateBasic() error { if err := ValidateClientType(clientState.ClientType()); err != nil { return sdkerrors.Wrap(err, "client type does not meet naming constraints") } + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) + } return consensusState.ValidateBasic() } @@ -98,10 +97,7 @@ func (msg MsgCreateClient) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgCreateClient) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } @@ -144,10 +140,6 @@ func (msg MsgUpdateClient) Type() string { // ValidateBasic implements sdk.Msg func (msg MsgUpdateClient) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) - } header, err := UnpackHeader(msg.Header) if err != nil { return err @@ -158,6 +150,9 @@ func (msg MsgUpdateClient) ValidateBasic() error { if msg.ClientId == exported.Localhost { return sdkerrors.Wrap(ErrInvalidClient, "localhost client is only updated on ABCI BeginBlock") } + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) + } return host.ClientIdentifierValidator(msg.ClientId) } @@ -169,10 +164,7 @@ func (msg MsgUpdateClient) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgUpdateClient) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } @@ -240,8 +232,7 @@ func (msg MsgUpgradeClient) ValidateBasic() error { if len(msg.ProofUpgradeConsensusState) == 0 { return sdkerrors.Wrap(ErrInvalidUpgradeClient, "proof of upgrade consensus state cannot be empty") } - _, err = sdk.AccAddressFromBech32(msg.Signer) - if err != nil { + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return host.ClientIdentifierValidator(msg.ClientId) @@ -255,10 +246,7 @@ func (msg MsgUpgradeClient) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgUpgradeClient) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } @@ -299,10 +287,6 @@ func (msg MsgSubmitMisbehaviour) Type() string { // ValidateBasic performs basic (non-state-dependant) validation on a MsgSubmitMisbehaviour. func (msg MsgSubmitMisbehaviour) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) - } misbehaviour, err := UnpackMisbehaviour(msg.Misbehaviour) if err != nil { return err @@ -317,6 +301,9 @@ func (msg MsgSubmitMisbehaviour) ValidateBasic() error { misbehaviour.GetClientID(), msg.ClientId, ) } + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) + } return host.ClientIdentifierValidator(msg.ClientId) } @@ -329,10 +316,7 @@ func (msg MsgSubmitMisbehaviour) GetSignBytes() []byte { // GetSigners returns the single expected signer for a MsgSubmitMisbehaviour. func (msg MsgSubmitMisbehaviour) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } diff --git a/x/ibc/core/03-connection/types/msgs.go b/x/ibc/core/03-connection/types/msgs.go index c8dbcb9717..a0cbf5c93a 100644 --- a/x/ibc/core/03-connection/types/msgs.go +++ b/x/ibc/core/03-connection/types/msgs.go @@ -64,8 +64,7 @@ func (msg MsgConnectionOpenInit) ValidateBasic() error { return sdkerrors.Wrap(err, "basic validation of the provided version failed") } } - _, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return msg.Counterparty.ValidateBasic() @@ -79,10 +78,7 @@ func (msg MsgConnectionOpenInit) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenInit) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } @@ -172,8 +168,7 @@ func (msg MsgConnectionOpenTry) ValidateBasic() error { if msg.ConsensusHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "consensus height must be non-zero") } - _, err = sdk.AccAddressFromBech32(msg.Signer) - if err != nil { + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return msg.Counterparty.ValidateBasic() @@ -192,10 +187,7 @@ func (msg MsgConnectionOpenTry) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenTry) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } @@ -274,8 +266,7 @@ func (msg MsgConnectionOpenAck) ValidateBasic() error { if msg.ConsensusHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "consensus height must be non-zero") } - _, err = sdk.AccAddressFromBech32(msg.Signer) - if err != nil { + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return nil @@ -289,10 +280,7 @@ func (msg MsgConnectionOpenAck) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenAck) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } @@ -331,8 +319,7 @@ func (msg MsgConnectionOpenConfirm) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - _, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { + if err := sdk.ValidateAccAddress(msg.Signer); err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return nil @@ -346,9 +333,6 @@ func (msg MsgConnectionOpenConfirm) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenConfirm) GetSigners() []sdk.AccAddress { - accAddr, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + accAddr := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{accAddr} } diff --git a/x/ibc/core/03-connection/types/msgs_test.go b/x/ibc/core/03-connection/types/msgs_test.go index 96ab442167..ec86e25cfe 100644 --- a/x/ibc/core/03-connection/types/msgs_test.go +++ b/x/ibc/core/03-connection/types/msgs_test.go @@ -77,7 +77,7 @@ func TestMsgTestSuite(t *testing.T) { func (suite *MsgTestSuite) TestNewMsgConnectionOpenInit() { prefix := commitmenttypes.NewMerklePrefix([]byte("storePrefixKey")) - signer, _ := sdk.AccAddressFromBech32("link1kerpa33qxdwvrgms5qr7xegfxnewzm6s46ce7t") + signer := sdk.AccAddress("link1kerpa33qxdwvrgms5qr7xegfxnewzm6s46ce7t") // empty versions are considered valid, the default compatible versions // will be used in protocol. var version *types.Version @@ -92,7 +92,7 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenInit() { {"invalid counterparty connection ID", &types.MsgConnectionOpenInit{connectionID, types.NewCounterparty("clienttotest", "connectiontotest", prefix), version, 500, signer.String()}, false}, {"empty counterparty prefix", types.NewMsgConnectionOpenInit("clienttotest", "clienttotest", emptyPrefix, version, 500, signer), false}, {"supplied version fails basic validation", types.NewMsgConnectionOpenInit("clienttotest", "clienttotest", prefix, &types.Version{}, 500, signer), false}, - {"empty singer", types.NewMsgConnectionOpenInit("clienttotest", "clienttotest", prefix, version, 500, nil), false}, + {"empty singer", types.NewMsgConnectionOpenInit("clienttotest", "clienttotest", prefix, version, 500, ""), false}, {"success", types.NewMsgConnectionOpenInit("clienttotest", "clienttotest", prefix, version, 500, signer), true}, } @@ -108,7 +108,7 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenInit() { func (suite *MsgTestSuite) TestNewMsgConnectionOpenTry() { prefix := commitmenttypes.NewMerklePrefix([]byte("storePrefixKey")) - signer, _ := sdk.AccAddressFromBech32("link10czqumeld9k6dm32ud0xpqs0kn4m6xtrxy024r") + signer := sdk.AccAddress("link10czqumeld9k6dm32ud0xpqs0kn4m6xtrxy024r") clientState := ibctmtypes.NewClientState( chainID, ibctmtypes.DefaultTrustLevel, ibctesting.TrustingPeriod, ibctesting.UnbondingPeriod, ibctesting.MaxClockDrift, clientHeight, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath, false, false, @@ -146,7 +146,7 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenTry() { {"empty proofConsensus", types.NewMsgConnectionOpenTry(connectionID, "clienttotesta", "connectiontotest", "clienttotest", clientState, prefix, []*types.Version{ibctesting.ConnectionVersion}, 500, suite.proof, suite.proof, emptyProof, clientHeight, clientHeight, signer), false}, {"invalid proofHeight", types.NewMsgConnectionOpenTry(connectionID, "clienttotesta", "connectiontotest", "clienttotest", clientState, prefix, []*types.Version{ibctesting.ConnectionVersion}, 500, suite.proof, suite.proof, suite.proof, clienttypes.ZeroHeight(), clientHeight, signer), false}, {"invalid consensusHeight", types.NewMsgConnectionOpenTry(connectionID, "clienttotesta", "connectiontotest", "clienttotest", clientState, prefix, []*types.Version{ibctesting.ConnectionVersion}, 500, suite.proof, suite.proof, suite.proof, clientHeight, clienttypes.ZeroHeight(), signer), false}, - {"empty singer", types.NewMsgConnectionOpenTry(connectionID, "clienttotesta", "connectiontotest", "clienttotest", clientState, prefix, []*types.Version{ibctesting.ConnectionVersion}, 500, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, nil), false}, + {"empty singer", types.NewMsgConnectionOpenTry(connectionID, "clienttotesta", "connectiontotest", "clienttotest", clientState, prefix, []*types.Version{ibctesting.ConnectionVersion}, 500, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, ""), false}, {"success", types.NewMsgConnectionOpenTry(connectionID, "clienttotesta", "connectiontotest", "clienttotest", clientState, prefix, []*types.Version{ibctesting.ConnectionVersion}, 500, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, signer), true}, {"invalid version", types.NewMsgConnectionOpenTry(connectionID, "clienttotesta", "connectiontotest", "clienttotest", clientState, prefix, []*types.Version{{}}, 500, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, signer), false}, } @@ -162,7 +162,7 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenTry() { } func (suite *MsgTestSuite) TestNewMsgConnectionOpenAck() { - signer, _ := sdk.AccAddressFromBech32("link1amsfdt72u7ysc8542p0mmafq9ys8c7qxh74wf5") + signer := sdk.AccAddress("link1amsfdt72u7ysc8542p0mmafq9ys8c7qxh74wf5") clientState := ibctmtypes.NewClientState( chainID, ibctmtypes.DefaultTrustLevel, ibctesting.TrustingPeriod, ibctesting.UnbondingPeriod, ibctesting.MaxClockDrift, clientHeight, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath, false, false, ) @@ -195,7 +195,7 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenAck() { {"invalid proofHeight", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clienttypes.ZeroHeight(), clientHeight, ibctesting.ConnectionVersion, signer), false}, {"invalid consensusHeight", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clientHeight, clienttypes.ZeroHeight(), ibctesting.ConnectionVersion, signer), false}, {"invalid version", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, &types.Version{}, signer), false}, - {"empty signer", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, ibctesting.ConnectionVersion, nil), false}, + {"empty signer", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, ibctesting.ConnectionVersion, ""), false}, {"success", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, ibctesting.ConnectionVersion, signer), true}, } @@ -210,13 +210,13 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenAck() { } func (suite *MsgTestSuite) TestNewMsgConnectionOpenConfirm() { - signer, _ := sdk.AccAddressFromBech32("link1ptg03mk43x5qcp9xnankk7cwt4vzrkpxqpcff3") + signer := sdk.AccAddress("link1ptg03mk43x5qcp9xnankk7cwt4vzrkpxqpcff3") testMsgs := []*types.MsgConnectionOpenConfirm{ types.NewMsgConnectionOpenConfirm("test/conn1", suite.proof, clientHeight, signer), types.NewMsgConnectionOpenConfirm(connectionID, emptyProof, clientHeight, signer), types.NewMsgConnectionOpenConfirm(connectionID, suite.proof, clienttypes.ZeroHeight(), signer), - types.NewMsgConnectionOpenConfirm(connectionID, suite.proof, clientHeight, nil), + types.NewMsgConnectionOpenConfirm(connectionID, suite.proof, clientHeight, ""), types.NewMsgConnectionOpenConfirm(connectionID, suite.proof, clientHeight, signer), } diff --git a/x/ibc/core/04-channel/types/msgs.go b/x/ibc/core/04-channel/types/msgs.go index 1c42c12291..d90c45013c 100644 --- a/x/ibc/core/04-channel/types/msgs.go +++ b/x/ibc/core/04-channel/types/msgs.go @@ -52,7 +52,7 @@ func (msg MsgChannelOpenInit) ValidateBasic() error { if msg.Channel.Counterparty.ChannelId != "" { return sdkerrors.Wrap(ErrInvalidCounterparty, "counterparty channel identifier must be empty") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -67,10 +67,7 @@ func (msg MsgChannelOpenInit) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenInit) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -133,7 +130,7 @@ func (msg MsgChannelOpenTry) ValidateBasic() error { return sdkerrors.Wrap(err, "invalid counterparty channel ID") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -148,10 +145,7 @@ func (msg MsgChannelOpenTry) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenTry) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -201,7 +195,7 @@ func (msg MsgChannelOpenAck) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -216,10 +210,7 @@ func (msg MsgChannelOpenAck) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenAck) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -264,7 +255,7 @@ func (msg MsgChannelOpenConfirm) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -279,10 +270,7 @@ func (msg MsgChannelOpenConfirm) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenConfirm) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -318,7 +306,7 @@ func (msg MsgChannelCloseInit) ValidateBasic() error { if !IsValidChannelID(msg.ChannelId) { return ErrInvalidChannelIdentifier } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -333,10 +321,7 @@ func (msg MsgChannelCloseInit) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelCloseInit) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -381,7 +366,7 @@ func (msg MsgChannelCloseConfirm) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -396,10 +381,7 @@ func (msg MsgChannelCloseConfirm) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelCloseConfirm) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -432,7 +414,7 @@ func (msg MsgRecvPacket) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -454,10 +436,7 @@ func (msg MsgRecvPacket) GetDataSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgRecvPacket) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -499,7 +478,7 @@ func (msg MsgTimeout) ValidateBasic() error { if msg.NextSequenceRecv == 0 { return sdkerrors.Wrap(sdkerrors.ErrInvalidSequence, "next sequence receive cannot be 0") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -514,10 +493,7 @@ func (msg MsgTimeout) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgTimeout) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -562,7 +538,7 @@ func (msg MsgTimeoutOnClose) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -577,10 +553,7 @@ func (msg MsgTimeoutOnClose) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgTimeoutOnClose) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } @@ -624,7 +597,7 @@ func (msg MsgAcknowledgement) ValidateBasic() error { if len(msg.Acknowledgement) == 0 { return sdkerrors.Wrap(ErrInvalidAcknowledgement, "ack bytes cannot be empty") } - _, err := sdk.AccAddressFromBech32(msg.Signer) + err := sdk.ValidateAccAddress(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -639,10 +612,7 @@ func (msg MsgAcknowledgement) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgAcknowledgement) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(msg.Signer) - if err != nil { - panic(err) - } + signer := sdk.AccAddress(msg.Signer) return []sdk.AccAddress{signer} } diff --git a/x/ibc/core/04-channel/types/msgs_test.go b/x/ibc/core/04-channel/types/msgs_test.go index f1b5f3c4e7..a4cc557eb2 100644 --- a/x/ibc/core/04-channel/types/msgs_test.go +++ b/x/ibc/core/04-channel/types/msgs_test.go @@ -59,7 +59,7 @@ var ( invalidProofs1 = exported.Proof(nil) invalidProofs2 = emptyProof - addr = sdk.AccAddress("testaddr111111111111") + addr = sdk.BytesToAccAddress([]byte("testaddr111111111111")) emptyAddr sdk.AccAddress connHops = []string{"testconnection"} @@ -353,7 +353,7 @@ func (suite *TypesTestSuite) TestMsgRecvPacketGetSigners() { msg := types.NewMsgRecvPacket(packet, suite.proof, height, addr) res := msg.GetSigners() - expected := "[7465737461646472313131313131313131313131]" + expected := "[6C696E6B3177336A687861727076336A38797666337879636E7A7666337879636E7A7666336339777A7374]" suite.Equal(expected, fmt.Sprintf("%v", res)) } diff --git a/x/ibc/testing/chain.go b/x/ibc/testing/chain.go index 0c8bad3886..397f12a1f1 100644 --- a/x/ibc/testing/chain.go +++ b/x/ibc/testing/chain.go @@ -124,7 +124,8 @@ func NewTestChain(t *testing.T, chainID string) *TestChain { // generate genesis account senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0) + acc := authtypes.NewBaseAccount(sdk.BytesToAccAddress(senderPrivKey.PubKey().Address()), + senderPrivKey.PubKey(), 0) balance := banktypes.Balance{ Address: acc.GetAddress().String(), Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 71fd2c2824..bdd00d96b6 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -26,7 +26,7 @@ func NewKeeper( feeCollectorName string, ) Keeper { // ensure mint module account is set - if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { + if addr := ak.GetModuleAddress(types.ModuleName); addr.Empty() { panic("the mint module account has not been set") } diff --git a/x/params/types/common_test.go b/x/params/types/common_test.go index cb5991e100..b17b714bc7 100644 --- a/x/params/types/common_test.go +++ b/x/params/types/common_test.go @@ -14,7 +14,7 @@ var ( keyMaxValidators = []byte("MaxValidators") keyBondDenom = []byte("BondDenom") - key = sdk.NewKVStoreKey("storekey") + key = sdk.NewKVStoreKey("storekey") ) type params struct { diff --git a/x/slashing/abci_test.go b/x/slashing/abci_test.go index 2bc95a6ba8..c5f420814d 100644 --- a/x/slashing/abci_test.go +++ b/x/slashing/abci_test.go @@ -22,7 +22,7 @@ func TestBeginBlocker(t *testing.T) { pks := simapp.CreateTestPubKeys(1) simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200)) - addr, pk := sdk.ValAddress(pks[0].Address()), pks[0] + addr, pk := sdk.BytesToValAddress(pks[0].Address()), pks[0] tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) // bond the validator @@ -30,7 +30,7 @@ func TestBeginBlocker(t *testing.T) { amt := tstaking.CreateValidatorWithValPower(addr, pk, power, true) staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( - t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), + t, app.BankKeeper.GetAllBalances(ctx, addr.ToAccAddress()), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) @@ -52,7 +52,7 @@ func TestBeginBlocker(t *testing.T) { slashing.BeginBlocker(ctx, req, app.SlashingKeeper) - info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(pk.Address())) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(pk.Address())) require.True(t, found) require.Equal(t, ctx.BlockHeight(), info.StartHeight) require.Equal(t, int64(1), info.IndexOffset) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 5d89bdcdce..472435b476 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -20,15 +20,15 @@ import ( var ( priv1 = secp256k1.GenPrivKey() - addr1 = sdk.AccAddress(priv1.PubKey().Address()) + addr1 = sdk.BytesToAccAddress(priv1.PubKey().Address()) valKey = ed25519.GenPrivKey() - valAddr = sdk.AccAddress(valKey.PubKey().Address()) + valAddr = sdk.BytesToAccAddress(valKey.PubKey().Address()) ) func checkValidator(t *testing.T, app *simapp.SimApp, _ sdk.AccAddress, expFound bool) stakingtypes.Validator { ctxCheck := app.BaseApp.NewContext(true, ostproto.Header{}) - validator, found := app.StakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1)) + validator, found := app.StakingKeeper.GetValidator(ctxCheck, addr1.ToValAddress()) require.Equal(t, expFound, found) return validator } @@ -64,7 +64,7 @@ func TestSlashingMsgs(t *testing.T) { commission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) createValidatorMsg, err := stakingtypes.NewMsgCreateValidator( - sdk.ValAddress(addr1), valKey.PubKey(), bondCoin, description, commission, sdk.OneInt(), + addr1.ToValAddress(), valKey.PubKey(), bondCoin, description, commission, sdk.OneInt(), ) require.NoError(t, err) @@ -78,12 +78,12 @@ func TestSlashingMsgs(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: header}) validator := checkValidator(t, app, addr1, true) - require.Equal(t, sdk.ValAddress(addr1).String(), validator.OperatorAddress) + require.Equal(t, addr1.ToValAddress().String(), validator.OperatorAddress) require.Equal(t, stakingtypes.Bonded, validator.Status) require.True(sdk.IntEq(t, bondTokens, validator.BondedTokens())) - unjailMsg := &types.MsgUnjail{ValidatorAddr: sdk.ValAddress(addr1).String()} + unjailMsg := &types.MsgUnjail{ValidatorAddr: addr1.ToValAddress().String()} - checkValidatorSigningInfo(t, app, sdk.ConsAddress(valAddr), true) + checkValidatorSigningInfo(t, app, valAddr.ToConsAddress(), true) // unjail should fail with unknown validator header = ostproto.Header{Height: app.LastBlockHeight() + 1} diff --git a/x/slashing/client/cli/cli_test.go b/x/slashing/client/cli/cli_test.go index 3508e51509..05cd1316d1 100644 --- a/x/slashing/client/cli/cli_test.go +++ b/x/slashing/client/cli/cli_test.go @@ -68,7 +68,7 @@ func (s *IntegrationTestSuite) TestGetCmdQuerySigningInfo() { fmt.Sprintf("--%s=1", flags.FlagHeight), }, false, - fmt.Sprintf("{\"address\":\"%s\",\"start_height\":\"0\",\"index_offset\":\"0\",\"jailed_until\":\"1970-01-01T00:00:00Z\",\"tombstoned\":false,\"missed_blocks_counter\":\"0\"}", sdk.ConsAddress(val.PubKey.Address())), + fmt.Sprintf("{\"address\":\"%s\",\"start_height\":\"0\",\"index_offset\":\"0\",\"jailed_until\":\"1970-01-01T00:00:00Z\",\"tombstoned\":false,\"missed_blocks_counter\":\"0\"}", sdk.BytesToConsAddress(val.PubKey.Address())), }, { "valid address (text output)", @@ -83,7 +83,7 @@ index_offset: "0" jailed_until: "1970-01-01T00:00:00Z" missed_blocks_counter: "0" start_height: "0" -tombstoned: false`, sdk.ConsAddress(val.PubKey.Address())), +tombstoned: false`, sdk.BytesToConsAddress(val.PubKey.Address())), }, } diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index d48ffded9b..6dc84549ea 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -56,7 +56,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdgexx return err } - consAddr := sdk.ConsAddress(pk.Address()) + consAddr := sdk.BytesToConsAddress(pk.Address()) params := &types.QuerySigningInfoRequest{ConsAddress: consAddr.String()} res, err := queryClient.SigningInfo(context.Background(), params) if err != nil { diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index 3196370a65..e11d2d35c1 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -6,7 +6,6 @@ import ( "github.com/line/lfb-sdk/client" "github.com/line/lfb-sdk/client/flags" "github.com/line/lfb-sdk/client/tx" - sdk "github.com/line/lfb-sdk/types" "github.com/line/lfb-sdk/x/slashing/types" ) @@ -40,7 +39,7 @@ $ tx slashing unjail --from mykey } valAddr := clientCtx.GetFromAddress() - msg := types.NewMsgUnjail(sdk.ValAddress(valAddr)) + msg := types.NewMsgUnjail(valAddr.ToValAddress()) if err := msg.ValidateBasic(); err != nil { return err } diff --git a/x/slashing/client/rest/grpc_query_test.go b/x/slashing/client/rest/grpc_query_test.go index a3b494c81e..8c6ccd8582 100644 --- a/x/slashing/client/rest/grpc_query_test.go +++ b/x/slashing/client/rest/grpc_query_test.go @@ -45,7 +45,7 @@ func (s *IntegrationTestSuite) TestGRPCQueries() { val := s.network.Validators[0] baseURL := val.APIAddress - consAddr := sdk.ConsAddress(val.PubKey.Address()).String() + consAddr := sdk.BytesToConsAddress(val.PubKey.Address()).String() testCases := []struct { name string @@ -66,7 +66,7 @@ func (s *IntegrationTestSuite) TestGRPCQueries() { &types.QuerySigningInfosResponse{ Info: []types.ValidatorSigningInfo{ { - Address: sdk.ConsAddress(val.PubKey.Address()).String(), + Address: sdk.BytesToConsAddress(val.PubKey.Address()).String(), JailedUntil: time.Unix(0, 0), }, }, @@ -85,7 +85,7 @@ func (s *IntegrationTestSuite) TestGRPCQueries() { &types.QuerySigningInfoResponse{}, &types.QuerySigningInfoResponse{ ValSigningInfo: types.ValidatorSigningInfo{ - Address: sdk.ConsAddress(val.PubKey.Address()).String(), + Address: sdk.BytesToConsAddress(val.PubKey.Address()).String(), JailedUntil: time.Unix(0, 0), }, }, diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index 42e906d34a..752f3e3c3a 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -39,12 +39,12 @@ func NewUnjailRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + fromAddr, err := sdk.AccAddressToBytes(req.BaseReq.From) if rest.CheckBadRequestError(w, err) { return } - valAddr, err := sdk.ValAddressFromBech32(bech32Validator) + valAddr, err := sdk.ValAddressToBytes(bech32Validator) if rest.CheckInternalServerError(w, err) { return } @@ -54,7 +54,7 @@ func NewUnjailRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - msg := types.NewMsgUnjail(valAddr) + msg := types.NewMsgUnjail(sdk.ValAddress(bech32Validator)) if rest.CheckBadRequestError(w, msg.ValidateBasic()) { return } diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index 77f668dc61..7c1d0f10db 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -22,18 +22,12 @@ func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, stakingKeeper types.Stak ) for _, info := range data.SigningInfos { - address, err := sdk.ConsAddressFromBech32(info.Address) - if err != nil { - panic(err) - } + address := sdk.ConsAddress(info.Address) keeper.SetValidatorSigningInfo(ctx, address, info.ValidatorSigningInfo) } for _, array := range data.MissedBlocks { - address, err := sdk.ConsAddressFromBech32(array.Address) - if err != nil { - panic(err) - } + address := sdk.ConsAddress(array.Address) for _, missed := range array.MissedBlocks { keeper.SetValidatorMissedBlockBitArray(ctx, address, missed.Index, missed.Missed) } diff --git a/x/slashing/genesis_test.go b/x/slashing/genesis_test.go index f425a01cd6..737f6abbf4 100644 --- a/x/slashing/genesis_test.go +++ b/x/slashing/genesis_test.go @@ -21,14 +21,13 @@ func TestExportAndInitGenesis(t *testing.T) { app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.TokensFromConsensusPower(200)) - - info1 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), int64(4), int64(3), + info1 := types.NewValidatorSigningInfo(addrDels[0].ToConsAddress(), int64(4), int64(3), time.Now().UTC().Add(100000000000), false, int64(10)) - info2 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), int64(5), int64(4), + info2 := types.NewValidatorSigningInfo(addrDels[1].ToConsAddress(), int64(5), int64(4), time.Now().UTC().Add(10000000000), false, int64(10)) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), info1) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1]), info2) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), info1) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[1].ToConsAddress(), info2) genesisState := slashing.ExportGenesis(ctx, app.SlashingKeeper) require.Equal(t, genesisState.Params, testslashing.TestParams()) @@ -36,23 +35,23 @@ func TestExportAndInitGenesis(t *testing.T) { require.Equal(t, genesisState.SigningInfos[0].ValidatorSigningInfo, info1) // Tombstone validators after genesis shouldn't effect genesis state - app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[0])) - app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[1])) + app.SlashingKeeper.Tombstone(ctx, addrDels[0].ToConsAddress()) + app.SlashingKeeper.Tombstone(ctx, addrDels[1].ToConsAddress()) - ok := app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0])) + ok := app.SlashingKeeper.IsTombstoned(ctx, addrDels[0].ToConsAddress()) require.True(t, ok) - newInfo1, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + newInfo1, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) require.NotEqual(t, info1, newInfo1) // Initialise genesis with genesis state before tombstone slashing.InitGenesis(ctx, app.SlashingKeeper, app.StakingKeeper, genesisState) // Validator isTombstoned should return false as GenesisState is initialised - ok = app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0])) + ok = app.SlashingKeeper.IsTombstoned(ctx, addrDels[0].ToConsAddress()) require.False(t, ok) - newInfo1, ok = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) - newInfo2, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1])) + newInfo1, ok = app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) + newInfo2, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[1].ToConsAddress()) require.True(t, ok) require.Equal(t, info1, newInfo1) require.Equal(t, info2, newInfo2) diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index 5ef05c00da..7f7305c889 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -30,12 +30,12 @@ func TestCannotUnjailUnlessJailed(t *testing.T) { tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) slh := slashing.NewHandler(app.SlashingKeeper) - addr, val := sdk.ValAddress(pks[0].Address()), pks[0] + addr, val := sdk.BytesToValAddress(pks[0].Address()), pks[0] amt := tstaking.CreateValidatorWithValPower(addr, val, 100, true) staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( - t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), + t, app.BankKeeper.GetAllBalances(ctx, addr.ToAccAddress()), sdk.Coins{sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))}, ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) @@ -56,7 +56,7 @@ func TestCannotUnjailUnlessMeetMinSelfDelegation(t *testing.T) { tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) slh := slashing.NewHandler(app.SlashingKeeper) - addr, val := sdk.ValAddress(pks[0].Address()), pks[0] + addr, val := sdk.BytesToValAddress(pks[0].Address()), pks[0] amt := sdk.TokensFromConsensusPower(100) msg := tstaking.CreateValidatorMsg(addr, val, amt) msg.MinSelfDelegation = amt @@ -64,11 +64,11 @@ func TestCannotUnjailUnlessMeetMinSelfDelegation(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( - t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), + t, app.BankKeeper.GetAllBalances(ctx, addr.ToAccAddress()), sdk.Coins{sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))}, ) - tstaking.Undelegate(sdk.AccAddress(addr), addr, sdk.OneInt(), true) + tstaking.Undelegate(addr.ToAccAddress(), addr, sdk.OneInt(), true) require.True(t, app.StakingKeeper.Validator(ctx, addr).IsJailed()) // assert non-jailed validator can't be unjailed @@ -90,7 +90,7 @@ func TestJailedValidatorDelegations(t *testing.T) { tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) stakingParams := app.StakingKeeper.GetParams(ctx) app.StakingKeeper.SetParams(ctx, stakingParams) - valAddr, consAddr := sdk.ValAddress(pks[1].Address()), sdk.ConsAddress(pks[0].Address()) + valAddr, consAddr := sdk.BytesToValAddress(pks[1].Address()), sdk.BytesToConsAddress(pks[0].Address()) amt := tstaking.CreateValidatorWithValPower(valAddr, pks[1], 10, true) staking.EndBlocker(ctx, app.StakingKeeper) @@ -100,13 +100,13 @@ func TestJailedValidatorDelegations(t *testing.T) { app.SlashingKeeper.SetValidatorSigningInfo(ctx, consAddr, newInfo) // delegate tokens to the validator - delAddr := sdk.AccAddress(pks[2].Address()) + delAddr := sdk.BytesToAccAddress(pks[2].Address()) tstaking.Delegate(delAddr, valAddr, amt) // unbond validator total self-delegations (which should jail the validator) - valAcc := sdk.AccAddress(valAddr) + valAcc := valAddr.ToAccAddress() tstaking.Undelegate(valAcc, valAddr, amt, true) - _, err := app.StakingKeeper.CompleteUnbonding(ctx, sdk.AccAddress(valAddr), valAddr) + _, err := app.StakingKeeper.CompleteUnbonding(ctx, valAcc, valAddr) require.Nil(t, err, "expected complete unbonding validator to be ok, got: %v", err) // verify validator still exists and is jailed @@ -149,7 +149,7 @@ func TestHandleAbsentValidator(t *testing.T) { app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) power := int64(100) - addr, val := sdk.ValAddress(pks[0].Address()), pks[0] + addr, val := sdk.BytesToValAddress(pks[0].Address()), pks[0] slh := slashing.NewHandler(app.SlashingKeeper) tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) @@ -157,13 +157,13 @@ func TestHandleAbsentValidator(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( - t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), + t, app.BankKeeper.GetAllBalances(ctx, addr.ToAccAddress()), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) // will exist since the validator has been bonded - info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) require.Equal(t, int64(0), info.IndexOffset) @@ -176,7 +176,7 @@ func TestHandleAbsentValidator(t *testing.T) { ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, true) } - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) require.Equal(t, int64(0), info.MissedBlocksCounter) @@ -186,7 +186,7 @@ func TestHandleAbsentValidator(t *testing.T) { ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false) } - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) require.Equal(t, app.SlashingKeeper.SignedBlocksWindow(ctx)-app.SlashingKeeper.MinSignedPerWindow(ctx), info.MissedBlocksCounter) @@ -201,7 +201,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 501st block missed ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false) - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) // counter now reset to zero @@ -223,7 +223,7 @@ func TestHandleAbsentValidator(t *testing.T) { height++ ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false) - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) require.Equal(t, int64(1), info.MissedBlocksCounter) @@ -257,7 +257,7 @@ func TestHandleAbsentValidator(t *testing.T) { require.True(t, amt.Sub(slashAmt).Equal(app.BankKeeper.GetBalance(ctx, bondPool.GetAddress(), app.StakingKeeper.BondDenom(ctx)).Amount)) // Validator start height should not have been changed - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) // we've missed 2 blocks more than the maximum, so the counter was reset to 0 at 1 block more and is now 1 diff --git a/x/slashing/keeper/grpc_query.go b/x/slashing/keeper/grpc_query.go index b267c47409..5ba6b946ee 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -34,10 +34,7 @@ func (k Keeper) SigningInfo(c context.Context, req *types.QuerySigningInfoReques return nil, status.Errorf(codes.InvalidArgument, "invalid request") } - consAddr, err := sdk.ConsAddressFromBech32(req.ConsAddress) - if err != nil { - return nil, err - } + consAddr := sdk.ConsAddress(req.ConsAddress) ctx := sdk.UnwrapSDKContext(c) signingInfo, found := k.GetValidatorSigningInfo(ctx, consAddr) diff --git a/x/slashing/keeper/grpc_query_test.go b/x/slashing/keeper/grpc_query_test.go index 07eba38d35..b405ee4fcc 100644 --- a/x/slashing/keeper/grpc_query_test.go +++ b/x/slashing/keeper/grpc_query_test.go @@ -37,13 +37,13 @@ func (suite *SlashingTestSuite) SetupTest() { addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.TokensFromConsensusPower(200)) - info1 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), int64(4), int64(3), + info1 := types.NewValidatorSigningInfo(addrDels[0].ToConsAddress(), int64(4), int64(3), time.Unix(2, 0), false, int64(10)) - info2 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), int64(5), int64(4), + info2 := types.NewValidatorSigningInfo(addrDels[1].ToConsAddress(), int64(5), int64(4), time.Unix(2, 0), false, int64(10)) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), info1) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1]), info2) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), info1) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[1].ToConsAddress(), info2) suite.app = app suite.ctx = ctx @@ -70,7 +70,7 @@ func (suite *SlashingTestSuite) TestGRPCSigningInfo() { suite.Error(err) suite.Nil(infoResp) - consAddr := sdk.ConsAddress(suite.addrDels[0]) + consAddr := suite.addrDels[0].ToConsAddress() info, found := suite.app.SlashingKeeper.GetValidatorSigningInfo(suite.ctx, consAddr) suite.True(found) diff --git a/x/slashing/keeper/infractions.go b/x/slashing/keeper/infractions.go index 695c570b0a..c9f860a0a6 100644 --- a/x/slashing/keeper/infractions.go +++ b/x/slashing/keeper/infractions.go @@ -14,7 +14,7 @@ func (k Keeper) HandleValidatorSignature(ctx sdk.Context, addr cryptotypes.Addre height := ctx.BlockHeight() // fetch the validator public key - consAddr := sdk.ConsAddress(addr) + consAddr := sdk.BytesToConsAddress(addr) if _, err := k.GetPubkey(ctx, addr); err != nil { panic(fmt.Sprintf("Validator consensus-address %s not found", consAddr)) } diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper/keeper.go index 017f9969a7..76693c91f0 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -56,7 +56,7 @@ func (k Keeper) GetPubkey(ctx sdk.Context, a cryptotypes.Address) (cryptotypes.P store := ctx.KVStore(k.storeKey) bz := store.Get(types.AddrPubkeyRelationKey(a)) if bz == nil { - return nil, fmt.Errorf("address %s not found", sdk.ConsAddress(a)) + return nil, fmt.Errorf("address %s not found", sdk.BytesToConsAddress(a)) } var pk cryptotypes.PubKey return pk, k.cdc.UnmarshalInterface(bz, &pk) diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index d40b54ee7b..7ce7c6f508 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -51,7 +51,7 @@ func TestUnJailNotBonded(t *testing.T) { // unbond below minimum self-delegation require.Equal(t, p.BondDenom, tstaking.Denom) - tstaking.Undelegate(sdk.AccAddress(addr), addr, sdk.TokensFromConsensusPower(1), true) + tstaking.Undelegate(addr.ToAccAddress(), addr, sdk.TokensFromConsensusPower(1), true) staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) @@ -65,7 +65,7 @@ func TestUnJailNotBonded(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) // bond to meet minimum self-delegation - tstaking.DelegateWithPower(sdk.AccAddress(addr), addr, 1) + tstaking.DelegateWithPower(addr.ToAccAddress(), addr, 1) staking.EndBlocker(ctx, app.StakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) @@ -95,7 +95,7 @@ func TestHandleNewValidator(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( - t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), + t, app.BankKeeper.GetAllBalances(ctx, addr.ToAccAddress()), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) @@ -105,7 +105,7 @@ func TestHandleNewValidator(t *testing.T) { ctx = ctx.WithBlockHeight(app.SlashingKeeper.SignedBlocksWindow(ctx) + 2) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false) - info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) require.True(t, found) require.Equal(t, app.SlashingKeeper.SignedBlocksWindow(ctx)+1, info.StartHeight) require.Equal(t, int64(2), info.IndexOffset) @@ -191,9 +191,9 @@ func TestValidatorDippingInAndOut(t *testing.T) { simapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200)) addr, val := pks[0].Address(), pks[0] - consAddr := sdk.ConsAddress(addr) + consAddr := sdk.BytesToConsAddress(addr) tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) - valAddr := sdk.ValAddress(addr) + valAddr := sdk.BytesToValAddress(addr) tstaking.CreateValidatorWithValPower(valAddr, val, power, true) staking.EndBlocker(ctx, app.StakingKeeper) @@ -206,7 +206,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { } // kick first validator out of validator set - tstaking.CreateValidatorWithValPower(sdk.ValAddress(pks[1].Address()), pks[1], 101, true) + tstaking.CreateValidatorWithValPower(sdk.BytesToValAddress(pks[1].Address()), pks[1], 101, true) validatorUpdates := staking.EndBlocker(ctx, app.StakingKeeper) require.Equal(t, 2, len(validatorUpdates)) tstaking.CheckValidator(valAddr, stakingtypes.Unbonding, false) @@ -216,7 +216,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { ctx = ctx.WithBlockHeight(height) // validator added back in - tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), sdk.ValAddress(pks[0].Address()), 50) + tstaking.DelegateWithPower(sdk.BytesToAccAddress(pks[2].Address()), sdk.BytesToValAddress(pks[0].Address()), 50) validatorUpdates = staking.EndBlocker(ctx, app.StakingKeeper) require.Equal(t, 2, len(validatorUpdates)) diff --git a/x/slashing/keeper/msg_server.go b/x/slashing/keeper/msg_server.go index 36ed3c9e58..ca87ab0018 100644 --- a/x/slashing/keeper/msg_server.go +++ b/x/slashing/keeper/msg_server.go @@ -25,10 +25,7 @@ var _ types.MsgServer = msgServer{} func (k msgServer) Unjail(goCtx context.Context, msg *types.MsgUnjail) (*types.MsgUnjailResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddr) - if valErr != nil { - return nil, valErr - } + valAddr := sdk.ValAddress(msg.ValidatorAddr) err := k.Keeper.Unjail(ctx, valAddr) if err != nil { return nil, err diff --git a/x/slashing/keeper/signing_info_test.go b/x/slashing/keeper/signing_info_test.go index 1a0e311d8f..6b856b3d7e 100644 --- a/x/slashing/keeper/signing_info_test.go +++ b/x/slashing/keeper/signing_info_test.go @@ -17,18 +17,18 @@ func TestGetSetValidatorSigningInfo(t *testing.T) { ctx := app.BaseApp.NewContext(false, ostproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200)) - info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) require.False(t, found) newInfo := types.NewValidatorSigningInfo( - sdk.ConsAddress(addrDels[0]), + addrDels[0].ToConsAddress(), int64(4), int64(3), time.Unix(2, 0), false, int64(10), ) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), newInfo) - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), newInfo) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) require.True(t, found) require.Equal(t, info.StartHeight, int64(4)) require.Equal(t, info.IndexOffset, int64(3)) @@ -41,10 +41,10 @@ func TestGetSetValidatorMissedBlockBitArray(t *testing.T) { ctx := app.BaseApp.NewContext(false, ostproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200)) - missed := app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, sdk.ConsAddress(addrDels[0]), 0) + missed := app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, addrDels[0].ToConsAddress(), 0) require.False(t, missed) // treat empty key as not missed - app.SlashingKeeper.SetValidatorMissedBlockBitArray(ctx, sdk.ConsAddress(addrDels[0]), 0, true) - missed = app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, sdk.ConsAddress(addrDels[0]), 0) + app.SlashingKeeper.SetValidatorMissedBlockBitArray(ctx, addrDels[0].ToConsAddress(), 0, true) + missed = app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, addrDels[0].ToConsAddress(), 0) require.True(t, missed) // now should be missed } @@ -53,23 +53,23 @@ func TestTombstoned(t *testing.T) { ctx := app.BaseApp.NewContext(false, ostproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200)) - require.Panics(t, func() { app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[0])) }) - require.False(t, app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0]))) + require.Panics(t, func() { app.SlashingKeeper.Tombstone(ctx, addrDels[0].ToConsAddress()) }) + require.False(t, app.SlashingKeeper.IsTombstoned(ctx, addrDels[0].ToConsAddress())) newInfo := types.NewValidatorSigningInfo( - sdk.ConsAddress(addrDels[0]), + addrDels[0].ToConsAddress(), int64(4), int64(3), time.Unix(2, 0), false, int64(10), ) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), newInfo) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), newInfo) - require.False(t, app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0]))) - app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[0])) - require.True(t, app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0]))) - require.Panics(t, func() { app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[0])) }) + require.False(t, app.SlashingKeeper.IsTombstoned(ctx, addrDels[0].ToConsAddress())) + app.SlashingKeeper.Tombstone(ctx, addrDels[0].ToConsAddress()) + require.True(t, app.SlashingKeeper.IsTombstoned(ctx, addrDels[0].ToConsAddress())) + require.Panics(t, func() { app.SlashingKeeper.Tombstone(ctx, addrDels[0].ToConsAddress()) }) } func TestJailUntil(t *testing.T) { @@ -77,20 +77,20 @@ func TestJailUntil(t *testing.T) { ctx := app.BaseApp.NewContext(false, ostproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200)) - require.Panics(t, func() { app.SlashingKeeper.JailUntil(ctx, sdk.ConsAddress(addrDels[0]), time.Now()) }) + require.Panics(t, func() { app.SlashingKeeper.JailUntil(ctx, addrDels[0].ToConsAddress(), time.Now()) }) newInfo := types.NewValidatorSigningInfo( - sdk.ConsAddress(addrDels[0]), + addrDels[0].ToConsAddress(), int64(4), int64(3), time.Unix(2, 0), false, int64(10), ) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), newInfo) - app.SlashingKeeper.JailUntil(ctx, sdk.ConsAddress(addrDels[0]), time.Unix(253402300799, 0).UTC()) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), newInfo) + app.SlashingKeeper.JailUntil(ctx, addrDels[0].ToConsAddress(), time.Unix(253402300799, 0).UTC()) - info, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + info, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) require.True(t, ok) require.Equal(t, time.Unix(253402300799, 0).UTC(), info.JailedUntil) } diff --git a/x/slashing/keeper/unjail.go b/x/slashing/keeper/unjail.go index 14935e7d07..bce2611957 100644 --- a/x/slashing/keeper/unjail.go +++ b/x/slashing/keeper/unjail.go @@ -15,7 +15,7 @@ func (k Keeper) Unjail(ctx sdk.Context, validatorAddr sdk.ValAddress) error { } // cannot be unjailed if no self-delegation exists - selfDel := k.sk.Delegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + selfDel := k.sk.Delegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) if selfDel == nil { return types.ErrMissingSelfDelegation } diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 6bc83917e7..7437827fb2 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -19,9 +19,9 @@ import ( // nolint:deadcode,unused,varcheck var ( delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) + delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) + valAddr1 = sdk.BytesToValAddress(delPk1.Address()) + consAddr1 = sdk.BytesToConsAddress(delPk1.Address()) ) func TestDecodeStore(t *testing.T) { @@ -36,7 +36,7 @@ func TestDecodeStore(t *testing.T) { Pairs: []kv.Pair{ {Key: types.ValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshalBinaryBare(&info)}, {Key: types.ValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryBare(&missed)}, - {Key: types.AddrPubkeyRelationKey(delAddr1), Value: cdc.MustMarshalBinaryBare(&gogotypes.StringValue{Value: bechPK})}, + {Key: types.AddrPubkeyRelationKey(delAddr1.Bytes()), Value: cdc.MustMarshalBinaryBare(&gogotypes.StringValue{Value: bechPK})}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 53608f35c8..230d3db2a9 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -55,7 +55,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "validator is not ok"), nil, nil // skip } - simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, validator.GetOperator().ToAccAddress()) if !found { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "unable to find account"), nil, nil // skip } @@ -79,7 +79,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "self delegation is nil"), nil, nil // skip } - account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) + account := ak.GetAccount(ctx, validator.GetOperator().ToAccAddress()) spendable := bk.SpendableCoins(ctx, account.GetAddress()) fees, err := simtypes.RandomFees(r, ctx, spendable) @@ -129,7 +129,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee } if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to deliver tx"), nil, errors.New(res.Log) + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to deliver tx"), nil, err } return simtypes.NewOperationMsg(msg, true, ""), nil, nil diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index e77c2eb9d6..0a7db6a853 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -79,11 +79,11 @@ func TestSimulateMsgUnjail(t *testing.T) { // setup self delegation delTokens := sdk.TokensFromConsensusPower(2) validator0, issuedShares := validator0.AddTokensFromDel(delTokens) - val0AccAddress, err := sdk.ValAddressFromBech32(validator0.OperatorAddress) + val0AccAddress := sdk.ValAddress(validator0.OperatorAddress).ToAccAddress() require.NoError(t, err) - selfDelegation := stakingtypes.NewDelegation(val0AccAddress.Bytes(), validator0.GetOperator(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(val0AccAddress, validator0.GetOperator(), issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) - app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), val0AccAddress.Bytes(), distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) + app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), val0AccAddress, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) // begin a new block app.BeginBlock(abci.RequestBeginBlock{Header: ostproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}}) @@ -138,7 +138,7 @@ func getTestingValidator0(t *testing.T, app *simapp.SimApp, ctx sdk.Context, acc func getTestingValidator(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account, commission stakingtypes.Commission, n int) stakingtypes.Validator { account := accounts[n] valPubKey := account.ConsKey.PubKey() - valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(account.PubKey.Address()) validator, err := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes.Description{}) require.NoError(t, err) validator, err = validator.SetInitialCommission(commission) diff --git a/x/slashing/types/keys.go b/x/slashing/types/keys.go index 770d4f195d..09587d8555 100644 --- a/x/slashing/types/keys.go +++ b/x/slashing/types/keys.go @@ -42,9 +42,6 @@ func ValidatorSigningInfoKey(v sdk.ConsAddress) []byte { // ValidatorSigningInfoAddress - extract the address from a validator signing info key func ValidatorSigningInfoAddress(key []byte) (v sdk.ConsAddress) { addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } return sdk.ConsAddress(addr) } diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index 3189541816..13430e1f3d 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -2,6 +2,7 @@ package types import ( sdk "github.com/line/lfb-sdk/types" + "github.com/line/lfb-sdk/types/errors" ) // slashing message types @@ -23,11 +24,7 @@ func NewMsgUnjail(validatorAddr sdk.ValAddress) *MsgUnjail { func (msg MsgUnjail) Route() string { return RouterKey } func (msg MsgUnjail) Type() string { return TypeMsgUnjail } func (msg MsgUnjail) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) - if err != nil { - panic(err) - } - return []sdk.AccAddress{valAddr.Bytes()} + return []sdk.AccAddress{sdk.ValAddress(msg.ValidatorAddr).ToAccAddress()} } // GetSignBytes gets the bytes for the message signer to sign on @@ -41,6 +38,9 @@ func (msg MsgUnjail) ValidateBasic() error { if msg.ValidatorAddr == "" { return ErrBadValidatorAddr } + if err := sdk.ValidateValAddress(msg.ValidatorAddr); err != nil { + return errors.Wrapf(errors.ErrInvalidAddress, "Invalid validator address (%s)", err) + } return nil } diff --git a/x/slashing/types/msg_test.go b/x/slashing/types/msg_test.go index 778d2208b5..ef933b6c10 100644 --- a/x/slashing/types/msg_test.go +++ b/x/slashing/types/msg_test.go @@ -9,8 +9,8 @@ import ( ) func TestMsgUnjailGetSignBytes(t *testing.T) { - addr := sdk.AccAddress("abcd") - msg := NewMsgUnjail(sdk.ValAddress(addr)) + addr := sdk.BytesToValAddress([]byte("abcd")) + msg := NewMsgUnjail(addr) bytes := msg.GetSignBytes() require.Equal( t, diff --git a/x/staking/app_test.go b/x/staking/app_test.go index 2494929664..8fa55fc8e0 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -66,7 +66,7 @@ func TestStakingMsgs(t *testing.T) { // create validator description := types.NewDescription("foo_moniker", "", "", "", "") createValidatorMsg, err := types.NewMsgCreateValidator( - sdk.ValAddress(addr1), valKey.PubKey(), bondCoin, description, commissionRates, sdk.OneInt(), + addr1.ToValAddress(), valKey.PubKey(), bondCoin, description, commissionRates, sdk.OneInt(), ) require.NoError(t, err) @@ -79,8 +79,8 @@ func TestStakingMsgs(t *testing.T) { header = ostproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - validator := checkValidator(t, app, sdk.ValAddress(addr1), true) - require.Equal(t, sdk.ValAddress(addr1).String(), validator.OperatorAddress) + validator := checkValidator(t, app, addr1.ToValAddress(), true) + require.Equal(t, addr1.ToValAddress().String(), validator.OperatorAddress) require.Equal(t, types.Bonded, validator.Status) require.True(sdk.IntEq(t, bondTokens, validator.BondedTokens())) @@ -89,34 +89,34 @@ func TestStakingMsgs(t *testing.T) { // edit the validator description = types.NewDescription("bar_moniker", "", "", "", "") - editValidatorMsg := types.NewMsgEditValidator(sdk.ValAddress(addr1), description, nil, nil) + editValidatorMsg := types.NewMsgEditValidator(addr1.ToValAddress(), description, nil, nil) header = ostproto.Header{Height: app.LastBlockHeight() + 1} _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{editValidatorMsg}, "", []uint64{0}, []uint64{1}, true, true, priv1) require.NoError(t, err) - validator = checkValidator(t, app, sdk.ValAddress(addr1), true) + validator = checkValidator(t, app, addr1.ToValAddress(), true) require.Equal(t, description, validator.Description) // delegate simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin}) - delegateMsg := types.NewMsgDelegate(addr2, sdk.ValAddress(addr1), bondCoin) + delegateMsg := types.NewMsgDelegate(addr2, addr1.ToValAddress(), bondCoin) header = ostproto.Header{Height: app.LastBlockHeight() + 1} _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{delegateMsg}, "", []uint64{1}, []uint64{0}, true, true, priv2) require.NoError(t, err) simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin.Sub(bondCoin)}) - checkDelegation(t, app, addr2, sdk.ValAddress(addr1), true, bondTokens.ToDec()) + checkDelegation(t, app, addr2, addr1.ToValAddress(), true, bondTokens.ToDec()) // begin unbonding - beginUnbondingMsg := types.NewMsgUndelegate(addr2, sdk.ValAddress(addr1), bondCoin) + beginUnbondingMsg := types.NewMsgUndelegate(addr2, addr1.ToValAddress(), bondCoin) header = ostproto.Header{Height: app.LastBlockHeight() + 1} _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, "", []uint64{1}, []uint64{1}, true, true, priv2) require.NoError(t, err) // delegation should exist anymore - checkDelegation(t, app, addr2, sdk.ValAddress(addr1), false, sdk.Dec{}) + checkDelegation(t, app, addr2, addr1.ToValAddress(), false, sdk.Dec{}) // balance should be the same because bonding not yet complete simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin.Sub(bondCoin)}) diff --git a/x/staking/client/cli/cli_test.go b/x/staking/client/cli/cli_test.go index dc727be4df..0103e0d323 100644 --- a/x/staking/client/cli/cli_test.go +++ b/x/staking/client/cli/cli_test.go @@ -85,7 +85,7 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewValidator", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) s.Require().NoError(err) - newAddr := sdk.AccAddress(info.GetPubKey().Address()) + newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) _, err = banktestutil.MsgSendExec( val.ClientCtx, @@ -1040,7 +1040,7 @@ func (s *IntegrationTestSuite) TestNewCmdDelegate() { info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewAccount", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) s.Require().NoError(err) - newAddr := sdk.AccAddress(info.GetPubKey().Address()) + newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) _, err = banktestutil.MsgSendExec( val.ClientCtx, @@ -1279,7 +1279,7 @@ func (s *IntegrationTestSuite) TestBlockResults() { // Create new account in the keyring. info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewDelegator", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) require.NoError(err) - newAddr := sdk.AccAddress(info.GetPubKey().Address()) + newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) // Send some funds to the new account. _, err = banktestutil.MsgSendExec( diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index b29df23d2c..45668dda1d 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -69,10 +69,10 @@ $ %s query staking validator %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - addr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateValAddress(args[0]); err != nil { return err } + addr := sdk.ValAddress(args[0]) params := &types.QueryValidatorRequest{ValidatorAddr: addr.String()} res, err := queryClient.Validator(cmd.Context(), params) @@ -157,10 +157,10 @@ $ %s query staking unbonding-delegations-from %s1gghjut3ccd8ay0zduzj64hwre2fxs9l } queryClient := types.NewQueryClient(clientCtx) - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateValAddress(args[0]); err != nil { return err } + valAddr := sdk.ValAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -212,10 +212,10 @@ $ %s query staking redelegations-from %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - valSrcAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateValAddress(args[0]); err != nil { return err } + valSrcAddr := sdk.ValAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -267,15 +267,15 @@ $ %s query staking delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1gghju } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateAccAddress(args[0]); err != nil { return err } + delAddr := sdk.AccAddress(args[0]) - valAddr, err := sdk.ValAddressFromBech32(args[1]) - if err != nil { + if err := sdk.ValidateValAddress(args[1]); err != nil { return err } + valAddr := sdk.ValAddress(args[1]) params := &types.QueryDelegationRequest{ DelegatorAddr: delAddr.String(), @@ -321,10 +321,10 @@ $ %s query staking delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateAccAddress(args[0]); err != nil { return err } + delAddr := sdk.AccAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -376,10 +376,10 @@ $ %s query staking delegations-to %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateValAddress(args[0]); err != nil { return err } + valAddr := sdk.ValAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -432,15 +432,15 @@ $ %s query staking unbonding-delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9 } queryClient := types.NewQueryClient(clientCtx) - valAddr, err := sdk.ValAddressFromBech32(args[1]) - if err != nil { + if err := sdk.ValidateAccAddress(args[0]); err != nil { return err } + delAddr := sdk.AccAddress(args[0]) - delAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateValAddress(args[1]); err != nil { return err } + valAddr := sdk.ValAddress(args[1]) params := &types.QueryUnbondingDelegationRequest{ DelegatorAddr: delAddr.String(), @@ -486,10 +486,10 @@ $ %s query staking unbonding-delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru } queryClient := types.NewQueryClient(clientCtx) - delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateAccAddress(args[0]); err != nil { return err } + delegatorAddr := sdk.AccAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -542,20 +542,20 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1l2r } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateAccAddress(args[0]); err != nil { return err } + delAddr := sdk.AccAddress(args[0]) - valSrcAddr, err := sdk.ValAddressFromBech32(args[1]) - if err != nil { + if err := sdk.ValidateValAddress(args[1]); err != nil { return err } + valSrcAddr := sdk.ValAddress(args[1]) - valDstAddr, err := sdk.ValAddressFromBech32(args[2]) - if err != nil { + if err := sdk.ValidateValAddress(args[2]); err != nil { return err } + valDstAddr := sdk.ValAddress(args[2]) params := &types.QueryRedelegationsRequest{ DelegatorAddr: delAddr.String(), @@ -602,10 +602,10 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } queryClient := types.NewQueryClient(clientCtx) - delAddr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { + if err := sdk.ValidateAccAddress(args[0]); err != nil { return err } + delAddr := sdk.AccAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 2cfa56a6a3..22b035c604 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -127,7 +127,7 @@ func NewEditValidatorCmd() *cobra.Command { newMinSelfDelegation = &msb } - msg := types.NewMsgEditValidator(sdk.ValAddress(valAddr), description, newRate, newMinSelfDelegation) + msg := types.NewMsgEditValidator(valAddr.ToValAddress(), description, newRate, newMinSelfDelegation) if err := msg.ValidateBasic(); err != nil { return err } @@ -171,10 +171,7 @@ $ %s tx staking delegate %s1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --f } delAddr := clientCtx.GetFromAddress() - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } + valAddr := sdk.ValAddress(args[0]) msg := types.NewMsgDelegate(delAddr, valAddr, amount) if err := msg.ValidateBasic(); err != nil { @@ -212,15 +209,9 @@ $ %s tx staking redelegate %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj %s1l2rsakp3 return err } delAddr := clientCtx.GetFromAddress() - valSrcAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } + valSrcAddr := sdk.ValAddress(args[0]) - valDstAddr, err := sdk.ValAddressFromBech32(args[1]) - if err != nil { - return err - } + valDstAddr := sdk.ValAddress(args[1]) amount, err := sdk.ParseCoinNormalized(args[2]) if err != nil { @@ -263,10 +254,7 @@ $ %s tx staking unbond %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from return err } delAddr := clientCtx.GetFromAddress() - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return err - } + valAddr := sdk.ValAddress(args[0]) amount, err := sdk.ParseCoinNormalized(args[1]) if err != nil { @@ -334,7 +322,7 @@ func NewBuildCreateValidatorMsg(clientCtx client.Context, txf tx.Factory, fs *fl } msg, err := types.NewMsgCreateValidator( - sdk.ValAddress(valAddr), pk, amount, description, commissionRates, minSelfDelegation, + valAddr.ToValAddress(), pk, amount, description, commissionRates, minSelfDelegation, ) if err != nil { return txf, nil, err @@ -544,7 +532,7 @@ func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorC } msg, err := types.NewMsgCreateValidator( - sdk.ValAddress(valAddr), pk, amount, description, commissionRates, minSelfDelegation, + valAddr.ToValAddress(), pk, amount, description, commissionRates, minSelfDelegation, ) if err != nil { return txBldr, msg, err diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 42a7504e64..0d4841661a 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -124,8 +124,8 @@ func delegatorTxsHandlerFn(clientCtx client.Context) http.HandlerFunc { vars := mux.Vars(r) delegatorAddr := vars["delegatorAddr"] - - if _, err := sdk.AccAddressFromBech32(delegatorAddr); rest.CheckBadRequestError(w, err) { + err := sdk.ValidateAccAddress(delegatorAddr) + if rest.CheckBadRequestError(w, err) { return } @@ -209,29 +209,35 @@ func redelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { bechDstValidatorAddr := r.URL.Query().Get("validator_to") if len(bechDelegatorAddr) != 0 { - delegatorAddr, err := sdk.AccAddressFromBech32(bechDelegatorAddr) + err := sdk.ValidateAccAddress(bechDelegatorAddr) if rest.CheckBadRequestError(w, err) { return } + delegatorAddr := sdk.AccAddress(bechDelegatorAddr) + params.DelegatorAddr = delegatorAddr } if len(bechSrcValidatorAddr) != 0 { - srcValidatorAddr, err := sdk.ValAddressFromBech32(bechSrcValidatorAddr) + err := sdk.ValidateValAddress(bechSrcValidatorAddr) if rest.CheckBadRequestError(w, err) { return } + srcValidatorAddr := sdk.ValAddress(bechSrcValidatorAddr) + params.SrcValidatorAddr = srcValidatorAddr } if len(bechDstValidatorAddr) != 0 { - dstValidatorAddr, err := sdk.ValAddressFromBech32(bechDstValidatorAddr) + err := sdk.ValidateValAddress(bechDstValidatorAddr) if rest.CheckBadRequestError(w, err) { return } + dstValidatorAddr := sdk.ValAddress(bechDstValidatorAddr) + params.DstValidatorAddr = dstValidatorAddr } diff --git a/x/staking/client/rest/tx.go b/x/staking/client/rest/tx.go index 5bbec5c089..b6f7ccaf26 100644 --- a/x/staking/client/rest/tx.go +++ b/x/staking/client/rest/tx.go @@ -1,7 +1,6 @@ package rest import ( - "bytes" "net/http" "github.com/gorilla/mux" @@ -72,12 +71,9 @@ func newPostDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if rest.CheckBadRequestError(w, err) { - return - } + fromAddr := sdk.AccAddress(req.BaseReq.From) - if !bytes.Equal(fromAddr, req.DelegatorAddress) { + if !fromAddr.Equals(req.DelegatorAddress) { rest.WriteErrorResponse(w, http.StatusUnauthorized, "must use own delegator address") return } @@ -103,12 +99,9 @@ func newPostRedelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if rest.CheckBadRequestError(w, err) { - return - } + fromAddr := sdk.AccAddress(req.BaseReq.From) - if !bytes.Equal(fromAddr, req.DelegatorAddress) { + if !fromAddr.Equals(req.DelegatorAddress) { rest.WriteErrorResponse(w, http.StatusUnauthorized, "must use own delegator address") return } @@ -134,12 +127,9 @@ func newPostUnbondingDelegationsHandlerFn(clientCtx client.Context) http.Handler return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if rest.CheckBadRequestError(w, err) { - return - } + fromAddr := sdk.AccAddress(req.BaseReq.From) - if !bytes.Equal(fromAddr, req.DelegatorAddress) { + if !fromAddr.Equals(req.DelegatorAddress) { rest.WriteErrorResponse(w, http.StatusUnauthorized, "must use own delegator address") return } diff --git a/x/staking/client/rest/utils.go b/x/staking/client/rest/utils.go index 1d008c1749..b4034df3a4 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -42,15 +42,17 @@ func queryBonds(clientCtx client.Context, endpoint string) http.HandlerFunc { bech32delegator := vars["delegatorAddr"] bech32validator := vars["validatorAddr"] - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + err := sdk.ValidateAccAddress(bech32delegator) if rest.CheckBadRequestError(w, err) { return } + delegatorAddr := sdk.AccAddress(bech32delegator) - validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) + err = sdk.ValidateValAddress(bech32validator) if rest.CheckBadRequestError(w, err) { return } + validatorAddr := sdk.ValAddress(bech32validator) clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { @@ -79,10 +81,11 @@ func queryDelegator(clientCtx client.Context, endpoint string) http.HandlerFunc vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + err := sdk.ValidateAccAddress(bech32delegator) if rest.CheckBadRequestError(w, err) { return } + delegatorAddr := sdk.AccAddress(bech32delegator) clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { @@ -116,10 +119,11 @@ func queryValidator(clientCtx client.Context, endpoint string) http.HandlerFunc return } - validatorAddr, err := sdk.ValAddressFromBech32(bech32validatorAddr) + err = sdk.ValidateValAddress(bech32validatorAddr) if rest.CheckBadRequestError(w, err) { return } + validatorAddr := sdk.ValAddress(bech32validatorAddr) clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { diff --git a/x/staking/common_test.go b/x/staking/common_test.go index 9641b1ff51..0b0b1bbe6e 100644 --- a/x/staking/common_test.go +++ b/x/staking/common_test.go @@ -21,12 +21,12 @@ func init() { // nolint:deadcode,unused,varcheck var ( priv1 = secp256k1.GenPrivKey() - addr1 = sdk.AccAddress(priv1.PubKey().Address()) + addr1 = sdk.BytesToAccAddress(priv1.PubKey().Address()) priv2 = secp256k1.GenPrivKey() - addr2 = sdk.AccAddress(priv2.PubKey().Address()) + addr2 = sdk.BytesToAccAddress(priv2.PubKey().Address()) valKey = ed25519.GenPrivKey() - valAddr = sdk.AccAddress(valKey.PubKey().Address()) + valAddr = sdk.BytesToAccAddress(valKey.PubKey().Address()) commissionRates = types.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) diff --git a/x/staking/genesis.go b/x/staking/genesis.go index f8e45456cf..e035e73e7b 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -63,10 +63,7 @@ func InitGenesis( } for _, delegation := range data.Delegations { - delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) // Call the before-creation hook if not exported if !data.Exported { @@ -132,10 +129,7 @@ func InitGenesis( // don't need to run Tendermint updates if we exported if data.Exported { for _, lv := range data.LastValidatorPowers { - valAddr, err := sdk.ValAddressFromBech32(lv.Address) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(lv.Address) keeper.SetLastValidatorPower(ctx, valAddr, lv.Power) validator, found := keeper.GetValidator(ctx, valAddr) @@ -208,7 +202,7 @@ func WriteValidators(ctx sdk.Context, keeper keeper.Keeper) (vals []osttypes.Gen } vals = append(vals, osttypes.GenesisValidator{ - Address: sdk.ConsAddress(tmPk.Address()).Bytes(), + Address: tmPk.Address(), PubKey: tmPk, Power: validator.GetConsensusPower(), Name: validator.GetMoniker(), diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index 1d5cb28d06..39f10d9ca4 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -52,13 +52,13 @@ func TestInitGenesis(t *testing.T) { require.NoError(t, err) // initialize the validators - validators[0].OperatorAddress = sdk.ValAddress(addrs[0]).String() + validators[0].OperatorAddress = addrs[0].ToValAddress().String() validators[0].ConsensusPubkey = pk0 validators[0].Description = types.NewDescription("hoop", "", "", "", "") validators[0].Status = types.Bonded validators[0].Tokens = valTokens validators[0].DelegatorShares = valTokens.ToDec() - validators[1].OperatorAddress = sdk.ValAddress(addrs[1]).String() + validators[1].OperatorAddress = addrs[1].ToValAddress().String() validators[1].ConsensusPubkey = pk1 validators[1].Description = types.NewDescription("bloop", "", "", "", "") validators[1].Status = types.Bonded @@ -81,11 +81,11 @@ func TestInitGenesis(t *testing.T) { } // now make sure the validators are bonded and intra-tx counters are correct - resVal, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[0])) + resVal, found := app.StakingKeeper.GetValidator(ctx, addrs[0].ToValAddress()) require.True(t, found) require.Equal(t, types.Bonded, resVal.Status) - resVal, found = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[1])) + resVal, found = app.StakingKeeper.GetValidator(ctx, addrs[1].ToValAddress()) require.True(t, found) require.Equal(t, types.Bonded, resVal.Status) @@ -108,7 +108,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { validators := make([]types.Validator, size) var err error for i := range validators { - validators[i], err = types.NewValidator(sdk.ValAddress(addrs[i]), + validators[i], err = types.NewValidator(addrs[i].ToValAddress(), PKs[i], types.NewDescription(fmt.Sprintf("#%d", i), "", "", "", "")) require.NoError(t, err) validators[i].Status = types.Bonded @@ -135,7 +135,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { func TestValidateGenesis(t *testing.T) { genValidators1 := make([]types.Validator, 1, 5) pk := ed25519.GenPrivKey().PubKey() - genValidators1[0] = teststaking.NewValidator(t, sdk.ValAddress(pk.Address()), pk) + genValidators1[0] = teststaking.NewValidator(t, sdk.BytesToValAddress(pk.Address()), pk) genValidators1[0].Tokens = sdk.OneInt() genValidators1[0].DelegatorShares = sdk.OneDec() diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index 1cb07f2e69..4dbb95274e 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -60,7 +60,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.Equal(t, 1, len(updates)) // verify the self-delegation exists - bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.True(t, found) gotBond := bond.Shares.RoundInt() require.Equal(t, initBond, gotBond) @@ -80,7 +80,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.Equal(t, 1, len(updates)) // slash and jail the first validator - consAddr0 := sdk.ConsAddress(PKs[0].Address()) + consAddr0 := sdk.BytesToConsAddress(PKs[0].Address()) app.StakingKeeper.Slash(ctx, consAddr0, 0, initPower, sdk.NewDecWithPrec(5, 1)) app.StakingKeeper.Jail(ctx, consAddr0) app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -106,7 +106,7 @@ func TestValidatorByPowerIndex(t *testing.T) { // unbond self-delegation totalBond := validator.TokensFromShares(bond.GetShares()).TruncateInt() - res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, totalBond, true) + res := tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, totalBond, true) var resData types.MsgUndelegateResponse err = proto.Unmarshal(res.Data, &resData) @@ -222,7 +222,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) valAddr := valAddrs[0] - valConsPubKey, valConsAddr := PKs[0], sdk.ConsAddress(PKs[0].Address()) + valConsPubKey, valConsAddr := PKs[0], sdk.BytesToConsAddress(PKs[0].Address()) delAddr := delAddrs[1] // create validator @@ -247,7 +247,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { require.Equal(t, bondAmount.MulRaw(2), validator.BondedTokens()) // unbond validator total self-delegations (which should jail the validator) - res := tstaking.Undelegate(sdk.AccAddress(valAddr), valAddr, bondAmount, true) + res := tstaking.Undelegate(valAddr.ToAccAddress(), valAddr, bondAmount, true) var resData types.MsgUndelegateResponse err = proto.Unmarshal(res.Data, &resData) @@ -268,7 +268,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt()) // verify the validator can still self-delegate - tstaking.Delegate(sdk.AccAddress(valAddr), valAddr, bondAmount) + tstaking.Delegate(valAddr.ToAccAddress(), valAddr, bondAmount) // verify validator bonded shares validator, found = app.StakingKeeper.GetValidator(ctx, valAddr) @@ -316,7 +316,7 @@ func TestIncrementsMsgDelegate(t *testing.T) { tstaking.CheckDelegator(delegatorAddr, validatorAddr, false) - bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.True(t, found) require.Equal(t, bondAmount, bond.Shares.RoundInt()) @@ -373,7 +373,7 @@ func TestEditValidatorDecreaseMinSelfDelegation(t *testing.T) { require.Equal(t, 1, len(updates)) // verify the self-delegation exists - bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.True(t, found) gotBond := bond.Shares.RoundInt() require.Equal(t, initBond, gotBond, @@ -404,7 +404,7 @@ func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) { require.Equal(t, 1, len(updates)) // verify the self-delegation exists - bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.True(t, found) gotBond := bond.Shares.RoundInt() require.Equal(t, initBond, gotBond, @@ -622,7 +622,7 @@ func TestJailValidator(t *testing.T) { // unbond the validators bond portion unamt := sdk.NewInt(amt) - res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, unamt, true) + res := tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, unamt, true) var resData types.MsgUndelegateResponse err := proto.Unmarshal(res.Data, &resData) @@ -665,7 +665,7 @@ func TestValidatorQueue(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // unbond the all self-delegation to put validator in unbonding state - res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, amt, true) + res := tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, amt, true) var resData types.MsgUndelegateResponse err := proto.Unmarshal(res.Data, &resData) @@ -711,26 +711,26 @@ func TestUnbondingPeriod(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin unbonding - tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, amt, true) + tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, amt, true) origHeader := ctx.BlockHeader() - _, found := app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + _, found := app.StakingKeeper.GetUnbondingDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.True(t, found, "should not have unbonded") // cannot complete unbonding at same time staking.EndBlocker(ctx, app.StakingKeeper) - _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.True(t, found, "should not have unbonded") // cannot complete unbonding at time 6 seconds later ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 6)) - _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.True(t, found, "should not have unbonded") // can complete unbonding at time 7 seconds later ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 7)) - _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) require.False(t, found, "should have unbonded") } @@ -746,7 +746,7 @@ func TestUnbondingFromUnbondingValidator(t *testing.T) { // unbond the validators bond portion unbondAmt := sdk.NewInt(10) - res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt, true) + res := tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, unbondAmt, true) // change the ctx to Block Time one second before the validator would have unbonded var resData types.MsgUndelegateResponse @@ -779,42 +779,42 @@ func TestRedelegationPeriod(t *testing.T) { params.UnbondingTime = 7 * time.Second app.StakingKeeper.SetParams(ctx, params) // initial balance - amt1 := app.BankKeeper.GetBalance(ctx, sdk.AccAddress(validatorAddr), denom).Amount + amt1 := app.BankKeeper.GetBalance(ctx, validatorAddr.ToAccAddress(), denom).Amount // create the validators tstaking.CreateValidator(validatorAddr, PKs[0], sdk.NewInt(10), true) // balance should have been subtracted after creation - amt2 := app.BankKeeper.GetBalance(ctx, sdk.AccAddress(validatorAddr), denom).Amount + amt2 := app.BankKeeper.GetBalance(ctx, validatorAddr.ToAccAddress(), denom).Amount require.Equal(t, amt1.Sub(sdk.NewInt(10)), amt2, "expected coins to be subtracted") tstaking.CreateValidator(validatorAddr2, PKs[1], sdk.NewInt(10), true) - bal1 := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(validatorAddr)) + bal1 := app.BankKeeper.GetAllBalances(ctx, validatorAddr.ToAccAddress()) // begin redelegate redAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgBeginRedelegate := types.NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2, redAmt) + msgBeginRedelegate := types.NewMsgBeginRedelegate(validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2, redAmt) tstaking.Handle(msgBeginRedelegate, true) // origin account should not lose tokens as with a regular delegation - bal2 := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(validatorAddr)) + bal2 := app.BankKeeper.GetAllBalances(ctx, validatorAddr.ToAccAddress()) require.Equal(t, bal1, bal2) origHeader := ctx.BlockHeader() // cannot complete redelegation at same time staking.EndBlocker(ctx, app.StakingKeeper) - _, found := app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) + _, found := app.StakingKeeper.GetRedelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2) require.True(t, found, "should not have unbonded") // cannot complete redelegation at time 6 seconds later ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 6)) - _, found = app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) + _, found = app.StakingKeeper.GetRedelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2) require.True(t, found, "should not have unbonded") // can complete redelegation at time 7 seconds later ctx = tstaking.TurnBlock(origHeader.Time.Add(time.Second * 7)) - _, found = app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) + _, found = app.StakingKeeper.GetRedelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2) require.False(t, found, "should have unbonded") } @@ -834,11 +834,11 @@ func TestTransitiveRedelegation(t *testing.T) { // begin redelegate redAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgBeginRedelegate := types.NewMsgBeginRedelegate(sdk.AccAddress(val1), val1, val2, redAmt) + msgBeginRedelegate := types.NewMsgBeginRedelegate(val1.ToAccAddress(), val1, val2, redAmt) tstaking.Handle(msgBeginRedelegate, true) // cannot redelegation to next validator while first delegation exists - msgBeginRedelegate = types.NewMsgBeginRedelegate(sdk.AccAddress(val1), val2, val3, redAmt) + msgBeginRedelegate = types.NewMsgBeginRedelegate(val1.ToAccAddress(), val2, val3, redAmt) tstaking.Handle(msgBeginRedelegate, false) params := app.StakingKeeper.GetParams(ctx) @@ -872,7 +872,7 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin a redelegate - selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) + selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) redAmt := sdk.NewCoin(sdk.DefaultBondDenom, valTokens.QuoRaw(2)) msgBeginRedelegate := types.NewMsgBeginRedelegate(selfDelAddr, valAddr, valAddr2, redAmt) tstaking.Handle(msgBeginRedelegate, true) @@ -916,7 +916,7 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin a redelegate - selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) + selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) redAmt := sdk.NewCoin(sdk.DefaultBondDenom, valTokens.QuoRaw(2)) msgBeginRedelegate := types.NewMsgBeginRedelegate(selfDelAddr, valAddr, valAddr2, redAmt) tstaking.Handle(msgBeginRedelegate, true) @@ -961,7 +961,7 @@ func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin an unbonding delegation - selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) + selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) tstaking.Undelegate(selfDelAddr, valAddr, valTokens.QuoRaw(2), true) // there should only be one entry in the ubd object @@ -1001,7 +1001,7 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin an unbonding delegation - selfDelAddr := sdk.AccAddress(valAddr) // (the validator is it's own delegator) + selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) tstaking.Undelegate(selfDelAddr, valAddr, valTokens.QuoRaw(2), true) // there should only be one entry in the ubd object @@ -1059,7 +1059,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { require.Equal(t, 2, len(app.StakingKeeper.GetLastValidators(ctx))) // unbond the validator-2 - tstaking.Undelegate(sdk.AccAddress(val2), val2, valTokens2, true) + tstaking.Undelegate(val2.ToAccAddress(), val2, valTokens2, true) // apply TM updates app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -1075,7 +1075,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { initPower := int64(1000) app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 3, sdk.TokensFromConsensusPower(initPower)) valA, valB, del := valAddrs[0], valAddrs[1], delAddrs[2] - consAddr0 := sdk.ConsAddress(PKs[0].Address()) + consAddr0 := sdk.BytesToConsAddress(PKs[0].Address()) tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) valTokens := tstaking.CreateValidatorWithValPower(valA, PKs[0], 10, true) diff --git a/x/staking/keeper/alias_functions.go b/x/staking/keeper/alias_functions.go index 1b3c757e60..35871b9461 100644 --- a/x/staking/keeper/alias_functions.go +++ b/x/staking/keeper/alias_functions.go @@ -40,8 +40,7 @@ func (k Keeper) IterateBondedValidatorsByPower(ctx sdk.Context, fn func(index in i := int64(0) for ; iterator.Valid() && i < int64(maxValidators); iterator.Next() { - address := iterator.Value() - validator := k.mustGetValidator(ctx, address) + validator := k.mustGetValidator(ctx, sdk.ValAddress(string(iterator.Value()))) if validator.IsBonded() { stop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to? @@ -63,7 +62,7 @@ func (k Keeper) IterateLastValidators(ctx sdk.Context, fn func(index int64, vali for ; iterator.Valid(); iterator.Next() { address := types.AddressFromLastValidatorPowerKey(iterator.Key()) - validator, found := k.GetValidator(ctx, address) + validator, found := k.GetValidator(ctx, sdk.ValAddress(string(address))) if !found { panic(fmt.Sprintf("validator record not found for address: %v\n", address)) } diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index da90bd1dfd..fef1037ac1 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -1,7 +1,6 @@ package keeper import ( - "bytes" "fmt" "time" @@ -90,10 +89,7 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres // set a delegation func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { - delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) store := ctx.KVStore(k.storeKey) b := types.MustMarshalDelegation(k.cdc, delegation) @@ -102,10 +98,7 @@ func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { // remove a delegation func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) { - delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) // TODO: Consider calling hooks outside of the store wrapper functions, it's unobvious. k.BeforeDelegationRemoved(ctx, delegatorAddress, delegation.GetValidatorAddr()) store := ctx.KVStore(k.storeKey) @@ -196,16 +189,10 @@ func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context, // set the unbonding delegation and associated index func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { - delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(ubd.DelegatorAddress) store := ctx.KVStore(k.storeKey) bz := types.MustMarshalUBD(k.cdc, ubd) - addr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) - if err != nil { - panic(err) - } + addr := sdk.ValAddress(ubd.ValidatorAddress) key := types.GetUBDKey(delegatorAddress, addr) store.Set(key, bz) store.Set(types.GetUBDByValIndexKey(delegatorAddress, addr), []byte{}) // index, store empty bytes @@ -213,16 +200,10 @@ func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDeleg // remove the unbonding delegation object and associated index func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { - delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(ubd.DelegatorAddress) store := ctx.KVStore(k.storeKey) - addr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) - if err != nil { - panic(err) - } + addr := sdk.ValAddress(ubd.ValidatorAddress) key := types.GetUBDKey(delegatorAddress, addr) store.Delete(key) store.Delete(types.GetUBDByValIndexKey(delegatorAddress, addr)) @@ -394,21 +375,12 @@ func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context, // set a redelegation and associated index func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { - delegatorAddress, err := sdk.AccAddressFromBech32(red.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(red.DelegatorAddress) store := ctx.KVStore(k.storeKey) bz := types.MustMarshalRED(k.cdc, red) - valSrcAddr, err := sdk.ValAddressFromBech32(red.ValidatorSrcAddress) - if err != nil { - panic(err) - } - valDestAddr, err := sdk.ValAddressFromBech32(red.ValidatorDstAddress) - if err != nil { - panic(err) - } + valSrcAddr := sdk.ValAddress(red.ValidatorSrcAddress) + valDestAddr := sdk.ValAddress(red.ValidatorDstAddress) key := types.GetREDKey(delegatorAddress, valSrcAddr, valDestAddr) store.Set(key, bz) store.Set(types.GetREDByValSrcIndexKey(delegatorAddress, valSrcAddr, valDestAddr), []byte{}) @@ -453,19 +425,10 @@ func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red t // remove a redelegation object and associated index func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) { - delegatorAddress, err := sdk.AccAddressFromBech32(red.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(red.DelegatorAddress) store := ctx.KVStore(k.storeKey) - valSrcAddr, err := sdk.ValAddressFromBech32(red.ValidatorSrcAddress) - if err != nil { - panic(err) - } - valDestAddr, err := sdk.ValAddressFromBech32(red.ValidatorDstAddress) - if err != nil { - panic(err) - } + valSrcAddr := sdk.ValAddress(red.ValidatorSrcAddress) + valDestAddr := sdk.ValAddress(red.ValidatorDstAddress) redKey := types.GetREDKey(delegatorAddress, valSrcAddr, valDestAddr) store.Delete(redKey) store.Delete(types.GetREDByValSrcIndexKey(delegatorAddress, valSrcAddr, valDestAddr)) @@ -568,10 +531,7 @@ func (k Keeper) Delegate( k.BeforeDelegationCreated(ctx, delAddr, validator.GetOperator()) } - delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) // if subtractAccount is true then we are // performing a delegation and not a redelegation, thus the source tokens are @@ -653,12 +613,9 @@ func (k Keeper) Unbond( // subtract shares from delegation delegation.Shares = delegation.Shares.Sub(shares) - delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - return amount, err - } + delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) - isValidatorOperator := delegatorAddress.Equals(validator.GetOperator()) + isValidatorOperator := delegatorAddress.Equals(validator.GetOperator().ToAccAddress()) // If the delegation is the operator of the validator and undelegating will decrease the validator's // self-delegation below their minimum, we jail the validator. @@ -764,10 +721,7 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd balances := sdk.NewCoins() ctxTime := ctx.BlockHeader().Time - delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) - if err != nil { - return nil, err - } + delegatorAddress := sdk.AccAddress(ubd.DelegatorAddress) // loop through all the entries and complete unbonding mature entries for i := 0; i < len(ubd.Entries); i++ { @@ -804,7 +758,7 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd func (k Keeper) BeginRedelegation( ctx sdk.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, sharesAmount sdk.Dec, ) (completionTime time.Time, err error) { - if bytes.Equal(valSrcAddr, valDstAddr) { + if valSrcAddr.Equals(valDstAddr) { return time.Time{}, types.ErrSelfRedelegation } diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index ff9f4bdbc3..23f9a27ca3 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -331,7 +331,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) require.True(t, validator.IsBonded()) - selfDelegation := types.NewDelegation(sdk.AccAddress(addrVals[0].Bytes()), addrVals[0], issuedShares) + selfDelegation := types.NewDelegation(addrVals[0].ToAccAddress(), addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) // add bonded tokens to pool for delegations @@ -357,7 +357,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + val0AccAddr := addrVals[0].ToAccAddress() _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], sdk.TokensFromConsensusPower(6).ToDec()) require.NoError(t, err) @@ -396,7 +396,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - selfDelegation := types.NewDelegation(addrVals[0].Bytes(), addrVals[0], issuedShares) + selfDelegation := types.NewDelegation(addrVals[0].ToAccAddress(), addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) bondedPool := app.StakingKeeper.GetBondedPool(ctx) @@ -433,7 +433,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { ctx = ctx.WithBlockHeader(header) // unbond the all self-delegation to put validator in unbonding state - val0AccAddr := sdk.AccAddress(addrVals[0]) + val0AccAddr := addrVals[0].ToAccAddress() _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) require.NoError(t, err) @@ -489,7 +489,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - val0AccAddr := sdk.AccAddress(addrVals[0]) + val0AccAddr := addrVals[0].ToAccAddress() selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -573,7 +573,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + val0AccAddr := addrVals[0].ToAccAddress() selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -678,7 +678,7 @@ func TestRedelegation(t *testing.T) { require.Equal(t, 1, len(redelegations)) require.Equal(t, redelegations[0], resRed) - redelegations = app.StakingKeeper.GetAllRedelegations(ctx, addrDels[0], nil, nil) + redelegations = app.StakingKeeper.GetAllRedelegations(ctx, addrDels[0], "", "") require.Equal(t, 1, len(redelegations)) require.Equal(t, redelegations[0], resRed) @@ -710,7 +710,7 @@ func TestRedelegation(t *testing.T) { redelegations = app.StakingKeeper.GetRedelegations(ctx, addrDels[0], 5) require.Equal(t, 0, len(redelegations)) - redelegations = app.StakingKeeper.GetAllRedelegations(ctx, addrDels[0], nil, nil) + redelegations = app.StakingKeeper.GetAllRedelegations(ctx, addrDels[0], "", "") require.Equal(t, 0, len(redelegations)) } @@ -737,7 +737,7 @@ func TestRedelegateToSameValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + val0AccAddr := addrVals[0].ToAccAddress() selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -767,7 +767,7 @@ func TestRedelegationMaxEntries(t *testing.T) { validator, issuedShares := validator.AddTokensFromDel(valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + val0AccAddr := addrVals[0].ToAccAddress() selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -829,7 +829,7 @@ func TestRedelegateSelfDelegation(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) - val0AccAddr := sdk.AccAddress(addrVals[0]) + val0AccAddr := addrVals[0].ToAccAddress() selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -885,7 +885,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { validator, issuedShares := validator.AddTokensFromDel(valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + val0AccAddr := addrVals[0].ToAccAddress() selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -969,7 +969,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { validator, issuedShares := validator.AddTokensFromDel(valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + val0AccAddr := addrVals[0].ToAccAddress() selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index 3ee9f24a42..2afcec9b67 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -70,12 +70,12 @@ func (k Querier) Validator(c context.Context, req *types.QueryValidatorRequest) if req.ValidatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "validator address cannot be empty") } - - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) - if err != nil { - return nil, err + if err := sdk.ValidateValAddress(req.ValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) } + valAddr := sdk.ValAddress(req.ValidatorAddr) + ctx := sdk.UnwrapSDKContext(c) validator, found := k.GetValidator(ctx, valAddr) if !found { @@ -94,6 +94,10 @@ func (k Querier) ValidatorDelegations(c context.Context, req *types.QueryValidat if req.ValidatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "validator address cannot be empty") } + if err := sdk.ValidateValAddress(req.ValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + var delegations []types.Delegation ctx := sdk.UnwrapSDKContext(c) @@ -105,10 +109,7 @@ func (k Querier) ValidatorDelegations(c context.Context, req *types.QueryValidat return false, err } - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) - if err != nil { - return false, err - } + valAddr := sdk.ValAddress(req.ValidatorAddr) if !delegation.GetValidatorAddr().Equals(valAddr) { return false, nil @@ -141,15 +142,15 @@ func (k Querier) ValidatorUnbondingDelegations(c context.Context, req *types.Que if req.ValidatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "validator address cannot be empty") } + if err := sdk.ValidateValAddress(req.ValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } var ubds types.UnbondingDelegations ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(k.storeKey) - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) - if err != nil { - return nil, err - } + valAddr := sdk.ValAddress(req.ValidatorAddr) srcValPrefix := types.GetUBDsByValIndexKey(valAddr) ubdStore := prefix.NewStore(store, srcValPrefix) @@ -183,20 +184,21 @@ func (k Querier) Delegation(c context.Context, req *types.QueryDelegationRequest if req.DelegatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "delegator address cannot be empty") } + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.ValidatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "validator address cannot be empty") } + if err := sdk.ValidateValAddress(req.ValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) - if err != nil { - return nil, err - } + valAddr := sdk.ValAddress(req.ValidatorAddr) delegation, found := k.GetDelegation(ctx, delAddr, valAddr) if !found { @@ -223,21 +225,22 @@ func (k Querier) UnbondingDelegation(c context.Context, req *types.QueryUnbondin if req.DelegatorAddr == "" { return nil, status.Errorf(codes.InvalidArgument, "delegator address cannot be empty") } + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.ValidatorAddr == "" { return nil, status.Errorf(codes.InvalidArgument, "validator address cannot be empty") } + if err := sdk.ValidateValAddress(req.ValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) - if err != nil { - return nil, err - } + valAddr := sdk.ValAddress(req.ValidatorAddr) unbond, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr) if !found { @@ -259,13 +262,14 @@ func (k Querier) DelegatorDelegations(c context.Context, req *types.QueryDelegat if req.DelegatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "delegator address cannot be empty") } + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + var delegations types.Delegations ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) store := ctx.KVStore(k.storeKey) delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) @@ -304,20 +308,21 @@ func (k Querier) DelegatorValidator(c context.Context, req *types.QueryDelegator if req.DelegatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "delegator address cannot be empty") } + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.ValidatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "validator address cannot be empty") } + if err := sdk.ValidateValAddress(req.ValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } ctx := sdk.UnwrapSDKContext(c) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) - valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) - if err != nil { - return nil, err - } + valAddr := sdk.ValAddress(req.ValidatorAddr) validator, err := k.GetDelegatorValidator(ctx, delAddr, valAddr) if err != nil { @@ -336,14 +341,15 @@ func (k Querier) DelegatorUnbondingDelegations(c context.Context, req *types.Que if req.DelegatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "delegator address cannot be empty") } + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + var unbondingDelegations types.UnbondingDelegations ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(k.storeKey) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) unbStore := prefix.NewStore(store, types.GetUBDsKey(delAddr)) pageRes, err := query.Paginate(unbStore, req.Pagination, func(key []byte, value []byte) error { @@ -393,10 +399,25 @@ func (k Querier) Redelegations(c context.Context, req *types.QueryRedelegationsR store := ctx.KVStore(k.storeKey) switch { case req.DelegatorAddr != "" && req.SrcValidatorAddr != "" && req.DstValidatorAddr != "": + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if err := sdk.ValidateValAddress(req.SrcValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if err := sdk.ValidateValAddress(req.DstValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } redels, err = queryRedelegation(ctx, k, req) case req.DelegatorAddr == "" && req.SrcValidatorAddr != "" && req.DstValidatorAddr == "": + if err := sdk.ValidateValAddress(req.SrcValidatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } redels, pageRes, err = queryRedelegationsFromSrcValidator(store, k, req) default: + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } redels, pageRes, err = queryAllRedelegations(store, k, req) } if err != nil { @@ -418,14 +439,15 @@ func (k Querier) DelegatorValidators(c context.Context, req *types.QueryDelegato if req.DelegatorAddr == "" { return nil, status.Error(codes.InvalidArgument, "delegator address cannot be empty") } + if err := sdk.ValidateAccAddress(req.DelegatorAddr); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + var validators types.Validators ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(k.storeKey) - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) pageRes, err := query.Paginate(delStore, req.Pagination, func(key []byte, value []byte) error { @@ -475,20 +497,11 @@ func (k Querier) Params(c context.Context, _ *types.QueryParamsRequest) (*types. func queryRedelegation(ctx sdk.Context, k Querier, req *types.QueryRedelegationsRequest) (redels types.Redelegations, err error) { - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) - srcValAddr, err := sdk.ValAddressFromBech32(req.SrcValidatorAddr) - if err != nil { - return nil, err - } + srcValAddr := sdk.ValAddress(req.SrcValidatorAddr) - dstValAddr, err := sdk.ValAddressFromBech32(req.DstValidatorAddr) - if err != nil { - return nil, err - } + dstValAddr := sdk.ValAddress(req.DstValidatorAddr) redel, found := k.GetRedelegation(ctx, delAddr, srcValAddr, dstValAddr) if !found { @@ -503,10 +516,7 @@ func queryRedelegation(ctx sdk.Context, k Querier, req *types.QueryRedelegations } func queryRedelegationsFromSrcValidator(store sdk.KVStore, k Querier, req *types.QueryRedelegationsRequest) (redels types.Redelegations, res *query.PageResponse, err error) { - valAddr, err := sdk.ValAddressFromBech32(req.SrcValidatorAddr) - if err != nil { - return nil, nil, err - } + valAddr := sdk.ValAddress(req.SrcValidatorAddr) srcValPrefix := types.GetREDsFromValSrcIndexKey(valAddr) redStore := prefix.NewStore(store, srcValPrefix) @@ -525,10 +535,7 @@ func queryRedelegationsFromSrcValidator(store sdk.KVStore, k Querier, req *types } func queryAllRedelegations(store sdk.KVStore, k Querier, req *types.QueryRedelegationsRequest) (redels types.Redelegations, res *query.PageResponse, err error) { - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) - if err != nil { - return nil, nil, err - } + delAddr := sdk.AccAddress(req.DelegatorAddr) redStore := prefix.NewStore(store, types.GetREDsKey(delAddr)) res, err = query.Paginate(redStore, req.Pagination, func(key []byte, value []byte) error { diff --git a/x/staking/keeper/grpc_query_test.go b/x/staking/keeper/grpc_query_test.go index 64e16e536d..ae6a1bb2a6 100644 --- a/x/staking/keeper/grpc_query_test.go +++ b/x/staking/keeper/grpc_query_test.go @@ -223,10 +223,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegatorValidator() { func (suite *KeeperTestSuite) TestGRPCQueryDelegation() { app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals addrAcc, addrAcc1 := addrs[0], addrs[1] - addrVal := vals[0].OperatorAddress - valAddr, err := sdk.ValAddressFromBech32(addrVal) - suite.NoError(err) - delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr) + addrVal := sdk.ValAddress(vals[0].OperatorAddress) + delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, addrVal) suite.True(found) var req *types.QueryDelegationRequest @@ -245,14 +243,14 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegation() { func() { req = &types.QueryDelegationRequest{ DelegatorAddr: addrAcc1.String(), - ValidatorAddr: addrVal, + ValidatorAddr: addrVal.String(), } }, false, }, {"valid request", func() { - req = &types.QueryDelegationRequest{DelegatorAddr: addrAcc.String(), ValidatorAddr: addrVal} + req = &types.QueryDelegationRequest{DelegatorAddr: addrAcc.String(), ValidatorAddr: addrVal.String()} }, true, }, @@ -278,8 +276,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegatorDelegations() { app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals addrAcc := addrs[0] addrVal1 := vals[0].OperatorAddress - valAddr, err := sdk.ValAddressFromBech32(addrVal1) - suite.NoError(err) + valAddr := sdk.ValAddress(addrVal1) delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr) suite.True(found) var req *types.QueryDelegatorDelegationsRequest @@ -332,8 +329,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorDelegations() { addrVal1 := vals[1].OperatorAddress valAddrs := simapp.ConvertAddrsToValAddrs(addrs) addrVal2 := valAddrs[4] - valAddr, err := sdk.ValAddressFromBech32(addrVal1) - suite.NoError(err) + valAddr := sdk.ValAddress(addrVal1) delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr) suite.True(found) @@ -396,8 +392,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryUnbondingDelegation() { addrVal2 := vals[1].OperatorAddress unbondingTokens := sdk.TokensFromConsensusPower(2) - valAddr, err1 := sdk.ValAddressFromBech32(addrVal2) - suite.NoError(err1) + valAddr := sdk.ValAddress(addrVal2) _, err := app.StakingKeeper.Undelegate(ctx, addrAcc2, valAddr, unbondingTokens.ToDec()) suite.NoError(err) @@ -451,12 +446,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegatorUnbondingDelegations() { addrVal, addrVal2 := vals[0].OperatorAddress, vals[1].OperatorAddress unbondingTokens := sdk.TokensFromConsensusPower(2) - valAddr1, err1 := sdk.ValAddressFromBech32(addrVal) - suite.NoError(err1) + valAddr1 := sdk.ValAddress(addrVal) _, err := app.StakingKeeper.Undelegate(ctx, addrAcc, valAddr1, unbondingTokens.ToDec()) suite.NoError(err) - valAddr2, err1 := sdk.ValAddressFromBech32(addrVal2) - suite.NoError(err1) + valAddr2 := sdk.ValAddress(addrVal2) _, err = app.StakingKeeper.Undelegate(ctx, addrAcc, valAddr2, unbondingTokens.ToDec()) suite.NoError(err) diff --git a/x/staking/keeper/invariants.go b/x/staking/keeper/invariants.go index 3dbfa301e8..673250439a 100644 --- a/x/staking/keeper/invariants.go +++ b/x/staking/keeper/invariants.go @@ -100,7 +100,7 @@ func NonNegativePowerInvariant(k Keeper) sdk.Invariant { iterator := k.ValidatorsPowerStoreIterator(ctx) for ; iterator.Valid(); iterator.Next() { - validator, found := k.GetValidator(ctx, iterator.Value()) + validator, found := k.GetValidator(ctx, sdk.ValAddress(string(iterator.Value()))) if !found { panic(fmt.Sprintf("validator record not found for address: %X\n", iterator.Value())) } diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index 712e274a0d..aff57f37a4 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -40,11 +40,11 @@ func NewKeeper( } // ensure bonded and not bonded module accounts are set - if addr := ak.GetModuleAddress(types.BondedPoolName); addr == nil { + if addr := ak.GetModuleAddress(types.BondedPoolName); addr.Empty() { panic(fmt.Sprintf("%s module account has not been set", types.BondedPoolName)) } - if addr := ak.GetModuleAddress(types.NotBondedPoolName); addr == nil { + if addr := ak.GetModuleAddress(types.NotBondedPoolName); addr.Empty() { panic(fmt.Sprintf("%s module account has not been set", types.NotBondedPoolName)) } diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index 27aa898d4d..269368748c 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -29,10 +29,7 @@ var _ types.MsgServer = msgServer{} func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateValidator) (*types.MsgCreateValidatorResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if err != nil { - return nil, err - } + valAddr := sdk.ValAddress(msg.ValidatorAddress) // check to see if the pubkey or sender has been registered before if _, found := k.GetValidator(ctx, valAddr); found { @@ -81,10 +78,7 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa return nil, err } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - return nil, err - } + delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) validator.MinSelfDelegation = msg.MinSelfDelegation @@ -121,10 +115,7 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa func (k msgServer) EditValidator(goCtx context.Context, msg *types.MsgEditValidator) (*types.MsgEditValidatorResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if err != nil { - return nil, err - } + valAddr := sdk.ValAddress(msg.ValidatorAddress) // validator must already be registered validator, found := k.GetValidator(ctx, valAddr) if !found { @@ -183,20 +174,14 @@ func (k msgServer) EditValidator(goCtx context.Context, msg *types.MsgEditValida func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if valErr != nil { - return nil, valErr - } + valAddr := sdk.ValAddress(msg.ValidatorAddress) validator, found := k.GetValidator(ctx, valAddr) if !found { return nil, types.ErrNoValidatorFound } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - return nil, err - } + delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) bondDenom := k.BondDenom(ctx) if msg.Amount.Denom != bondDenom { @@ -204,7 +189,7 @@ func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*typ } // NOTE: source funds are always unbonded - _, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonded, validator, true) + _, err := k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonded, validator, true) if err != nil { return nil, err } @@ -238,14 +223,8 @@ func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*typ func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRedelegate) (*types.MsgBeginRedelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress) - if err != nil { - return nil, err - } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - return nil, err - } + valSrcAddr := sdk.ValAddress(msg.ValidatorSrcAddress) + delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) shares, err := k.ValidateUnbondAmount( ctx, delegatorAddress, valSrcAddr, msg.Amount.Amount, ) @@ -258,10 +237,7 @@ func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRed return nil, sdkerrors.Wrapf(types.ErrBadDenom, "got %s, expected %s", msg.Amount.Denom, bondDenom) } - valDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress) - if err != nil { - return nil, err - } + valDstAddr := sdk.ValAddress(msg.ValidatorDstAddress) completionTime, err := k.BeginRedelegation( ctx, delegatorAddress, valSrcAddr, valDstAddr, shares, @@ -304,14 +280,8 @@ func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRed func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - addr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if err != nil { - return nil, err - } - delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - return nil, err - } + addr := sdk.ValAddress(msg.ValidatorAddress) + delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) shares, err := k.ValidateUnbondAmount( ctx, delegatorAddress, addr, msg.Amount.Amount, ) diff --git a/x/staking/keeper/querier.go b/x/staking/keeper/querier.go index 3ea10c9861..4807e860cc 100644 --- a/x/staking/keeper/querier.go +++ b/x/staking/keeper/querier.go @@ -251,7 +251,8 @@ func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, return res, nil } -func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { +func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, + legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorValidatorRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -259,17 +260,18 @@ func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, l return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) + err = sdk.ValidateAccAddress(params.DelegatorAddr) if err != nil { return nil, err } - valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) + err = sdk.ValidateValAddress(params.ValidatorAddr) if err != nil { return nil, err } - validator, err := k.GetDelegatorValidator(ctx, delAddr, valAddr) + validator, err := k.GetDelegatorValidator(ctx, sdk.AccAddress(params.DelegatorAddr), + sdk.ValAddress(params.ValidatorAddr)) if err != nil { return nil, err } @@ -282,7 +284,8 @@ func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, l return res, nil } -func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { +func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, + legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorValidatorRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -290,17 +293,18 @@ func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) + err = sdk.ValidateAccAddress(params.DelegatorAddr) if err != nil { return nil, err } - valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) + err = sdk.ValidateValAddress(params.ValidatorAddr) if err != nil { return nil, err } - delegation, found := k.GetDelegation(ctx, delAddr, valAddr) + delegation, found := k.GetDelegation(ctx, sdk.AccAddress(params.DelegatorAddr), + sdk.ValAddress(params.ValidatorAddr)) if !found { return nil, types.ErrNoDelegation } @@ -318,7 +322,8 @@ func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue return res, nil } -func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { +func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, + legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params types.QueryDelegatorValidatorRequest err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -326,17 +331,18 @@ func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) + err = sdk.ValidateAccAddress(params.DelegatorAddr) if err != nil { return nil, err } - valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) + err = sdk.ValidateValAddress(params.ValidatorAddr) if err != nil { return nil, err } - unbond, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr) + unbond, found := k.GetUnbondingDelegation(ctx, sdk.AccAddress(params.DelegatorAddr), + sdk.ValAddress(params.ValidatorAddr)) if !found { return nil, types.ErrNoUnbondingDelegation } @@ -453,10 +459,7 @@ func DelegationToDelegationResponse(ctx sdk.Context, k Keeper, del types.Delegat return types.DelegationResponse{}, types.ErrNoValidatorFound } - delegatorAddress, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - return types.DelegationResponse{}, err - } + delegatorAddress := sdk.AccAddress(del.DelegatorAddress) return types.NewDelegationResp( delegatorAddress, @@ -489,19 +492,10 @@ func RedelegationsToRedelegationResponses( resp := make(types.RedelegationResponses, len(redels)) for i, redel := range redels { - valSrcAddr, err := sdk.ValAddressFromBech32(redel.ValidatorSrcAddress) - if err != nil { - panic(err) - } - valDstAddr, err := sdk.ValAddressFromBech32(redel.ValidatorDstAddress) - if err != nil { - panic(err) - } + valSrcAddr := sdk.ValAddress(redel.ValidatorSrcAddress) + valDstAddr := sdk.ValAddress(redel.ValidatorDstAddress) - delegatorAddress, err := sdk.AccAddressFromBech32(redel.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(redel.DelegatorAddress) val, found := k.GetValidator(ctx, valDstAddr) if !found { return nil, types.ErrNoValidatorFound diff --git a/x/staking/keeper/querier_test.go b/x/staking/keeper/querier_test.go index 1b0026e60e..5ae2d1bbf7 100644 --- a/x/staking/keeper/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -90,7 +90,7 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"delegatorValidators"}, query) require.NoError(t, err) - bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(nil, nil, nil)) + bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams("", "", "")) require.NoError(t, errRes) query.Data = bz @@ -210,7 +210,7 @@ func TestQueryDelegation(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) + addrVal1, addrVal2 := addrAcc1.ToValAddress(), addrAcc2.ToValAddress() pubKeys := simapp.CreateTestPubKeys(2) pk1, pk2 := pubKeys[0], pubKeys[1] @@ -459,7 +459,7 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 100, sdk.TokensFromConsensusPower(10000)) pubKeys := simapp.CreateTestPubKeys(1) - valAddress := sdk.ValAddress(addrs[0]) + valAddress := addrs[0].ToValAddress() val1 := teststaking.NewValidator(t, valAddress, pubKeys[0]) app.StakingKeeper.SetValidator(ctx, val1) @@ -543,7 +543,7 @@ func TestQueryRedelegations(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) + addrVal1, addrVal2 := addrAcc1.ToValAddress(), addrAcc2.ToValAddress() // Create Validators and Delegation val1 := teststaking.NewValidator(t, addrVal1, PKs[0]) @@ -615,7 +615,7 @@ func TestQueryUnbondingDelegation(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1 := sdk.ValAddress(addrAcc1) + addrVal1 := addrAcc1.ToValAddress() // Create Validators and Delegation val1 := teststaking.NewValidator(t, addrVal1, PKs[0]) @@ -711,7 +711,7 @@ func TestQueryHistoricalInfo(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) + addrVal1, addrVal2 := addrAcc1.ToValAddress(), addrAcc2.ToValAddress() // Create Validators and Delegation val1 := teststaking.NewValidator(t, addrVal1, PKs[0]) diff --git a/x/staking/keeper/query_utils.go b/x/staking/keeper/query_utils.go index 48cd4662e3..59a3193567 100644 --- a/x/staking/keeper/query_utils.go +++ b/x/staking/keeper/query_utils.go @@ -109,14 +109,9 @@ func (k Keeper) GetAllRedelegations( for ; iterator.Valid(); iterator.Next() { redelegation := types.MustUnmarshalRED(k.cdc, iterator.Value()) - valSrcAddr, err := sdk.ValAddressFromBech32(redelegation.ValidatorSrcAddress) - if err != nil { - panic(err) - } - valDstAddr, err := sdk.ValAddressFromBech32(redelegation.ValidatorDstAddress) - if err != nil { - panic(err) - } + valSrcAddr := sdk.ValAddress(redelegation.ValidatorSrcAddress) + valDstAddr := sdk.ValAddress(redelegation.ValidatorDstAddress) + if srcValFilter && !(srcValAddress.Equals(valSrcAddr)) { continue } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 5e0de83d0e..ee21bc935f 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -33,7 +33,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh slashAmountDec := amount.ToDec().Mul(slashFactor) slashAmount := slashAmountDec.TruncateInt() - // ref https://github.com/line/lfb-sdk/issues/1348 + // ref https://github.com/cosmos/cosmos-sdk/issues/1348 validator, found := k.GetValidatorByConsAddr(ctx, consAddr) if !found { @@ -245,15 +245,9 @@ func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, continue } - valDstAddr, err := sdk.ValAddressFromBech32(redelegation.ValidatorDstAddress) - if err != nil { - panic(err) - } + valDstAddr := sdk.ValAddress(redelegation.ValidatorDstAddress) - delegatorAddress, err := sdk.AccAddressFromBech32(redelegation.DelegatorAddress) - if err != nil { - panic(err) - } + delegatorAddress := sdk.AccAddress(redelegation.DelegatorAddress) delegation, found := k.GetDelegation(ctx, delegatorAddress, valDstAddr) if !found { diff --git a/x/staking/keeper/slash_test.go b/x/staking/keeper/slash_test.go index 32f45ffb7b..1e6d9cb22b 100644 --- a/x/staking/keeper/slash_test.go +++ b/x/staking/keeper/slash_test.go @@ -55,7 +55,7 @@ func bootstrapSlashTest(t *testing.T, power int64) (*simapp.SimApp, sdk.Context, func TestRevocation(t *testing.T) { app, ctx, _, addrVals := bootstrapSlashTest(t, 5) - consAddr := sdk.ConsAddress(PKs[0].Address()) + consAddr := sdk.BytesToConsAddress(PKs[0].Address()) // initial state val, found := app.StakingKeeper.GetValidator(ctx, addrVals[0]) @@ -190,7 +190,7 @@ func TestSlashRedelegation(t *testing.T) { func TestSlashAtFutureHeight(t *testing.T) { app, ctx, _, _ := bootstrapSlashTest(t, 10) - consAddr := sdk.ConsAddress(PKs[0].Address()) + consAddr := sdk.BytesToConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) require.Panics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 1, 10, fraction) }) } @@ -199,7 +199,7 @@ func TestSlashAtFutureHeight(t *testing.T) { // this just represents pre-genesis and should have the same effect as slashing at height 0 func TestSlashAtNegativeHeight(t *testing.T) { app, ctx, _, _ := bootstrapSlashTest(t, 10) - consAddr := sdk.ConsAddress(PKs[0].Address()) + consAddr := sdk.BytesToConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) bondedPool := app.StakingKeeper.GetBondedPool(ctx) @@ -230,7 +230,7 @@ func TestSlashAtNegativeHeight(t *testing.T) { // tests Slash at the current height func TestSlashValidatorAtCurrentHeight(t *testing.T) { app, ctx, _, _ := bootstrapSlashTest(t, 10) - consAddr := sdk.ConsAddress(PKs[0].Address()) + consAddr := sdk.BytesToConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) bondedPool := app.StakingKeeper.GetBondedPool(ctx) @@ -262,7 +262,7 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { func TestSlashWithUnbondingDelegation(t *testing.T) { app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10) - consAddr := sdk.ConsAddress(PKs[0].Address()) + consAddr := sdk.BytesToConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) // set an unbonding delegation with expiration timestamp beyond which the @@ -389,7 +389,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // tests Slash at a previous height with a redelegation func TestSlashWithRedelegation(t *testing.T) { app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10) - consAddr := sdk.ConsAddress(PKs[0].Address()) + consAddr := sdk.BytesToConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) bondDenom := app.StakingKeeper.BondDenom(ctx) @@ -589,7 +589,7 @@ func TestSlashBoth(t *testing.T) { ctx = ctx.WithBlockHeight(12) validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) require.True(t, found) - consAddr0 := sdk.ConsAddress(PKs[0].Address()) + consAddr0 := sdk.BytesToConsAddress(PKs[0].Address()) app.StakingKeeper.Slash(ctx, consAddr0, 10, 10, fraction) burnedNotBondedAmount := fraction.MulInt(ubdATokens).TruncateInt() diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 293cda5c6a..ba27270f95 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -1,7 +1,6 @@ package keeper // noalias import ( - "bytes" "math/rand" sdk "github.com/line/lfb-sdk/types" @@ -26,8 +25,8 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - valAddr := types.ParseValidatorPowerRankKey(iterator.Key()) - if bytes.Equal(valAddr, validator.GetOperator()) { + valAddr := sdk.ValAddress(string(types.ParseValidatorPowerRankKey(iterator.Key()))) + if valAddr.Equals(validator.GetOperator()) { if deleted { panic("found duplicate power index key") } else { diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index a59790486e..59a72b7e13 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "sort" + "strings" gogotypes "github.com/gogo/protobuf/types" abci "github.com/line/ostracon/abci/types" @@ -35,15 +36,8 @@ func (k Keeper) BlockValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate { // Remove all mature unbonding delegations from the ubd queue. matureUnbonds := k.DequeueAllMatureUBDQueue(ctx, ctx.BlockHeader().Time) for _, dvPair := range matureUnbonds { - addr, err := sdk.ValAddressFromBech32(dvPair.ValidatorAddress) - if err != nil { - panic(err) - } - delegatorAddress, err := sdk.AccAddressFromBech32(dvPair.DelegatorAddress) - if err != nil { - panic(err) - } - balances, err := k.CompleteUnbonding(ctx, delegatorAddress, addr) + balances, err := k.CompleteUnbonding(ctx, sdk.AccAddress(dvPair.DelegatorAddress), + sdk.ValAddress(dvPair.ValidatorAddress)) if err != nil { continue } @@ -61,23 +55,11 @@ func (k Keeper) BlockValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate { // Remove all mature redelegations from the red queue. matureRedelegations := k.DequeueAllMatureRedelegationQueue(ctx, ctx.BlockHeader().Time) for _, dvvTriplet := range matureRedelegations { - valSrcAddr, err := sdk.ValAddressFromBech32(dvvTriplet.ValidatorSrcAddress) - if err != nil { - panic(err) - } - valDstAddr, err := sdk.ValAddressFromBech32(dvvTriplet.ValidatorDstAddress) - if err != nil { - panic(err) - } - delegatorAddress, err := sdk.AccAddressFromBech32(dvvTriplet.DelegatorAddress) - if err != nil { - panic(err) - } balances, err := k.CompleteRedelegation( ctx, - delegatorAddress, - valSrcAddr, - valDstAddr, + sdk.AccAddress(dvvTriplet.DelegatorAddress), + sdk.ValAddress(dvvTriplet.ValidatorSrcAddress), + sdk.ValAddress(dvvTriplet.ValidatorDstAddress), ) if err != nil { continue @@ -160,10 +142,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab } // fetch the old power bytes - var valAddrBytes [sdk.AddrLen]byte - - copy(valAddrBytes[:], valAddr[:]) - oldPowerBytes, found := last[valAddrBytes] + oldPowerBytes, found := last[valAddr.String()] newPower := validator.ConsensusPower() newPowerBytes := k.cdc.MustMarshalBinaryBare(&gogotypes.Int64Value{Value: newPower}) @@ -174,7 +153,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab k.SetLastValidatorPower(ctx, valAddr, newPower) } - delete(last, valAddrBytes) + delete(last, valAddr.String()) count++ totalPower = totalPower.Add(sdk.NewInt(newPower)) @@ -340,7 +319,7 @@ func (k Keeper) completeUnbondingValidator(ctx sdk.Context, validator types.Vali } // map of operator addresses to serialized power -type validatorsByAddr map[[sdk.AddrLen]byte][]byte +type validatorsByAddr map[string][]byte // get the last validator set func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr { @@ -350,9 +329,8 @@ func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr { defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - var valAddr [sdk.AddrLen]byte // extract the validator address from the key (prefix is 1-byte) - copy(valAddr[:], iterator.Key()[1:]) + valAddr := string(iterator.Key()[1:]) powerBytes := iterator.Value() last[valAddr] = make([]byte, len(powerBytes)) copy(last[valAddr], powerBytes) @@ -363,21 +341,19 @@ func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr { // given a map of remaining validators to previous bonded power // returns the list of validators to be unbonded, sorted by operator address -func sortNoLongerBonded(last validatorsByAddr) [][]byte { +func sortNoLongerBonded(last validatorsByAddr) []string { // sort the map keys for determinism - noLongerBonded := make([][]byte, len(last)) + noLongerBonded := make([]string, len(last)) index := 0 for valAddrBytes := range last { - valAddr := make([]byte, sdk.AddrLen) - copy(valAddr, valAddrBytes[:]) - noLongerBonded[index] = valAddr + noLongerBonded[index] = valAddrBytes index++ } // sorted by address - order doesn't matter sort.SliceStable(noLongerBonded, func(i, j int) bool { // -1 means strictly less than - return bytes.Compare(noLongerBonded[i], noLongerBonded[j]) == -1 + return strings.Compare(noLongerBonded[i], noLongerBonded[j]) == -1 }) return noLongerBonded diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 76ca9b30e7..45f331abc2 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -41,7 +41,7 @@ func (k Keeper) GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress return validator, false } - return k.GetValidator(ctx, opAddr) + return k.GetValidator(ctx, sdk.ValAddress(string(opAddr))) } func (k Keeper) mustGetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) types.Validator { @@ -67,7 +67,7 @@ func (k Keeper) SetValidatorByConsAddr(ctx sdk.Context, validator types.Validato return err } store := ctx.KVStore(k.storeKey) - store.Set(types.GetValidatorByConsAddrKey(consPk), validator.GetOperator()) + store.Set(types.GetValidatorByConsAddrKey(consPk), validator.GetOperator().Bytes()) return nil } @@ -79,7 +79,7 @@ func (k Keeper) SetValidatorByPowerIndex(ctx sdk.Context, validator types.Valida } store := ctx.KVStore(k.storeKey) - store.Set(types.GetValidatorsByPowerIndexKey(validator), validator.GetOperator()) + store.Set(types.GetValidatorsByPowerIndexKey(validator), validator.GetOperator().Bytes()) } // validator index @@ -91,7 +91,7 @@ func (k Keeper) DeleteValidatorByPowerIndex(ctx sdk.Context, validator types.Val // validator index func (k Keeper) SetNewValidatorByPowerIndex(ctx sdk.Context, validator types.Validator) { store := ctx.KVStore(k.storeKey) - store.Set(types.GetValidatorsByPowerIndexKey(validator), validator.GetOperator()) + store.Set(types.GetValidatorsByPowerIndexKey(validator), validator.GetOperator().Bytes()) } // Update the tokens of an existing validator, update the validators power index key @@ -222,7 +222,7 @@ func (k Keeper) GetBondedValidatorsByPower(ctx sdk.Context) []types.Validator { i := 0 for ; iterator.Valid() && i < int(maxValidators); iterator.Next() { - address := iterator.Value() + address := sdk.ValAddress(string(iterator.Value())) validator := k.mustGetValidator(ctx, address) if validator.IsBonded() { @@ -318,7 +318,7 @@ func (k Keeper) GetLastValidators(ctx sdk.Context) (validators []types.Validator } address := types.AddressFromLastValidatorPowerKey(iterator.Key()) - validator := k.mustGetValidator(ctx, address) + validator := k.mustGetValidator(ctx, sdk.ValAddress(string(address))) validators[i] = validator i++ @@ -423,10 +423,7 @@ func (k Keeper) UnbondAllMatureValidators(ctx sdk.Context) { k.cdc.MustUnmarshalBinaryBare(unbondingValIterator.Value(), &addrs) for _, valAddr := range addrs.Addresses { - addr, err := sdk.ValAddressFromBech32(valAddr) - if err != nil { - panic(err) - } + addr := sdk.ValAddress(valAddr) val, found := k.GetValidator(ctx, addr) if !found { panic("validator in the unbonding queue was not found") diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index a927a9f971..0fd9f25292 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -49,7 +49,7 @@ func initValidators(t testing.TB, power int64, numAddrs int, powers []int64) (*s vs := make([]types.Validator, len(powers)) for i, power := range powers { - vs[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), pks[i]) + vs[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), pks[i]) tokens := sdk.TokensFromConsensusPower(power) vs[i], _ = vs[i].AddTokensFromDel(tokens) } @@ -60,7 +60,7 @@ func TestSetValidator(t *testing.T) { app, ctx, _, _ := bootstrapValidatorTest(t, 10, 100) valPubKey := PKs[0] - valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(valPubKey.Address()) valTokens := sdk.TokensFromConsensusPower(10) // test how the validator is set from a purely unbonbed pool @@ -204,9 +204,9 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // require all the validators have their respective statuses for valIdx, status := range expectedValStatus { valAddr := validators[valIdx].OperatorAddress - addr, err := sdk.ValAddressFromBech32(valAddr) + err := sdk.ValidateValAddress(valAddr) assert.NoError(t, err) - val, _ := app.StakingKeeper.GetValidator(ctx, addr) + val, _ := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(valAddr)) assert.Equal( t, status, val.GetStatus(), @@ -238,7 +238,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { require.Equal(t, valTokens, validator.Tokens, "\nvalidator %v\npool %v", validator, valTokens) // slash the validator by 100% - app.StakingKeeper.Slash(ctx, sdk.ConsAddress(PKs[0].Address()), 0, 100, sdk.OneDec()) + app.StakingKeeper.Slash(ctx, sdk.BytesToConsAddress(PKs[0].Address()), 0, 100, sdk.OneDec()) // apply TM updates applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) // validator should be unbonding @@ -282,7 +282,7 @@ func TestValidatorBasics(t *testing.T) { assert.True(ValEq(t, validators[0], resVal)) // retrieve from consensus - resVal, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.ConsAddress(PKs[0].Address())) + resVal, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.BytesToConsAddress(PKs[0].Address())) require.True(t, found) assert.True(ValEq(t, validators[0], resVal)) resVal, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) @@ -359,7 +359,7 @@ func TestGetValidatorSortingUnmixed(t *testing.T) { n := len(amts) var validators [5]types.Validator for i, amt := range amts { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) + validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) validators[i].Status = types.Bonded validators[i].Tokens = amt validators[i].DelegatorShares = sdk.NewDecFromInt(amt) @@ -455,22 +455,22 @@ func TestGetValidatorSortingMixed(t *testing.T) { var validators [5]types.Validator for i, amt := range amts { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) + validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) validators[i].DelegatorShares = sdk.NewDecFromInt(amt) validators[i].Status = types.Bonded validators[i].Tokens = amt keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[i], true) } - val0, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[0])) + val0, found := app.StakingKeeper.GetValidator(ctx, addrs[0].ToValAddress()) require.True(t, found) - val1, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[1])) + val1, found := app.StakingKeeper.GetValidator(ctx, addrs[1].ToValAddress()) require.True(t, found) - val2, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[2])) + val2, found := app.StakingKeeper.GetValidator(ctx, addrs[2].ToValAddress()) require.True(t, found) - val3, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[3])) + val3, found := app.StakingKeeper.GetValidator(ctx, addrs[3].ToValAddress()) require.True(t, found) - val4, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[4])) + val4, found := app.StakingKeeper.GetValidator(ctx, addrs[4].ToValAddress()) require.True(t, found) require.Equal(t, types.Bonded, val0.Status) require.Equal(t, types.Unbonding, val1.Status) @@ -503,7 +503,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { var validators [4]types.Validator for i, power := range powers { moniker := fmt.Sprintf("val#%d", int64(i)) - validators[i] = newMonikerValidator(t, sdk.ValAddress(addrs[i]), PKs[i], moniker) + validators[i] = newMonikerValidator(t, addrs[i].ToValAddress(), PKs[i], moniker) tokens := sdk.TokensFromConsensusPower(power) validators[i], _ = validators[i].AddTokensFromDel(tokens) @@ -617,9 +617,9 @@ func TestValidatorBondHeight(t *testing.T) { // initialize some validators into the state var validators [3]types.Validator - validators[0] = teststaking.NewValidator(t, sdk.ValAddress(PKs[0].Address().Bytes()), PKs[0]) - validators[1] = teststaking.NewValidator(t, sdk.ValAddress(addrs[1]), PKs[1]) - validators[2] = teststaking.NewValidator(t, sdk.ValAddress(addrs[2]), PKs[2]) + validators[0] = teststaking.NewValidator(t, sdk.BytesToValAddress(PKs[0].Address()), PKs[0]) + validators[1] = teststaking.NewValidator(t, addrs[1].ToValAddress(), PKs[1]) + validators[2] = teststaking.NewValidator(t, addrs[2].ToValAddress(), PKs[2]) tokens0 := sdk.TokensFromConsensusPower(200) tokens1 := sdk.TokensFromConsensusPower(100) @@ -665,7 +665,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { powers := []int64{0, 100, 400, 400, 200} var validators [5]types.Validator for i, power := range powers { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) + validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) tokens := sdk.TokensFromConsensusPower(power) validators[i], _ = validators[i].AddTokensFromDel(tokens) keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[i], true) @@ -703,7 +703,7 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) { var validators [2]types.Validator for i, power := range powers { valPubKey := PKs[i+1] - valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(valPubKey.Address()) validators[i] = teststaking.NewValidator(t, valAddr, valPubKey) tokens := sdk.TokensFromConsensusPower(power) @@ -731,7 +731,7 @@ func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) { powers := []int64{10, 20} var validators [2]types.Validator for i, power := range powers { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) + validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) tokens := sdk.TokensFromConsensusPower(power) validators[i], _ = validators[i].AddTokensFromDel(tokens) @@ -754,7 +754,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) { powers := []int64{10, 20} var validators [2]types.Validator for i, power := range powers { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) + validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) tokens := sdk.TokensFromConsensusPower(power) validators[i], _ = validators[i].AddTokensFromDel(tokens) @@ -839,7 +839,7 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { powers := []int64{10, 20, 5} var validators [5]types.Validator for i, power := range powers { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) + validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) tokens := sdk.TokensFromConsensusPower(power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } @@ -872,7 +872,7 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { powers := []int64{100, 100} var validators [2]types.Validator for i, power := range powers { - validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) + validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) tokens := sdk.TokensFromConsensusPower(power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } @@ -916,7 +916,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // initialize some validators into the state for i, power := range powers { valPubKey := PKs[i+1] - valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(valPubKey.Address()) validators[i] = teststaking.NewValidator(t, valAddr, valPubKey) tokens := sdk.TokensFromConsensusPower(power) @@ -949,7 +949,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // add a new validator that goes from zero power, to non-zero power, back to // zero power valPubKey := PKs[len(validators)+1] - valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(valPubKey.Address()) amt := sdk.NewInt(100) validator := teststaking.NewValidator(t, valAddr, valPubKey) @@ -963,7 +963,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // add a new validator that increases in power valPubKey = PKs[len(validators)+2] - valAddr = sdk.ValAddress(valPubKey.Address().Bytes()) + valAddr = sdk.BytesToValAddress(valPubKey.Address()) validator = teststaking.NewValidator(t, valAddr, valPubKey) tokens := sdk.TokensFromConsensusPower(500) @@ -995,7 +995,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { for i, power := range powers { moniker := fmt.Sprintf("%d", i) valPubKey := PKs[i+1] - valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(valPubKey.Address()) validators[i] = newMonikerValidator(t, valAddr, valPubKey, moniker) tokens := sdk.TokensFromConsensusPower(power) diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 4f111e34df..b524d71781 100644 --- a/x/staking/simulation/decoder_test.go +++ b/x/staking/simulation/decoder_test.go @@ -19,8 +19,8 @@ import ( var ( delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) + delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) + valAddr1 = sdk.BytesToValAddress(delPk1.Address()) ) func makeTestCodec() (cdc *codec.LegacyAmino) { diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 60ed674f41..27399d8930 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -74,7 +74,7 @@ func RandomizedGenState(simState *module.SimulationState) { valAddrs := make([]sdk.ValAddress, simState.NumBonded) for i := 0; i < int(simState.NumBonded); i++ { - valAddr := sdk.ValAddress(simState.Accounts[i].Address) + valAddr := simState.Accounts[i].Address.ToValAddress() valAddrs[i] = valAddr maxCommission := sdk.NewDecWithPrec(int64(simulation.RandIntBetween(simState.Rand, 1, 100)), 2) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 5ef103e4a7..7b4b31c1a8 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -98,7 +98,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { simAccount, _ := simtypes.RandomAcc(r, accs) - address := sdk.ValAddress(simAccount.Address) + address := simAccount.Address.ToValAddress() // ensure the validator doesn't exist already _, found := k.GetValidator(ctx, address) @@ -201,7 +201,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgEditValidator, "invalid commission rate"), nil, nil } - simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, val.GetOperator().ToAccAddress()) if !found { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgEditValidator, "unable to find account"), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index 3429413371..e4197dffc9 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -232,9 +232,9 @@ func TestSimulateMsgBeginRedelegate(t *testing.T) { // setup accounts[2] as delegator delegator := accounts[2] - delegation := types.NewDelegation(delegator.Address, validator1.GetOperator(), issuedShares) + delegation := types.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) - app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator1.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) + app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) setupValidatorRewards(app, ctx, validator0.GetOperator()) setupValidatorRewards(app, ctx, validator1.GetOperator()) @@ -243,6 +243,8 @@ func TestSimulateMsgBeginRedelegate(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: ostproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}}) // execute operation + // SimulateMsgBeginRedelegate selects a validator randomly, so this test code was modified such that + // two validator addresses switched into each other op := simulation.SimulateMsgBeginRedelegate(app.AccountKeeper, app.BankKeeper, app.StakingKeeper) operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "") require.NoError(t, err) @@ -255,10 +257,9 @@ func TestSimulateMsgBeginRedelegate(t *testing.T) { require.Equal(t, "489348507626016866", msg.Amount.Amount.String()) require.Equal(t, "stake", msg.Amount.Denom) require.Equal(t, types.TypeMsgBeginRedelegate, msg.Type()) - require.Equal(t, "linkvaloper1h6a7shta7jyc72hyznkys683z98z36e0qrqd3d", msg.ValidatorDstAddress) - require.Equal(t, "linkvaloper17s94pzwhsn4ah25tec27w70n65h5t2sc2g5u4z", msg.ValidatorSrcAddress) + require.Equal(t, "linkvaloper17s94pzwhsn4ah25tec27w70n65h5t2sc2g5u4z", msg.ValidatorDstAddress) + require.Equal(t, "linkvaloper1h6a7shta7jyc72hyznkys683z98z36e0qrqd3d", msg.ValidatorSrcAddress) require.Len(t, futureOperations, 0) - } // returns context and an app with updated mint keeper @@ -303,7 +304,7 @@ func getTestingValidator1(t *testing.T, app *simapp.SimApp, ctx sdk.Context, acc func getTestingValidator(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account, commission types.Commission, n int) types.Validator { account := accounts[n] valPubKey := account.PubKey - valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) + valAddr := sdk.BytesToValAddress(account.PubKey.Address()) validator := teststaking.NewValidator(t, valAddr, valPubKey) validator, err := validator.SetInitialCommission(commission) require.NoError(t, err) diff --git a/x/staking/types/data_test.go b/x/staking/types/data_test.go index f91963e3a7..aeed2a3109 100644 --- a/x/staking/types/data_test.go +++ b/x/staking/types/data_test.go @@ -14,12 +14,12 @@ var ( pk1Any *codectypes.Any pk2 = ed25519.GenPrivKey().PubKey() pk3 = ed25519.GenPrivKey().PubKey() - addr1, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk1.Address().Bytes()) - addr2, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk2.Address().Bytes()) - addr3, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk3.Address().Bytes()) - valAddr1 = sdk.ValAddress(pk1.Address()) - valAddr2 = sdk.ValAddress(pk2.Address()) - valAddr3 = sdk.ValAddress(pk3.Address()) + addr1, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk1.Address()) + addr2, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk2.Address()) + addr3, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk3.Address()) + valAddr1 = sdk.BytesToValAddress(pk1.Address()) + valAddr2 = sdk.BytesToValAddress(pk2.Address()) + valAddr3 = sdk.BytesToValAddress(pk3.Address()) emptyAddr sdk.ValAddress emptyPubkey cryptotypes.PubKey diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index df85b5a787..c45435a5a0 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -60,19 +60,17 @@ func UnmarshalDelegation(cdc codec.BinaryMarshaler, value []byte) (delegation De } func (d Delegation) GetDelegatorAddr() sdk.AccAddress { - delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) - if err != nil { - panic(err) - } - return delAddr + return sdk.AccAddress(d.DelegatorAddress) } + func (d Delegation) GetValidatorAddr() sdk.ValAddress { - addr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) + err := sdk.ValidateValAddress(d.ValidatorAddress) if err != nil { panic(err) } - return addr + return sdk.ValAddress(d.ValidatorAddress) } + func (d Delegation) GetShares() sdk.Dec { return d.Shares } // String returns a human readable string representation of a Delegation. diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 3154c4df64..7fa901b7f7 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "fmt" "strconv" + "strings" "time" sdk "github.com/line/lfb-sdk/types" @@ -46,6 +47,8 @@ var ( ValidatorQueueKey = []byte{0x43} // prefix for the timestamps in validator queue HistoricalInfoKey = []byte{0x50} // prefix for the historical info + + AddressDelimiter = "," ) // gets the key for the validator with address @@ -81,21 +84,17 @@ func GetValidatorsByPowerIndexKey(validator Validator) []byte { powerBytesLen := len(powerBytes) // 8 // key is of format prefix || powerbytes || addrBytes - key := make([]byte, 1+powerBytesLen+sdk.AddrLen) + key := make([]byte, 1+powerBytesLen) key[0] = ValidatorsByPowerIndexKey[0] copy(key[1:powerBytesLen+1], powerBytes) - addr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) - if err != nil { - panic(err) - } - operAddrInvr := sdk.CopyBytes(addr) + operAddrInvr := sdk.CopyBytes([]byte(validator.OperatorAddress)) for i, b := range operAddrInvr { operAddrInvr[i] = ^b } - copy(key[powerBytesLen+1:], operAddrInvr) + key = append(key, operAddrInvr...) return key } @@ -108,9 +107,6 @@ func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte { // parse the validators operator address from power rank key func ParseValidatorPowerRankKey(key []byte) (operAddr []byte) { powerBytesLen := 8 - if len(key) != 1+powerBytesLen+sdk.AddrLen { - panic("Invalid validator power rank key length") - } operAddr = sdk.CopyBytes(key[powerBytesLen+1:]) @@ -168,7 +164,7 @@ func ParseValidatorQueueKey(bz []byte) (time.Time, int64, error) { // gets the key for delegator bond with validator // VALUE: staking/Delegation func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return append(GetDelegationsKey(delAddr), valAddr.Bytes()...) + return append(append(GetDelegationsKey(delAddr), AddressDelimiter...), valAddr.Bytes()...) } // gets the prefix for a delegator for all validators @@ -179,28 +175,20 @@ func GetDelegationsKey(delAddr sdk.AccAddress) []byte { // gets the key for an unbonding delegation by delegator and validator addr // VALUE: staking/UnbondingDelegation func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return append( - GetUBDsKey(delAddr.Bytes()), - valAddr.Bytes()...) + return append(append(GetUBDsKey(delAddr), AddressDelimiter...), valAddr...) } // gets the index-key for an unbonding delegation, stored by validator-index // VALUE: none (key rearrangement used) func GetUBDByValIndexKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return append(GetUBDsByValIndexKey(valAddr), delAddr.Bytes()...) + return append(append(GetUBDsByValIndexKey(valAddr), AddressDelimiter...), delAddr...) } // rearranges the ValIndexKey to get the UBDKey func GetUBDKeyFromValIndexKey(indexKey []byte) []byte { addrs := indexKey[1:] // remove prefix bytes - if len(addrs) != 2*sdk.AddrLen { - panic("unexpected key length") - } - - valAddr := addrs[:sdk.AddrLen] - delAddr := addrs[sdk.AddrLen:] - - return GetUBDKey(delAddr, valAddr) + addresses := strings.Split(string(addrs), AddressDelimiter) + return GetUBDKey(sdk.AccAddress(addresses[1]), sdk.ValAddress(addresses[0])) } // gets the prefix for all unbonding delegations from a delegator @@ -222,11 +210,10 @@ func GetUnbondingDelegationTimeKey(timestamp time.Time) []byte { // GetREDKey returns a key prefix for indexing a redelegation from a delegator // and source validator to a destination validator. func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { - key := make([]byte, 1+sdk.AddrLen*3) + key := GetREDsKey(delAddr) - copy(key[0:sdk.AddrLen+1], GetREDsKey(delAddr.Bytes())) - copy(key[sdk.AddrLen+1:2*sdk.AddrLen+1], valSrcAddr.Bytes()) - copy(key[2*sdk.AddrLen+1:3*sdk.AddrLen+1], valDstAddr.Bytes()) + key = append(append(key, AddressDelimiter...), valSrcAddr...) + key = append(append(key, AddressDelimiter...), valDstAddr...) return key } @@ -235,13 +222,10 @@ func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) [] // VALUE: none (key rearrangement used) func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { REDSFromValsSrcKey := GetREDsFromValSrcIndexKey(valSrcAddr) - offset := len(REDSFromValsSrcKey) // key is of the form REDSFromValsSrcKey || delAddr || valDstAddr - key := make([]byte, len(REDSFromValsSrcKey)+2*sdk.AddrLen) - copy(key[0:offset], REDSFromValsSrcKey) - copy(key[offset:offset+sdk.AddrLen], delAddr.Bytes()) - copy(key[offset+sdk.AddrLen:offset+2*sdk.AddrLen], valDstAddr.Bytes()) + key := append(append(REDSFromValsSrcKey, AddressDelimiter...), delAddr...) + key = append(append(key, AddressDelimiter...), valDstAddr...) return key } @@ -250,13 +234,10 @@ func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.V // VALUE: none (key rearrangement used) func GetREDByValDstIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { REDSToValsDstKey := GetREDsToValDstIndexKey(valDstAddr) - offset := len(REDSToValsDstKey) // key is of the form REDSToValsDstKey || delAddr || valSrcAddr - key := make([]byte, len(REDSToValsDstKey)+2*sdk.AddrLen) - copy(key[0:offset], REDSToValsDstKey) - copy(key[offset:offset+sdk.AddrLen], delAddr.Bytes()) - copy(key[offset+sdk.AddrLen:offset+2*sdk.AddrLen], valSrcAddr.Bytes()) + key := append(append(REDSToValsDstKey, AddressDelimiter...), delAddr...) + key = append(append(key, AddressDelimiter...), valSrcAddr...) return key } @@ -264,29 +245,25 @@ func GetREDByValDstIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.V // GetREDKeyFromValSrcIndexKey rearranges the ValSrcIndexKey to get the REDKey func GetREDKeyFromValSrcIndexKey(indexKey []byte) []byte { // note that first byte is prefix byte - if len(indexKey) != 3*sdk.AddrLen+1 { - panic("unexpected key length") - } - - valSrcAddr := indexKey[1 : sdk.AddrLen+1] - delAddr := indexKey[sdk.AddrLen+1 : 2*sdk.AddrLen+1] - valDstAddr := indexKey[2*sdk.AddrLen+1 : 3*sdk.AddrLen+1] + addrs := indexKey[1:] // remove prefix bytes - return GetREDKey(delAddr, valSrcAddr, valDstAddr) + addresses := strings.Split(string(addrs), AddressDelimiter) + if len(addresses) != 3 { + panic(fmt.Sprintf("%s does not contain three addresses", addrs)) + } + return GetREDKey(sdk.AccAddress(addresses[1]), sdk.ValAddress(addresses[0]), sdk.ValAddress(addresses[2])) } // GetREDKeyFromValDstIndexKey rearranges the ValDstIndexKey to get the REDKey func GetREDKeyFromValDstIndexKey(indexKey []byte) []byte { // note that first byte is prefix byte - if len(indexKey) != 3*sdk.AddrLen+1 { - panic("unexpected key length") - } - - valDstAddr := indexKey[1 : sdk.AddrLen+1] - delAddr := indexKey[sdk.AddrLen+1 : 2*sdk.AddrLen+1] - valSrcAddr := indexKey[2*sdk.AddrLen+1 : 3*sdk.AddrLen+1] + addrs := indexKey[1:] // remove prefix bytes - return GetREDKey(delAddr, valSrcAddr, valDstAddr) + addresses := strings.Split(string(addrs), AddressDelimiter) + if len(addresses) != 3 { + panic(fmt.Sprintf("%s does not contain three addresses", addrs)) + } + return GetREDKey(sdk.AccAddress(addresses[1]), sdk.ValAddress(addresses[2]), sdk.ValAddress(addresses[0])) } // GetRedelegationTimeKey returns a key prefix for indexing an unbonding @@ -317,7 +294,7 @@ func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte { // GetREDsByDelToValDstIndexKey returns a key prefix for indexing a redelegation // from an address to a source validator. func GetREDsByDelToValDstIndexKey(delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) []byte { - return append(GetREDsToValDstIndexKey(valDstAddr), delAddr.Bytes()...) + return append(append(GetREDsToValDstIndexKey(valDstAddr), AddressDelimiter...), delAddr.Bytes()...) } // GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects. diff --git a/x/staking/types/keys_test.go b/x/staking/types/keys_test.go index b64c8b20c5..e65929dc98 100644 --- a/x/staking/types/keys_test.go +++ b/x/staking/types/keys_test.go @@ -24,7 +24,7 @@ var ( ) func TestGetValidatorPowerRank(t *testing.T) { - valAddr1 := sdk.ValAddress(keysAddr1) + valAddr1 := sdk.BytesToValAddress(keysAddr1) val1 := newValidator(t, valAddr1, keysPK1) val1.Tokens = sdk.ZeroInt() val2, val3, val4 := val1, val1, val1 @@ -37,10 +37,10 @@ func TestGetValidatorPowerRank(t *testing.T) { validator types.Validator wantHex string }{ - {val1, "2300000000000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"}, - {val2, "2300000000000000019c288ede7df62742fc3b7d0962045a8cef0f79f6"}, - {val3, "23000000000000000a9c288ede7df62742fc3b7d0962045a8cef0f79f6"}, - {val4, "2300000100000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"}, + {val1, "23000000000000000093969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, + {val2, "23000000000000000193969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, + {val3, "23000000000000000a93969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, + {val4, "23000001000000000093969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, } for i, tt := range tests { got := hex.EncodeToString(types.GetValidatorsByPowerIndexKey(tt.validator)) @@ -56,12 +56,12 @@ func TestGetREDByValDstIndexKey(t *testing.T) { valDstAddr sdk.ValAddress wantHex string }{ - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), - "3663d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f08609"}, - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), - "363ab62f0d93849be495e21e3e9013a517038f45bd63d771218209d8bd03c482f69dfba57310f086095ef3b5f25c54946d4a89fc0d09d2f126614540f2"}, - {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), - "363ab62f0d93849be495e21e3e9013a517038f45bd5ef3b5f25c54946d4a89fc0d09d2f126614540f263d771218209d8bd03c482f69dfba57310f08609"}, + {sdk.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), + "366c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d39326667392c6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b2c6c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d3932666739"}, + {sdk.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr2), sdk.BytesToValAddress(keysAddr3), + "366c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a757063373364613074633273342c6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b2c6c696e6b76616c6f70657231746d656d74756a75326a3278366a35666c7378736e356833796573353273386a7a37736e7777"}, + {sdk.BytesToAccAddress(keysAddr2), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr3), + "366c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a757063373364613074633273342c6c696e6b31746d656d74756a75326a3278366a35666c7378736e356833796573353273386a73326a7771612c6c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d3932666739"}, } for i, tt := range tests { got := hex.EncodeToString(types.GetREDByValDstIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) @@ -77,12 +77,12 @@ func TestGetREDByValSrcIndexKey(t *testing.T) { valDstAddr sdk.ValAddress wantHex string }{ - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), - "3563d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f0860963d771218209d8bd03c482f69dfba57310f08609"}, - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), - "355ef3b5f25c54946d4a89fc0d09d2f126614540f263d771218209d8bd03c482f69dfba57310f086093ab62f0d93849be495e21e3e9013a517038f45bd"}, - {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), - "3563d771218209d8bd03c482f69dfba57310f086095ef3b5f25c54946d4a89fc0d09d2f126614540f23ab62f0d93849be495e21e3e9013a517038f45bd"}, + {sdk.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), + "356c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d39326667392c6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b2c6c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d3932666739"}, + {sdk.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr2), sdk.BytesToValAddress(keysAddr3), + "356c696e6b76616c6f70657231746d656d74756a75326a3278366a35666c7378736e356833796573353273386a7a37736e77772c6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b2c6c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a75706337336461307463327334"}, + {sdk.BytesToAccAddress(keysAddr2), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr3), + "356c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d39326667392c6c696e6b31746d656d74756a75326a3278366a35666c7378736e356833796573353273386a73326a7771612c6c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a75706337336461307463327334"}, } for i, tt := range tests { got := hex.EncodeToString(types.GetREDByValSrcIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index ba48e22e12..19728f00c9 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -43,7 +43,7 @@ func NewMsgCreateValidator( } return &MsgCreateValidator{ Description: description, - DelegatorAddress: sdk.AccAddress(valAddr).String(), + DelegatorAddress: valAddr.ToAccAddress().String(), ValidatorAddress: valAddr.String(), Pubkey: pkAny, Value: selfDelegation, @@ -64,17 +64,10 @@ func (msg MsgCreateValidator) Type() string { return TypeMsgCreateValidator } // sign the msg as well. func (msg MsgCreateValidator) GetSigners() []sdk.AccAddress { // delegator is first signer so delegator pays fees - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) - if err != nil { - panic(err) - } - addrs := []sdk.AccAddress{delAddr} - addr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if err != nil { - panic(err) - } - if !bytes.Equal(delAddr.Bytes(), addr.Bytes()) { - addrs = append(addrs, sdk.AccAddress(addr)) + addrs := []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} + valAddr := sdk.ValAddress(msg.ValidatorAddress).ToAccAddress() + if !addrs[0].Equals(valAddr) { + addrs = append(addrs, valAddr) } return addrs @@ -89,11 +82,11 @@ func (msg MsgCreateValidator) GetSignBytes() []byte { // ValidateBasic implements the sdk.Msg interface. func (msg MsgCreateValidator) ValidateBasic() error { // note that unmarshaling from bech32 ensures either empty or valid - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + delAddrBytes, err := sdk.AccAddressToBytes(msg.DelegatorAddress) if err != nil { return err } - if delAddr.Empty() { + if len(delAddrBytes) == 0 { return ErrEmptyDelegatorAddr } @@ -101,11 +94,11 @@ func (msg MsgCreateValidator) ValidateBasic() error { return ErrEmptyValidatorAddr } - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + valAddrBytes, err := sdk.ValAddressToBytes(msg.ValidatorAddress) if err != nil { return err } - if !sdk.AccAddress(valAddr).Equals(delAddr) { + if !bytes.Equal(delAddrBytes, valAddrBytes) { return ErrBadValidatorAddr } @@ -165,11 +158,7 @@ func (msg MsgEditValidator) Type() string { return TypeMsgEditValidator } // GetSigners implements the sdk.Msg interface. func (msg MsgEditValidator) GetSigners() []sdk.AccAddress { - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) - if err != nil { - panic(err) - } - return []sdk.AccAddress{valAddr.Bytes()} + return []sdk.AccAddress{sdk.ValAddress(msg.ValidatorAddress).ToAccAddress()} } // GetSignBytes implements the sdk.Msg interface. @@ -183,6 +172,9 @@ func (msg MsgEditValidator) ValidateBasic() error { if msg.ValidatorAddress == "" { return ErrEmptyValidatorAddr } + if err := sdk.ValidateValAddress(msg.ValidatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid validator address (%s)", err) + } if msg.Description == (Description{}) { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "empty description") @@ -219,11 +211,11 @@ func (msg MsgDelegate) Type() string { return TypeMsgDelegate } // GetSigners implements the sdk.Msg interface. func (msg MsgDelegate) GetSigners() []sdk.AccAddress { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + err := sdk.ValidateAccAddress(msg.DelegatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{delAddr} + return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} } // GetSignBytes implements the sdk.Msg interface. @@ -237,10 +229,16 @@ func (msg MsgDelegate) ValidateBasic() error { if msg.DelegatorAddress == "" { return ErrEmptyDelegatorAddr } + if err := sdk.ValidateAccAddress(msg.DelegatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid delegator address (%s)", err) + } if msg.ValidatorAddress == "" { return ErrEmptyValidatorAddr } + if err := sdk.ValidateValAddress(msg.ValidatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid validator address (%s)", err) + } if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { return ErrBadDelegationAmount @@ -270,11 +268,11 @@ func (msg MsgBeginRedelegate) Type() string { return TypeMsgBeginRedelegate } // GetSigners implements the sdk.Msg interface func (msg MsgBeginRedelegate) GetSigners() []sdk.AccAddress { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + err := sdk.ValidateAccAddress(msg.DelegatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{delAddr} + return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} } // GetSignBytes implements the sdk.Msg interface. @@ -288,14 +286,23 @@ func (msg MsgBeginRedelegate) ValidateBasic() error { if msg.DelegatorAddress == "" { return ErrEmptyDelegatorAddr } + if err := sdk.ValidateAccAddress(msg.DelegatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid delegator address (%s)", err) + } if msg.ValidatorSrcAddress == "" { return ErrEmptyValidatorAddr } + if err := sdk.ValidateValAddress(msg.ValidatorSrcAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid source validator address (%s)", err) + } if msg.ValidatorDstAddress == "" { return ErrEmptyValidatorAddr } + if err := sdk.ValidateValAddress(msg.ValidatorDstAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid destination validator address (%s)", err) + } if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { return ErrBadSharesAmount @@ -322,11 +329,11 @@ func (msg MsgUndelegate) Type() string { return TypeMsgUndelegate } // GetSigners implements the sdk.Msg interface. func (msg MsgUndelegate) GetSigners() []sdk.AccAddress { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + err := sdk.ValidateAccAddress(msg.DelegatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{delAddr} + return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} } // GetSignBytes implements the sdk.Msg interface. @@ -340,10 +347,16 @@ func (msg MsgUndelegate) ValidateBasic() error { if msg.DelegatorAddress == "" { return ErrEmptyDelegatorAddr } + if err := sdk.ValidateAccAddress(msg.DelegatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid delegator address (%s)", err) + } if msg.ValidatorAddress == "" { return ErrEmptyValidatorAddr } + if err := sdk.ValidateValAddress(msg.ValidatorAddress); err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid validator address (%s)", err) + } if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() { return ErrBadSharesAmount diff --git a/x/staking/types/msg_test.go b/x/staking/types/msg_test.go index 519cacffa0..c399243af1 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -127,12 +127,12 @@ func TestMsgDelegate(t *testing.T) { bond sdk.Coin expectPass bool }{ - {"basic good", sdk.AccAddress(valAddr1), valAddr2, coinPos, true}, - {"self bond", sdk.AccAddress(valAddr1), valAddr1, coinPos, true}, - {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, coinPos, false}, - {"empty validator", sdk.AccAddress(valAddr1), emptyAddr, coinPos, false}, - {"empty bond", sdk.AccAddress(valAddr1), valAddr2, coinZero, false}, - {"nil bold", sdk.AccAddress(valAddr1), valAddr2, sdk.Coin{}, false}, + {"basic good", valAddr1.ToAccAddress(), valAddr2, coinPos, true}, + {"self bond", valAddr1.ToAccAddress(), valAddr1, coinPos, true}, + {"empty delegator", emptyAddr.ToAccAddress(), valAddr1, coinPos, false}, + {"empty validator", valAddr1.ToAccAddress(), emptyAddr, coinPos, false}, + {"empty bond", valAddr1.ToAccAddress(), valAddr2, coinZero, false}, + {"nil bold", valAddr1.ToAccAddress(), valAddr2, sdk.Coin{}, false}, } for _, tc := range tests { @@ -155,12 +155,12 @@ func TestMsgBeginRedelegate(t *testing.T) { amount sdk.Coin expectPass bool }{ - {"regular", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, - {"zero amount", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, - {"nil amount", sdk.AccAddress(valAddr1), valAddr2, valAddr3, sdk.Coin{}, false}, - {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - {"empty source validator", sdk.AccAddress(valAddr1), emptyAddr, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - {"empty destination validator", sdk.AccAddress(valAddr1), valAddr2, emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, + {"regular", valAddr1.ToAccAddress(), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, + {"zero amount", valAddr1.ToAccAddress(), valAddr2, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, + {"nil amount", valAddr1.ToAccAddress(), valAddr2, valAddr3, sdk.Coin{}, false}, + {"empty delegator", emptyAddr.ToAccAddress(), valAddr1, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, + {"empty source validator", valAddr1.ToAccAddress(), emptyAddr, valAddr3, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, + {"empty destination validator", valAddr1.ToAccAddress(), valAddr2, emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, } for _, tc := range tests { @@ -182,11 +182,11 @@ func TestMsgUndelegate(t *testing.T) { amount sdk.Coin expectPass bool }{ - {"regular", sdk.AccAddress(valAddr1), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, - {"zero amount", sdk.AccAddress(valAddr1), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, - {"nil amount", sdk.AccAddress(valAddr1), valAddr2, sdk.Coin{}, false}, - {"empty delegator", sdk.AccAddress(emptyAddr), valAddr1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, - {"empty validator", sdk.AccAddress(valAddr1), emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, + {"regular", valAddr1.ToAccAddress(), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), true}, + {"zero amount", valAddr1.ToAccAddress(), valAddr2, sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), false}, + {"nil amount", valAddr1.ToAccAddress(), valAddr2, sdk.Coin{}, false}, + {"empty delegator", emptyAddr.ToAccAddress(), valAddr1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, + {"empty validator", valAddr1.ToAccAddress(), emptyAddr, sdk.NewInt64Coin(sdk.DefaultBondDenom, 1), false}, } for _, tc := range tests { diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 5b423cdaab..42fba7ab00 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -98,7 +98,9 @@ func (v Validators) Len() int { // Implements sort interface func (v Validators) Less(i, j int) bool { - return bytes.Compare(v[i].GetOperator().Bytes(), v[j].GetOperator().Bytes()) == -1 + valIBytes, _ := sdk.ValAddressToBytes(v[i].GetOperator().String()) + valJBytes, _ := sdk.ValAddressToBytes(v[j].GetOperator().String()) + return bytes.Compare(valIBytes, valJBytes) == -1 } // Implements sort interface @@ -124,7 +126,9 @@ func (valz ValidatorsByVotingPower) Less(i, j int) bool { if errI != nil || errJ != nil { return false } - return bytes.Compare(addrI, addrJ) == -1 + bytesI, _ := sdk.ConsAddressToBytes(addrI.String()) + bytesJ, _ := sdk.ConsAddressToBytes(addrJ.String()) + return bytes.Compare(bytesI, bytesJ) == -1 } return valz[i].ConsensusPower() > valz[j].ConsensusPower() } @@ -460,13 +464,9 @@ func (v Validator) GetMoniker() string { return v.Description.Moniker } func (v Validator) GetStatus() BondStatus { return v.Status } func (v Validator) GetOperator() sdk.ValAddress { if v.OperatorAddress == "" { - return nil + return "" } - addr, err := sdk.ValAddressFromBech32(v.OperatorAddress) - if err != nil { - panic(err) - } - return addr + return sdk.ValAddress(v.OperatorAddress) } // ConsPubKey returns the validator PubKey as a cryptotypes.PubKey. @@ -499,10 +499,10 @@ func (v Validator) TmConsPublicKey() (ostprotocrypto.PublicKey, error) { func (v Validator) GetConsAddr() (sdk.ConsAddress, error) { pk, ok := v.ConsensusPubkey.GetCachedValue().(cryptotypes.PubKey) if !ok { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expecting cryptotypes.PubKey, got %T", pk) + return "", sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expecting cryptotypes.PubKey, got %T", pk) } - return sdk.ConsAddress(pk.Address()), nil + return sdk.BytesToConsAddress(pk.Address()), nil } func (v Validator) GetTokens() sdk.Int { return v.Tokens } diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index c48b6167db..2f09a7a2a4 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -251,7 +251,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { // Create random validator slice for i := range vals { pk := ed25519.GenPrivKey().PubKey() - vals[i] = newValidator(t, sdk.ValAddress(pk.Address()), pk) + vals[i] = newValidator(t, sdk.BytesToValAddress(pk.Address()), pk) } // Save sorted copy @@ -278,7 +278,7 @@ func TestValidatorsSortTendermint(t *testing.T) { for i := range vals { pk := ed25519.GenPrivKey().PubKey() pk2 := ed25519.GenPrivKey().PubKey() - vals[i] = newValidator(t, sdk.ValAddress(pk2.Address()), pk) + vals[i] = newValidator(t, sdk.BytesToValAddress(pk2.Address()), pk) vals[i].Status = types.Bonded vals[i].Tokens = sdk.NewInt(rand.Int63()) } @@ -308,7 +308,7 @@ func TestValidatorToTm(t *testing.T) { for i := range vals { pk := ed25519.GenPrivKey().PubKey() - val := newValidator(t, sdk.ValAddress(pk.Address()), pk) + val := newValidator(t, sdk.BytesToValAddress(pk.Address()), pk) val.Status = types.Bonded val.Tokens = sdk.NewInt(rand.Int63()) vals[i] = val diff --git a/x/upgrade/client/rest/tx.go b/x/upgrade/client/rest/tx.go index 45dff9f201..5833aa47ec 100644 --- a/x/upgrade/client/rest/tx.go +++ b/x/upgrade/client/rest/tx.go @@ -71,13 +71,11 @@ func newPostPlanHandler(clientCtx client.Context) http.HandlerFunc { return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if rest.CheckBadRequestError(w, err) { - return - } + fromAddr := sdk.AccAddress(req.BaseReq.From) var t time.Time if req.UpgradeTime != "" { + var err error t, err = time.Parse(time.RFC3339, req.UpgradeTime) if rest.CheckBadRequestError(w, err) { return @@ -111,10 +109,7 @@ func newCancelPlanHandler(clientCtx client.Context) http.HandlerFunc { return } - fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if rest.CheckBadRequestError(w, err) { - return - } + fromAddr := sdk.AccAddress(req.BaseReq.From) content := types.NewCancelSoftwareUpgradeProposal(req.Title, req.Description) diff --git a/x/wasm/client/cli/genesis_msg.go b/x/wasm/client/cli/genesis_msg.go index 6a728431bd..cd2a2dfe20 100644 --- a/x/wasm/client/cli/genesis_msg.go +++ b/x/wasm/client/cli/genesis_msg.go @@ -276,11 +276,11 @@ func getAllCodes(state *types.GenesisState) ([]codeMeta, error) { accessConfig = *msg.InstantiatePermission } else { // default - creator, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, fmt.Errorf("sender: %s", err) } - accessConfig = state.Params.InstantiateDefaultPermission.With(creator) + accessConfig = state.Params.InstantiateDefaultPermission.With(sdk.AccAddress(msg.Sender)) } hash := sha256.Sum256(msg.WASMByteCode) all = append(all, codeMeta{ @@ -484,15 +484,15 @@ func codeSeqValue(state *types.GenesisState) uint64 { func getActorAddress(cmd *cobra.Command) (sdk.AccAddress, error) { actorArg, err := cmd.Flags().GetString(flagRunAs) if err != nil { - return nil, fmt.Errorf("run-as: %s", err.Error()) + return "", fmt.Errorf("run-as: %s", err.Error()) } if len(actorArg) == 0 { - return nil, errors.New("run-as address is required") + return "", errors.New("run-as address is required") } - actorAddr, err := sdk.AccAddressFromBech32(actorArg) + err = sdk.ValidateAccAddress(actorArg) if err == nil { - return actorAddr, nil + return sdk.AccAddress(actorArg), nil } inBuf := bufio.NewReader(cmd.InOrStdin()) keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) @@ -501,12 +501,12 @@ func getActorAddress(cmd *cobra.Command) (sdk.AccAddress, error) { // attempt to lookup address from Keybase if no address was provided kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, homeDir, inBuf) if err != nil { - return nil, err + return "", err } info, err := kb.Key(actorArg) if err != nil { - return nil, fmt.Errorf("failed to get address from Keybase: %w", err) + return "", fmt.Errorf("failed to get address from Keybase: %w", err) } return info.GetAddress(), nil } @@ -524,5 +524,5 @@ func addrFromUint64(id uint64) sdk.AccAddress { addr := make([]byte, 20) addr[0] = 'C' binary.PutUvarint(addr[1:], id) - return sdk.AccAddress(crypto.AddressHash(addr)) + return sdk.BytesToAccAddress(crypto.AddressHash(addr)) } diff --git a/x/wasm/client/cli/query.go b/x/wasm/client/cli/query.go index 05d3e97798..360e4fb710 100644 --- a/x/wasm/client/cli/query.go +++ b/x/wasm/client/cli/query.go @@ -167,7 +167,7 @@ func GetCmdGetContractInfo() *cobra.Command { return err } - _, err = sdk.AccAddressFromBech32(args[0]) + err = sdk.ValidateAccAddress(args[0]) if err != nil { return err } @@ -218,7 +218,7 @@ func GetCmdGetContractStateAll() *cobra.Command { return err } - _, err = sdk.AccAddressFromBech32(args[0]) + err = sdk.ValidateAccAddress(args[0]) if err != nil { return err } @@ -259,7 +259,7 @@ func GetCmdGetContractStateRaw() *cobra.Command { return err } - _, err = sdk.AccAddressFromBech32(args[0]) + err = sdk.ValidateAccAddress(args[0]) if err != nil { return err } @@ -300,7 +300,7 @@ func GetCmdGetContractStateSmart() *cobra.Command { return err } - _, err = sdk.AccAddressFromBech32(args[0]) + err = sdk.ValidateAccAddress(args[0]) if err != nil { return err } @@ -348,7 +348,7 @@ func GetCmdGetContractHistory() *cobra.Command { return err } - _, err = sdk.AccAddressFromBech32(args[0]) + err = sdk.ValidateAccAddress(args[0]) if err != nil { return err } diff --git a/x/wasm/client/cli/tx.go b/x/wasm/client/cli/tx.go index a2f11b8790..1dd5249342 100644 --- a/x/wasm/client/cli/tx.go +++ b/x/wasm/client/cli/tx.go @@ -104,11 +104,11 @@ func parseStoreCodeArgs(file string, sender sdk.AccAddress, flags *flag.FlagSet) return types.MsgStoreCode{}, fmt.Errorf("instantiate by address: %s", err) } if onlyAddrStr != "" { - allowedAddr, err := sdk.AccAddressFromBech32(onlyAddrStr) + err := sdk.ValidateAccAddress(onlyAddrStr) if err != nil { return types.MsgStoreCode{}, sdkerrors.Wrap(err, flagInstantiateByAddress) } - x := types.AccessTypeOnlyAddress.With(allowedAddr) + x := types.AccessTypeOnlyAddress.With(sdk.AccAddress(onlyAddrStr)) perm = &x } else { everybodyStr, err := flags.GetString(flagInstantiateByEverybody) @@ -271,11 +271,11 @@ func parseStoreCodeAndInstantiateContractArgs(file string, initMsg string, sende return types.MsgStoreCodeAndInstantiateContract{}, fmt.Errorf("instantiate by address: %s", err) } if onlyAddrStr != "" { - allowedAddr, err := sdk.AccAddressFromBech32(onlyAddrStr) + err := sdk.ValidateAccAddress(onlyAddrStr) if err != nil { return types.MsgStoreCodeAndInstantiateContract{}, sdkerrors.Wrap(err, flagInstantiateByAddress) } - x := types.AccessTypeOnlyAddress.With(allowedAddr) + x := types.AccessTypeOnlyAddress.With(sdk.AccAddress(onlyAddrStr)) perm = &x } else { everybodyStr, err := flags.GetString(flagInstantiateByEverybody) diff --git a/x/wasm/client/rest/gov.go b/x/wasm/client/rest/gov.go index 90c97eab80..3adffc3a25 100644 --- a/x/wasm/client/rest/gov.go +++ b/x/wasm/client/rest/gov.go @@ -259,12 +259,12 @@ type wasmProposalData interface { } func toStdTxResponse(cliCtx client.Context, w http.ResponseWriter, data wasmProposalData) { - proposerAddr, err := sdk.AccAddressFromBech32(data.GetProposer()) + err := sdk.ValidateAccAddress(data.GetProposer()) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - msg, err := govtypes.NewMsgSubmitProposal(data.Content(), data.GetDeposit(), proposerAddr) + msg, err := govtypes.NewMsgSubmitProposal(data.Content(), data.GetDeposit(), sdk.AccAddress(data.GetProposer())) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return diff --git a/x/wasm/client/rest/query.go b/x/wasm/client/rest/query.go index 1f324f6697..0698fd510b 100644 --- a/x/wasm/client/rest/query.go +++ b/x/wasm/client/rest/query.go @@ -144,7 +144,8 @@ func listContractsByCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) + addr := mux.Vars(r)["contractAddr"] + err := sdk.ValidateAccAddress(addr) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -154,7 +155,7 @@ func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContract, addr.String()) + route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContract, addr) res, height, err := cliCtx.Query(route) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -168,7 +169,8 @@ func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { func queryContractStateAllHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) + addr := mux.Vars(r)["contractAddr"] + err := sdk.ValidateAccAddress(addr) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -178,7 +180,8 @@ func queryContractStateAllHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateAll) + route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr, + keeper.QueryMethodContractStateAll) res, height, err := cliCtx.Query(route) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -201,7 +204,8 @@ func queryContractStateAllHandlerFn(cliCtx client.Context) http.HandlerFunc { func queryContractStateRawHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { decoder := newArgDecoder(hex.DecodeString) - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) + addr := mux.Vars(r)["contractAddr"] + err := sdk.ValidateAccAddress(addr) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -217,7 +221,8 @@ func queryContractStateRawHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateRaw) + route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr, + keeper.QueryMethodContractStateRaw) res, height, err := cliCtx.QueryWithData(route, queryData) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -237,7 +242,8 @@ type smartResponse struct { func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { decoder := newArgDecoder(hex.DecodeString) - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) + addr := mux.Vars(r)["contractAddr"] + err := sdk.ValidateAccAddress(addr) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -248,7 +254,8 @@ func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateSmart) + route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr, + keeper.QueryMethodContractStateSmart) queryData, err := decoder.DecodeString(mux.Vars(r)["query"]) if err != nil { @@ -270,7 +277,8 @@ func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { func queryContractHistoryFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) + addr := mux.Vars(r)["contractAddr"] + err := sdk.ValidateAccAddress(addr) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -280,7 +288,7 @@ func queryContractHistoryFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryContractHistory, addr.String()) + route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryContractHistory, addr) pageKey, offset, limit, page, countTotal, err := parseHTTPArgs(r) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -294,7 +302,7 @@ func queryContractHistoryFn(cliCtx client.Context) http.HandlerFunc { } data := &types.QueryContractHistoryRequest{ - Address: addr.String(), + Address: addr, Pagination: pageReq, } bs, err := cliCtx.LegacyAmino.MarshalJSON(data) diff --git a/x/wasm/common_test.go b/x/wasm/common_test.go index d7487bf5fd..01b4b6764b 100644 --- a/x/wasm/common_test.go +++ b/x/wasm/common_test.go @@ -27,7 +27,7 @@ func parseInitResponse(t *testing.T, data []byte) string { require.NotEmpty(t, pInstResp.Address) addr := pInstResp.Address // ensure this is a valid sdk address - _, err := sdk.AccAddressFromBech32(addr) + err := sdk.ValidateAccAddress(addr) require.NoError(t, err) return addr } @@ -41,7 +41,7 @@ func parseStoreAndInitResponse(t *testing.T, data []byte) (uint64, string) { addr := res.Address codeID := res.CodeID // ensure this is a valid sdk address - _, err := sdk.AccAddressFromBech32(addr) + err := sdk.ValidateAccAddress(addr) require.NoError(t, err) return codeID, addr } diff --git a/x/wasm/keeper/api.go b/x/wasm/keeper/api.go index 51bff4b814..23f8354b6c 100644 --- a/x/wasm/keeper/api.go +++ b/x/wasm/keeper/api.go @@ -13,16 +13,16 @@ type cosmwasmAPIImpl struct { func (a cosmwasmAPIImpl) humanAddress(canon []byte) (string, uint64, error) { gas := 5 * a.gasMultiplier - if len(canon) != sdk.AddrLen { + if len(canon) != sdk.BytesAddrLen { //nolint:stylecheck - return "", gas, fmt.Errorf("expected %d byte address", sdk.AddrLen) + return "", gas, fmt.Errorf("expected %d byte address", sdk.BytesAddrLen) } - return sdk.AccAddress(canon).String(), gas, nil + return sdk.BytesToAccAddress(canon).String(), gas, nil } func (a cosmwasmAPIImpl) canonicalAddress(human string) ([]byte, uint64, error) { - bz, err := sdk.AccAddressFromBech32(human) + bz, err := sdk.AccAddressToBytes(human) return bz, 4 * a.gasMultiplier, err } diff --git a/x/wasm/keeper/authz_policy.go b/x/wasm/keeper/authz_policy.go index ab690d52ad..ab20535646 100644 --- a/x/wasm/keeper/authz_policy.go +++ b/x/wasm/keeper/authz_policy.go @@ -24,7 +24,7 @@ func (p DefaultAuthorizationPolicy) CanInstantiateContract(config types.AccessCo } func (p DefaultAuthorizationPolicy) CanModifyContract(admin, actor sdk.AccAddress) bool { - return admin != nil && admin.Equals(actor) + return admin != "" && admin.Equals(actor) } func (p DefaultAuthorizationPolicy) CanUpdateContractStatus(config types.AccessConfig, actor sdk.AccAddress) bool { diff --git a/x/wasm/keeper/contract_keeper.go b/x/wasm/keeper/contract_keeper.go index 3ed6bbc1cc..83529490ab 100644 --- a/x/wasm/keeper/contract_keeper.go +++ b/x/wasm/keeper/contract_keeper.go @@ -58,7 +58,7 @@ func (p PermissionedKeeper) UpdateContractAdmin(ctx sdk.Context, contractAddress } func (p PermissionedKeeper) ClearContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress) error { - return p.nested.setContractAdmin(ctx, contractAddress, caller, nil, p.authZPolicy) + return p.nested.setContractAdmin(ctx, contractAddress, caller, "", p.authZPolicy) } func (p PermissionedKeeper) PinCode(ctx sdk.Context, codeID uint64) error { diff --git a/x/wasm/keeper/genesis.go b/x/wasm/keeper/genesis.go index 7691cc7c85..e8d3eaf023 100644 --- a/x/wasm/keeper/genesis.go +++ b/x/wasm/keeper/genesis.go @@ -36,11 +36,12 @@ func InitGenesis(ctx sdk.Context, keeper *Keeper, data types.GenesisState, staki var maxContractID int for i, contract := range data.Contracts { - contractAddr, err := sdk.AccAddressFromBech32(contract.ContractAddress) + err := sdk.ValidateAccAddress(contract.ContractAddress) if err != nil { return nil, sdkerrors.Wrapf(err, "address in contract number %d", i) } - err = keeper.importContract(ctx, contractAddr, &contract.ContractInfo, contract.ContractState) + err = keeper.importContract(ctx, sdk.AccAddress(contract.ContractAddress), &contract.ContractInfo, + contract.ContractState) if err != nil { return nil, sdkerrors.Wrapf(err, "contract number %d", i) } diff --git a/x/wasm/keeper/genesis_test.go b/x/wasm/keeper/genesis_test.go index add9888624..369a8fd252 100644 --- a/x/wasm/keeper/genesis_test.go +++ b/x/wasm/keeper/genesis_test.go @@ -63,9 +63,9 @@ func TestGenesisExportImport(t *testing.T) { f.Fuzz(&pinned) f.Fuzz(&contractExtension) - creatorAddr, err := sdk.AccAddressFromBech32(codeInfo.Creator) + err := sdk.ValidateAccAddress(codeInfo.Creator) require.NoError(t, err) - codeID, err := contractKeeper.Create(srcCtx, creatorAddr, wasmCode, codeInfo.Source, codeInfo.Builder, &codeInfo.InstantiateConfig) + codeID, err := contractKeeper.Create(srcCtx, sdk.AccAddress(codeInfo.Creator), wasmCode, codeInfo.Source, codeInfo.Builder, &codeInfo.InstantiateConfig) require.NoError(t, err) if pinned { contractKeeper.PinCode(srcCtx, codeID) @@ -541,7 +541,7 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) { assert.Equal(t, expCodeInfo, *gotCodeInfo) // verify contract - contractAddr, _ := sdk.AccAddressFromBech32("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") + contractAddr := sdk.AccAddress("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") gotContractInfo := keeper.GetContractInfo(ctx, contractAddr) require.NotNil(t, gotContractInfo) contractCreatorAddr := "link1p0yx9c9q4xsnedlcn24gqfry5dcu6e9xkhv9aj" @@ -570,9 +570,9 @@ func TestSupportedGenMsgTypes(t *testing.T) { wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) var ( - myAddress sdk.AccAddress = bytes.Repeat([]byte{1}, sdk.AddrLen) - verifierAddress sdk.AccAddress = bytes.Repeat([]byte{2}, sdk.AddrLen) - beneficiaryAddress sdk.AccAddress = bytes.Repeat([]byte{3}, sdk.AddrLen) + myAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, sdk.BytesAddrLen)) + verifierAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, sdk.BytesAddrLen)) + beneficiaryAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{3}, sdk.BytesAddrLen)) ) const denom = "stake" importState := types.GenesisState{ diff --git a/x/wasm/keeper/ibc.go b/x/wasm/keeper/ibc.go index fd5cc3ac43..178d6b72dd 100644 --- a/x/wasm/keeper/ibc.go +++ b/x/wasm/keeper/ibc.go @@ -38,9 +38,12 @@ func PortIDForContract(addr sdk.AccAddress) string { func ContractFromPortID(portID string) (sdk.AccAddress, error) { if !strings.HasPrefix(portID, portIDPrefix) { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "without prefix") + return "", sdkerrors.Wrapf(types.ErrInvalid, "without prefix") } - return sdk.AccAddressFromBech32(portID[len(portIDPrefix):]) + if err := sdk.ValidateAccAddress(portID[len(portIDPrefix):]); err != nil { + return "", sdkerrors.Wrapf(types.ErrInvalid, err.Error()) + } + return sdk.AccAddress(portID[len(portIDPrefix):]), nil } // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function diff --git a/x/wasm/keeper/ibc_test.go b/x/wasm/keeper/ibc_test.go index 5a0dbd5b2b..10ccb8e0bb 100644 --- a/x/wasm/keeper/ibc_test.go +++ b/x/wasm/keeper/ibc_test.go @@ -30,7 +30,7 @@ func TestBindingPortForIBCContractOnInstantiate(t *testing.T) { // create a second contract should give yet another portID (and different address) creator := RandomAccountAddress(t) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, creator, nil, initMsgBz, "ibc-reflect-2", nil) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, creator, "", initMsgBz, "ibc-reflect-2", nil) require.NoError(t, err) require.NotEqual(t, example.Contract, addr) diff --git a/x/wasm/keeper/keeper.go b/x/wasm/keeper/keeper.go index acdea8e759..aa47e30fe4 100644 --- a/x/wasm/keeper/keeper.go +++ b/x/wasm/keeper/keeper.go @@ -242,13 +242,13 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A contractAddress := k.generateContractAddress(ctx, codeID) existingAcct := k.accountKeeper.GetAccount(ctx, contractAddress) if existingAcct != nil { - return nil, nil, sdkerrors.Wrap(types.ErrAccountExists, existingAcct.GetAddress().String()) + return "", nil, sdkerrors.Wrap(types.ErrAccountExists, existingAcct.GetAddress().String()) } // deposit initial contract funds if !deposit.IsZero() { if err := k.bank.TransferCoins(ctx, creator, contractAddress, deposit); err != nil { - return nil, nil, err + return "", nil, err } } else { @@ -262,13 +262,13 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A store := ctx.KVStore(k.storeKey) bz := store.Get(types.GetCodeKey(codeID)) if bz == nil { - return nil, nil, sdkerrors.Wrap(types.ErrNotFound, "code") + return "", nil, sdkerrors.Wrap(types.ErrNotFound, "code") } var codeInfo types.CodeInfo k.cdc.MustUnmarshalBinaryBare(bz, &codeInfo) if !authZ.CanInstantiateContract(codeInfo.InstantiateConfig, creator) { - return nil, nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") + return "", nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") } // prepare params for contract instantiate call @@ -309,7 +309,7 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A // register IBC port ibcPort, err := k.ensureIbcPort(ctx, contractAddress) if err != nil { - return nil, nil, err + return "", nil, err } contractInfo.IBCPortID = ibcPort } @@ -323,7 +323,7 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A // dispatch submessages then messages data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res) if err != nil { - return nil, nil, sdkerrors.Wrap(err, "dispatch") + return "", nil, sdkerrors.Wrap(err, "dispatch") } return contractAddress, data, nil @@ -555,7 +555,7 @@ func (k Keeper) IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(a prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractByCodeIDSecondaryIndexPrefix(codeID)) for iter := prefixStore.Iterator(nil, nil); iter.Valid(); iter.Next() { key := iter.Key() - if cb(key[types.AbsoluteTxPositionLen:]) { + if cb(sdk.AccAddress(string(key[types.AbsoluteTxPositionLen:]))) { return } } @@ -719,7 +719,7 @@ func (k Keeper) IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, typ var contract types.ContractInfo k.cdc.MustUnmarshalBinaryBare(iter.Value(), &contract) // cb returns true to stop early - if cb(iter.Key(), contract) { + if cb(sdk.AccAddress(string(iter.Key())), contract) { break } } @@ -954,7 +954,7 @@ func addrFromUint64(id uint64) sdk.AccAddress { addr := make([]byte, 20) addr[0] = 'C' binary.PutUvarint(addr[1:], id) - return sdk.AccAddress(crypto.AddressHash(addr)) + return sdk.BytesToAccAddress(crypto.AddressHash(addr)) } // MultipliedGasMeter wraps the GasMeter from context and multiplies all reads by out defined multiplier diff --git a/x/wasm/keeper/keeper_test.go b/x/wasm/keeper/keeper_test.go index 2b9fe9899d..19f6ac63ec 100644 --- a/x/wasm/keeper/keeper_test.go +++ b/x/wasm/keeper/keeper_test.go @@ -52,8 +52,8 @@ func TestCreateStoresInstantiatePermission(t *testing.T) { wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) var ( - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr sdk.AccAddress = bytes.Repeat([]byte{1}, sdk.AddrLen) + deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) + myAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, sdk.BytesAddrLen)) ) specs := map[string]struct { @@ -281,7 +281,7 @@ func TestInstantiate(t *testing.T) { gasBefore := ctx.GasMeter().GasConsumed() // create with no balance is also legal - gotContractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, "demo contract 1", nil) + gotContractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", initMsgBz, "demo contract 1", nil) require.NoError(t, err) require.Equal(t, "link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu", gotContractAddr.String()) @@ -312,8 +312,8 @@ func TestInstantiateWithDeposit(t *testing.T) { require.NoError(t, err) var ( - bob = bytes.Repeat([]byte{1}, sdk.AddrLen) - fred = bytes.Repeat([]byte{2}, sdk.AddrLen) + bob = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, sdk.BytesAddrLen)) + fred = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, sdk.BytesAddrLen)) deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) initMsg = HackatomExampleInitMsg{Verifier: fred, Beneficiary: bob} @@ -353,7 +353,7 @@ func TestInstantiateWithDeposit(t *testing.T) { require.NoError(t, err) // when - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsgBz, "my label", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, "", initMsgBz, "my label", deposit) // then if spec.expError { require.Error(t, err) @@ -372,9 +372,9 @@ func TestInstantiateWithPermissions(t *testing.T) { var ( deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr = bytes.Repeat([]byte{1}, sdk.AddrLen) - otherAddr = bytes.Repeat([]byte{2}, sdk.AddrLen) - anyAddr = bytes.Repeat([]byte{3}, sdk.AddrLen) + myAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, sdk.BytesAddrLen)) + otherAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, sdk.BytesAddrLen)) + anyAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{3}, sdk.BytesAddrLen)) ) initMsg := HackatomExampleInitMsg{ @@ -420,7 +420,7 @@ func TestInstantiateWithPermissions(t *testing.T) { contractID, err := keeper.Create(ctx, myAddr, wasmCode, "https://github.com/line/lfb-sdk/blob/main/x/wasm/internal/keeper/testdata/hackatom.wasm", "", &spec.srcPermission) require.NoError(t, err) - _, _, err = keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsgBz, "demo contract 1", nil) + _, _, err = keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, "", initMsgBz, "demo contract 1", nil) assert.True(t, spec.expError.Is(err), "got %+v", err) }) } @@ -438,9 +438,9 @@ func TestInstantiateWithNonExistingCodeID(t *testing.T) { require.NoError(t, err) const nonExistingCodeID = 9999 - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, nonExistingCodeID, creator, nil, initMsgBz, "demo contract 2", nil) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, nonExistingCodeID, creator, "", initMsgBz, "demo contract 2", nil) require.True(t, types.ErrNotFound.Is(err), err) - require.Nil(t, addr) + require.Equal(t, addr.String(), "") } func TestInstantiateWithContractDataResponse(t *testing.T) { @@ -455,7 +455,7 @@ func TestInstantiateWithContractDataResponse(t *testing.T) { } example := StoreRandomContract(t, ctx, keepers, wasmerMock) - _, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil) + _, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, "", nil, "test", nil) require.NoError(t, err) assert.Equal(t, []byte("my-response-data"), data) } @@ -483,7 +483,7 @@ func TestExecute(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 3", deposit) require.NoError(t, err) require.Equal(t, "link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu", addr.String()) @@ -542,8 +542,8 @@ func TestExecuteWithDeposit(t *testing.T) { require.NoError(t, err) var ( - bob = bytes.Repeat([]byte{1}, sdk.AddrLen) - fred = bytes.Repeat([]byte{2}, sdk.AddrLen) + bob = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, sdk.BytesAddrLen)) + fred = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, sdk.BytesAddrLen)) blockedAddr = authtypes.NewModuleAddress(authtypes.FeeCollectorName) deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) ) @@ -612,7 +612,7 @@ func TestExecuteWithDeposit(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, spec.srcActor, nil, initMsgBz, "my label", nil) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, spec.srcActor, "", initMsgBz, "my label", nil) require.NoError(t, err) // when @@ -666,7 +666,7 @@ func TestExecuteWithPanic(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 4", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 4", deposit) require.NoError(t, err) // let's make sure we get a reasonable error, no panic/crash @@ -700,7 +700,7 @@ func TestExecuteWithCpuLoop(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 5", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 5", deposit) require.NoError(t, err) // make sure we set a limit before calling @@ -745,7 +745,7 @@ func TestExecuteWithStorageLoop(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 6", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 6", deposit) require.NoError(t, err) // make sure we set a limit before calling @@ -789,7 +789,7 @@ func TestExecuteInactiveContract(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) + addr, _, err := keeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 3", deposit) require.NoError(t, err) require.Equal(t, "link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu", addr.String()) @@ -945,7 +945,7 @@ func TestMigrate(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, spec.fromCodeID, creator, spec.admin, spec.initMsg, "demo contract", nil) require.NoError(t, err) - if spec.overrideContractAddr != nil { + if spec.overrideContractAddr != "" { contractAddr = spec.overrideContractAddr } // when @@ -1143,7 +1143,7 @@ func TestIterateContractsByCode(t *testing.T) { Verifier: RandomAccountAddress(t), Beneficiary: RandomAccountAddress(t), }.GetBytes(t) - contractAddr3, _, err := c.Instantiate(ctx, example1.CodeID, example1.CreatorAddr, nil, initMsg, "foo", nil) + contractAddr3, _, err := c.Instantiate(ctx, example1.CodeID, example1.CreatorAddr, "", initMsg, "foo", nil) require.NoError(t, err) specs := map[string]struct { codeID uint64 @@ -1238,7 +1238,7 @@ func TestSudo(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 3", deposit) require.NoError(t, err) require.Equal(t, "link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu", addr.String()) @@ -1353,7 +1353,7 @@ func TestUpdateContractAdmin(t *testing.T) { t.Run(msg, func(t *testing.T) { addr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, spec.instAdmin, initMsgBz, "demo contract", nil) require.NoError(t, err) - if spec.overrideContractAddr != nil { + if spec.overrideContractAddr != "" { addr = spec.overrideContractAddr } err = keeper.UpdateContractAdmin(ctx, addr, spec.caller, spec.newAdmin) @@ -1455,7 +1455,7 @@ func TestClearContractAdmin(t *testing.T) { t.Run(msg, func(t *testing.T) { addr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, spec.instAdmin, initMsgBz, "demo contract", nil) require.NoError(t, err) - if spec.overrideContractAddr != nil { + if spec.overrideContractAddr != "" { addr = spec.overrideContractAddr } err = keeper.ClearContractAdmin(ctx, addr, spec.caller) @@ -1598,7 +1598,7 @@ func runUpdateStatusSpec(t *testing.T, msg string, contractKeeper types.Contract t.Run(msg, func(t *testing.T) { addr, _, err := contractKeeper.Instantiate(ctx, originalContractID, creator, spec.instAdmin, initMsgBz, "demo contract", nil) require.NoError(t, err) - if spec.overrideContractAddr != nil { + if spec.overrideContractAddr != "" { addr = spec.overrideContractAddr } err = contractKeeper.UpdateContractStatus(ctx, addr, spec.caller, types.ContractStatusInactive) diff --git a/x/wasm/keeper/legacy_querier.go b/x/wasm/keeper/legacy_querier.go index 300427d1b3..226cd0bc44 100644 --- a/x/wasm/keeper/legacy_querier.go +++ b/x/wasm/keeper/legacy_querier.go @@ -35,12 +35,12 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { ) switch path[0] { case QueryGetContract: - addr, err := sdk.AccAddressFromBech32(path[1]) + err := sdk.ValidateAccAddress(path[1]) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) } //nolint:staticcheck - rsp, err = queryContractInfo(ctx, addr, keeper) + rsp, err = queryContractInfo(ctx, sdk.AccAddress(path[1]), keeper) case QueryListContractByCode: codeID, err := strconv.ParseUint(path[1], 10, 64) if err != nil { @@ -49,6 +49,10 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { //nolint:staticcheck rsp = queryContractListByCode(ctx, codeID, keeper) case QueryGetContractState: + err := sdk.ValidateAccAddress(path[1]) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + } if len(path) < 3 { return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") } @@ -64,12 +68,12 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { //nolint:staticcheck rsp, err = queryCodeList(ctx, keeper) case QueryContractHistory: - contractAddr, err := sdk.AccAddressFromBech32(path[1]) + err := sdk.ValidateAccAddress(path[1]) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) } //nolint:staticcheck - rsp, err = queryContractHistory(ctx, contractAddr, keeper) + rsp, err = queryContractHistory(ctx, sdk.AccAddress(path[1]), keeper) default: return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") } @@ -88,11 +92,11 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { } func queryContractState(ctx sdk.Context, bech, queryMethod string, data []byte, gasLimit sdk.Gas, keeper types.ViewKeeper) (json.RawMessage, error) { - contractAddr, err := sdk.AccAddressFromBech32(bech) + err := sdk.ValidateAccAddress(bech) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, bech) } - + contractAddr := sdk.AccAddress(bech) var resultData []types.Model switch queryMethod { case QueryMethodContractStateAll: diff --git a/x/wasm/keeper/legacy_querier_test.go b/x/wasm/keeper/legacy_querier_test.go index 7306d60118..867eb85996 100644 --- a/x/wasm/keeper/legacy_querier_test.go +++ b/x/wasm/keeper/legacy_querier_test.go @@ -38,7 +38,7 @@ func TestLegacyQueryContractState(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract to query", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract to query", deposit) require.NoError(t, err) contractModel := []types.Model{ @@ -192,7 +192,7 @@ func TestLegacyQueryContractListByCodeOrdering(t *testing.T) { ctx = setBlock(ctx, h) h++ } - _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) + _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", initMsgBz, fmt.Sprintf("contract %d", i), topUp) require.NoError(t, err) } @@ -221,7 +221,7 @@ func TestLegacyQueryContractHistory(t *testing.T) { keeper := keepers.WasmKeeper var ( - otherAddr sdk.AccAddress = bytes.Repeat([]byte{0x2}, sdk.AddrLen) + otherAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, sdk.BytesAddrLen)) ) specs := map[string]struct { @@ -292,7 +292,7 @@ func TestLegacyQueryContractHistory(t *testing.T) { var defaultQueryGasLimit sdk.Gas = 3000000 q := NewLegacyQuerier(keeper, defaultQueryGasLimit) queryContractAddr := spec.srcQueryAddr - if queryContractAddr == nil { + if queryContractAddr.Empty() { queryContractAddr = myContractAddr } diff --git a/x/wasm/keeper/msg_server.go b/x/wasm/keeper/msg_server.go index 733244296d..d268fd1a03 100644 --- a/x/wasm/keeper/msg_server.go +++ b/x/wasm/keeper/msg_server.go @@ -21,11 +21,12 @@ func NewMsgServerImpl(k types.ContractOpsKeeper) types.MsgServer { func (m msgServer) StoreCode(goCtx context.Context, msg *types.MsgStoreCode) (*types.MsgStoreCodeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - codeID, err := m.keeper.Create(ctx, senderAddr, msg.WASMByteCode, msg.Source, msg.Builder, msg.InstantiatePermission) + codeID, err := m.keeper.Create(ctx, sdk.AccAddress(msg.Sender), msg.WASMByteCode, msg.Source, msg.Builder, + msg.InstantiatePermission) if err != nil { return nil, err } @@ -48,18 +49,19 @@ func (m msgServer) StoreCode(goCtx context.Context, msg *types.MsgStoreCode) (*t func (m msgServer) InstantiateContract(goCtx context.Context, msg *types.MsgInstantiateContract) (*types.MsgInstantiateContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } var adminAddr sdk.AccAddress if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { + if err = sdk.ValidateAccAddress(msg.Admin); err != nil { return nil, sdkerrors.Wrap(err, "admin") } + adminAddr = sdk.AccAddress(msg.Admin) } - contractAddr, data, err := m.keeper.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.InitMsg, msg.Label, msg.Funds) + contractAddr, data, err := m.keeper.Instantiate(ctx, msg.CodeID, sdk.AccAddress(msg.Sender), adminAddr, msg.InitMsg, msg.Label, msg.Funds) if err != nil { return nil, err } @@ -81,13 +83,15 @@ func (m msgServer) InstantiateContract(goCtx context.Context, msg *types.MsgInst }, nil } -func (m msgServer) StoreCodeAndInstantiateContract(goCtx context.Context, msg *types.MsgStoreCodeAndInstantiateContract) (*types.MsgStoreCodeAndInstantiateContractResponse, error) { +func (m msgServer) StoreCodeAndInstantiateContract(goCtx context.Context, + msg *types.MsgStoreCodeAndInstantiateContract) (*types.MsgStoreCodeAndInstantiateContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - codeID, err := m.keeper.Create(ctx, senderAddr, msg.WASMByteCode, msg.Source, msg.Builder, msg.InstantiatePermission) + codeID, err := m.keeper.Create(ctx, sdk.AccAddress(msg.Sender), msg.WASMByteCode, msg.Source, msg.Builder, + msg.InstantiatePermission) if err != nil { return nil, err } @@ -104,12 +108,14 @@ func (m msgServer) StoreCodeAndInstantiateContract(goCtx context.Context, msg *t var adminAddr sdk.AccAddress if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { + if err = sdk.ValidateAccAddress(msg.Admin); err != nil { return nil, sdkerrors.Wrap(err, "admin") } + adminAddr = sdk.AccAddress(msg.Admin) } - contractAddr, data, err := m.keeper.Instantiate(ctx, codeID, senderAddr, adminAddr, msg.InitMsg, msg.Label, msg.Funds) + contractAddr, data, err := m.keeper.Instantiate(ctx, codeID, sdk.AccAddress(msg.Sender), adminAddr, msg.InitMsg, + msg.Label, msg.Funds) if err != nil { return nil, err } @@ -129,16 +135,16 @@ func (m msgServer) StoreCodeAndInstantiateContract(goCtx context.Context, msg *t func (m msgServer) ExecuteContract(goCtx context.Context, msg *types.MsgExecuteContract) (*types.MsgExecuteContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) + err = sdk.ValidateAccAddress(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } - res, err := m.keeper.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) + res, err := m.keeper.Execute(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), msg.Msg, msg.Funds) if err != nil { return nil, err } @@ -161,16 +167,16 @@ func (m msgServer) ExecuteContract(goCtx context.Context, msg *types.MsgExecuteC func (m msgServer) MigrateContract(goCtx context.Context, msg *types.MsgMigrateContract) (*types.MsgMigrateContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) + err = sdk.ValidateAccAddress(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } - res, err := m.keeper.Migrate(ctx, contractAddr, senderAddr, msg.CodeID, msg.MigrateMsg) + res, err := m.keeper.Migrate(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), msg.CodeID, msg.MigrateMsg) if err != nil { return nil, err } @@ -193,20 +199,21 @@ func (m msgServer) MigrateContract(goCtx context.Context, msg *types.MsgMigrateC func (m msgServer) UpdateAdmin(goCtx context.Context, msg *types.MsgUpdateAdmin) (*types.MsgUpdateAdminResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) + err = sdk.ValidateAccAddress(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } - newAdminAddr, err := sdk.AccAddressFromBech32(msg.NewAdmin) + err = sdk.ValidateAccAddress(msg.NewAdmin) if err != nil { return nil, sdkerrors.Wrap(err, "new admin") } - if err := m.keeper.UpdateContractAdmin(ctx, contractAddr, senderAddr, newAdminAddr); err != nil { + if err := m.keeper.UpdateContractAdmin(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), + sdk.AccAddress(msg.NewAdmin)); err != nil { return nil, err } @@ -225,16 +232,16 @@ func (m msgServer) UpdateAdmin(goCtx context.Context, msg *types.MsgUpdateAdmin) func (m msgServer) ClearAdmin(goCtx context.Context, msg *types.MsgClearAdmin) (*types.MsgClearAdminResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) + err = sdk.ValidateAccAddress(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } - if err := m.keeper.ClearContractAdmin(ctx, contractAddr, senderAddr); err != nil { + if err := m.keeper.ClearContractAdmin(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender)); err != nil { return nil, err } @@ -255,16 +262,17 @@ func (m msgServer) ClearAdmin(goCtx context.Context, msg *types.MsgClearAdmin) ( // CONTRACT: msg.validateBasic() must be called before calling this func (m msgServer) UpdateContractStatus(goCtx context.Context, msg *types.MsgUpdateContractStatus) (*types.MsgUpdateContractStatusResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) + err = sdk.ValidateAccAddress(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } - if err = m.keeper.UpdateContractStatus(ctx, contractAddr, senderAddr, msg.Status); err != nil { + if err = m.keeper.UpdateContractStatus(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), + msg.Status); err != nil { return nil, err } diff --git a/x/wasm/keeper/proposal_handler.go b/x/wasm/keeper/proposal_handler.go index 5f8da8d83f..9157c7d4d2 100644 --- a/x/wasm/keeper/proposal_handler.go +++ b/x/wasm/keeper/proposal_handler.go @@ -57,11 +57,11 @@ func handleStoreCodeProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types return err } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) + err := sdk.ValidateAccAddress(p.RunAs) if err != nil { return sdkerrors.Wrap(err, "run as address") } - codeID, err := k.Create(ctx, runAsAddr, p.WASMByteCode, p.Source, p.Builder, p.InstantiatePermission) + codeID, err := k.Create(ctx, sdk.AccAddress(p.RunAs), p.WASMByteCode, p.Source, p.Builder, p.InstantiatePermission) if err != nil { return err } @@ -78,16 +78,16 @@ func handleInstantiateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p typ if err := p.ValidateBasic(); err != nil { return err } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) + err := sdk.ValidateAccAddress(p.RunAs) if err != nil { return sdkerrors.Wrap(err, "run as address") } - adminAddr, err := sdk.AccAddressFromBech32(p.Admin) + err = sdk.ValidateAccAddress(p.Admin) if err != nil { return sdkerrors.Wrap(err, "admin") } - contractAddr, _, err := k.Instantiate(ctx, p.CodeID, runAsAddr, adminAddr, p.InitMsg, p.Label, p.Funds) + contractAddr, _, err := k.Instantiate(ctx, p.CodeID, sdk.AccAddress(p.RunAs), sdk.AccAddress(p.Admin), p.InitMsg, p.Label, p.Funds) if err != nil { return err } @@ -106,15 +106,15 @@ func handleMigrateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.M return err } - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) + err := sdk.ValidateAccAddress(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) + err = sdk.ValidateAccAddress(p.RunAs) if err != nil { return sdkerrors.Wrap(err, "run as address") } - res, err := k.Migrate(ctx, contractAddr, runAsAddr, p.CodeID, p.MigrateMsg) + res, err := k.Migrate(ctx, sdk.AccAddress(p.Contract), sdk.AccAddress(p.RunAs), p.CodeID, p.MigrateMsg) if err != nil { return err } @@ -139,16 +139,16 @@ func handleUpdateAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p typ if err := p.ValidateBasic(); err != nil { return err } - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) + err := sdk.ValidateAccAddress(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - newAdminAddr, err := sdk.AccAddressFromBech32(p.NewAdmin) + err = sdk.ValidateAccAddress(p.NewAdmin) if err != nil { return sdkerrors.Wrap(err, "run as address") } - if err := k.UpdateContractAdmin(ctx, contractAddr, nil, newAdminAddr); err != nil { + if err := k.UpdateContractAdmin(ctx, sdk.AccAddress(p.Contract), "", sdk.AccAddress(p.NewAdmin)); err != nil { return err } @@ -165,11 +165,11 @@ func handleClearAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p type return err } - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) + err := sdk.ValidateAccAddress(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - if err := k.ClearContractAdmin(ctx, contractAddr, nil); err != nil { + if err := k.ClearContractAdmin(ctx, sdk.AccAddress(p.Contract), ""); err != nil { return err } @@ -241,11 +241,11 @@ func handleUpdateContractStatusProposal(ctx sdk.Context, k types.ContractOpsKeep if err := p.ValidateBasic(); err != nil { return err } - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) + err := sdk.ValidateAccAddress(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - if err = k.UpdateContractStatus(ctx, contractAddr, nil, p.Status); err != nil { + if err = k.UpdateContractStatus(ctx, sdk.AccAddress(p.Contract), "", p.Status); err != nil { return err } diff --git a/x/wasm/keeper/proposal_integration_test.go b/x/wasm/keeper/proposal_integration_test.go index 6eb5e927dd..92f95e5071 100644 --- a/x/wasm/keeper/proposal_integration_test.go +++ b/x/wasm/keeper/proposal_integration_test.go @@ -85,8 +85,8 @@ func TestInstantiateProposal(t *testing.T) { ) var ( - oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, sdk.AddrLen) + oneAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, sdk.BytesAddrLen)) + otherAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, sdk.BytesAddrLen)) ) src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { p.CodeID = firstCodeID @@ -105,10 +105,11 @@ func TestInstantiateProposal(t *testing.T) { require.NoError(t, err) // then - contractAddr, err := sdk.AccAddressFromBech32("link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu") + contractAddr := "link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu" + err = sdk.ValidateAccAddress(contractAddr) require.NoError(t, err) - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) + cInfo := wasmKeeper.GetContractInfo(ctx, sdk.AccAddress(contractAddr)) require.NotNil(t, cInfo) assert.Equal(t, uint64(1), cInfo.CodeID) assert.Equal(t, oneAddress.String(), cInfo.Creator) @@ -120,7 +121,7 @@ func TestInstantiateProposal(t *testing.T) { Updated: types.NewAbsoluteTxPosition(ctx), Msg: src.InitMsg, }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) + assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, sdk.AccAddress(contractAddr))) } func TestMigrateProposal(t *testing.T) { @@ -144,9 +145,9 @@ func TestMigrateProposal(t *testing.T) { require.NoError(t, wasmKeeper.importCode(ctx, 2, codeInfoFixture, wasmCode)) var ( - anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, sdk.AddrLen) - contractAddr = contractAddress(1, 1) + anyAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, sdk.BytesAddrLen)) + otherAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, sdk.BytesAddrLen)) + contractAddr = contractAddress(1, 1) ) contractInfoFixture := types.ContractInfoFixture(func(c *types.ContractInfo) { @@ -204,8 +205,8 @@ func TestMigrateProposal(t *testing.T) { func TestAdminProposals(t *testing.T) { var ( - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, sdk.AddrLen) - contractAddr = contractAddress(1, 1) + otherAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, sdk.BytesAddrLen)) + contractAddr = contractAddress(1, 1) ) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -244,7 +245,7 @@ func TestAdminProposals(t *testing.T) { Description: "Bar", Contract: contractAddr.String(), }, - expAdmin: nil, + expAdmin: "", }, "clear with old admin empty": { state: types.ContractInfoFixture(func(info *types.ContractInfo) { @@ -255,7 +256,7 @@ func TestAdminProposals(t *testing.T) { Description: "Bar", Contract: contractAddr.String(), }, - expAdmin: nil, + expAdmin: "", }, } for msg, spec := range specs { @@ -298,9 +299,9 @@ func TestUpdateParamsProposal(t *testing.T) { govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper var ( - cdc = keepers.WasmKeeper.cdc - myAddress sdk.AccAddress = make([]byte, sdk.AddrLen) - oneAddressAccessConfig = types.AccessTypeOnlyAddress.With(myAddress) + cdc = keepers.WasmKeeper.cdc + myAddress = sdk.BytesToAccAddress(make([]byte, sdk.BytesAddrLen)) + oneAddressAccessConfig = types.AccessTypeOnlyAddress.With(myAddress) ) nobodyJson, err := json.Marshal(types.AccessTypeNobody) diff --git a/x/wasm/keeper/querier.go b/x/wasm/keeper/querier.go index 6fcddd3dfd..08c231dcfa 100644 --- a/x/wasm/keeper/querier.go +++ b/x/wasm/keeper/querier.go @@ -33,11 +33,11 @@ func (q GrpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInf if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) + err := sdk.ValidateAccAddress(req.Address) if err != nil { return nil, err } - rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), contractAddr, q.keeper) + rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), sdk.AccAddress(req.Address), q.keeper) switch { case err != nil: return nil, err @@ -51,7 +51,7 @@ func (q GrpcQuerier) ContractHistory(c context.Context, req *types.QueryContract if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) + err := sdk.ValidateAccAddress(req.Address) if err != nil { return nil, err } @@ -59,7 +59,7 @@ func (q GrpcQuerier) ContractHistory(c context.Context, req *types.QueryContract ctx := sdk.UnwrapSDKContext(c) r := make([]types.ContractCodeHistoryEntry, 0) - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) + prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractCodeHistoryElementPrefix(sdk.AccAddress(req.Address))) pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { if accumulate { var e types.ContractCodeHistoryEntry @@ -94,7 +94,7 @@ func (q GrpcQuerier) ContractsByCode(c context.Context, req *types.QueryContract prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractByCodeIDSecondaryIndexPrefix(req.CodeId)) pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { if accumulate { - var contractAddr sdk.AccAddress = key[types.AbsoluteTxPositionLen:] + var contractAddr sdk.AccAddress = sdk.AccAddress(string(key[types.AbsoluteTxPositionLen:])) r = append(r, contractAddr.String()) } return true, nil @@ -112,17 +112,17 @@ func (q GrpcQuerier) AllContractState(c context.Context, req *types.QueryAllCont if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) + err := sdk.ValidateAccAddress(req.Address) if err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) - if !q.keeper.HasContractInfo(ctx, contractAddr) { + if !q.keeper.HasContractInfo(ctx, sdk.AccAddress(req.Address)) { return nil, types.ErrNotFound } r := make([]types.Model, 0) - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractStorePrefix(contractAddr)) + prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractStorePrefix(sdk.AccAddress(req.Address))) pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { if accumulate { r = append(r, types.Model{ @@ -147,15 +147,15 @@ func (q GrpcQuerier) RawContractState(c context.Context, req *types.QueryRawCont } ctx := sdk.UnwrapSDKContext(c) - contractAddr, err := sdk.AccAddressFromBech32(req.Address) + err := sdk.ValidateAccAddress(req.Address) if err != nil { return nil, err } - if !q.keeper.HasContractInfo(ctx, contractAddr) { + if !q.keeper.HasContractInfo(ctx, sdk.AccAddress(req.Address)) { return nil, types.ErrNotFound } - rsp := q.keeper.QueryRaw(ctx, contractAddr, req.QueryData) + rsp := q.keeper.QueryRaw(ctx, sdk.AccAddress(req.Address), req.QueryData) return &types.QueryRawContractStateResponse{Data: rsp}, nil } @@ -163,7 +163,7 @@ func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) + err = sdk.ValidateAccAddress(req.Address) if err != nil { return nil, err } @@ -189,7 +189,7 @@ func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart } }() - bz, err := q.keeper.QuerySmart(ctx, contractAddr, req.QueryData) + bz, err := q.keeper.QuerySmart(ctx, sdk.AccAddress(req.Address), req.QueryData) switch { case err != nil: return nil, err diff --git a/x/wasm/keeper/querier_test.go b/x/wasm/keeper/querier_test.go index 0c11198132..bc0f2d22b6 100644 --- a/x/wasm/keeper/querier_test.go +++ b/x/wasm/keeper/querier_test.go @@ -291,7 +291,7 @@ func TestQueryContractListByCodeOrdering(t *testing.T) { ctx = setBlock(ctx, h) h++ } - _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) + _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", initMsgBz, fmt.Sprintf("contract %d", i), topUp) require.NoError(t, err) } @@ -430,7 +430,7 @@ func TestQueryContractHistory(t *testing.T) { t.Run(msg, func(t *testing.T) { xCtx, _ := ctx.CacheContext() - cAddr, _ := sdk.AccAddressFromBech32(myContractBech32Addr) + cAddr := sdk.AccAddress(myContractBech32Addr) keeper.appendToContractHistory(xCtx, cAddr, spec.srcHistory...) // when diff --git a/x/wasm/keeper/query_plugins.go b/x/wasm/keeper/query_plugins.go index 5608e01d00..fa352da3e3 100644 --- a/x/wasm/keeper/query_plugins.go +++ b/x/wasm/keeper/query_plugins.go @@ -153,22 +153,22 @@ func (e QueryPlugins) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, reques func BankQuerier(bankKeeper types.BankViewKeeper) func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) { return func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) { if request.AllBalances != nil { - addr, err := sdk.AccAddressFromBech32(request.AllBalances.Address) + err := sdk.ValidateAccAddress(request.AllBalances.Address) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address) } - coins := bankKeeper.GetAllBalances(ctx, addr) + coins := bankKeeper.GetAllBalances(ctx, sdk.AccAddress(request.AllBalances.Address)) res := wasmvmtypes.AllBalancesResponse{ Amount: convertSdkCoinsToWasmCoins(coins), } return json.Marshal(res) } if request.Balance != nil { - addr, err := sdk.AccAddressFromBech32(request.Balance.Address) + err := sdk.ValidateAccAddress(request.Balance.Address) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address) } - coins := bankKeeper.GetAllBalances(ctx, addr) + coins := bankKeeper.GetAllBalances(ctx, sdk.AccAddress(request.Balance.Address)) amount := coins.AmountOf(request.Balance.Denom) res := wasmvmtypes.BalanceResponse{ Amount: wasmvmtypes.Coin{ @@ -320,11 +320,11 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee return json.Marshal(res) } if request.Validator != nil { - valAddr, err := sdk.ValAddressFromBech32(request.Validator.Address) + err := sdk.ValidateValAddress(request.Validator.Address) if err != nil { return nil, err } - v, found := keeper.GetValidator(ctx, valAddr) + v, found := keeper.GetValidator(ctx, sdk.ValAddress(request.Validator.Address)) res := wasmvmtypes.ValidatorResponse{} if found { res.Validator = &wasmvmtypes.Validator{ @@ -337,11 +337,11 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee return json.Marshal(res) } if request.AllDelegations != nil { - delegator, err := sdk.AccAddressFromBech32(request.AllDelegations.Delegator) + err := sdk.ValidateAccAddress(request.AllDelegations.Delegator) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllDelegations.Delegator) } - sdkDels := keeper.GetAllDelegatorDelegations(ctx, delegator) + sdkDels := keeper.GetAllDelegatorDelegations(ctx, sdk.AccAddress(request.AllDelegations.Delegator)) delegations, err := sdkToDelegations(ctx, keeper, sdkDels) if err != nil { return nil, err @@ -352,17 +352,18 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee return json.Marshal(res) } if request.Delegation != nil { - delegator, err := sdk.AccAddressFromBech32(request.Delegation.Delegator) + err := sdk.ValidateAccAddress(request.Delegation.Delegator) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Delegator) } - validator, err := sdk.ValAddressFromBech32(request.Delegation.Validator) + err = sdk.ValidateValAddress(request.Delegation.Validator) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator) } var res wasmvmtypes.DelegationResponse - d, found := keeper.GetDelegation(ctx, delegator, validator) + d, found := keeper.GetDelegation(ctx, sdk.AccAddress(request.Delegation.Delegator), + sdk.ValAddress(request.Delegation.Validator)) if found { res.Delegation, err = sdkToFullDelegation(ctx, keeper, distKeeper, d) if err != nil { @@ -380,27 +381,27 @@ func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations [ bondDenom := keeper.BondDenom(ctx) for i, d := range delegations { - delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) + err := sdk.ValidateAccAddress(d.DelegatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "delegator address") } - valAddr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) + err = sdk.ValidateValAddress(d.ValidatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "validator address") } // shares to amount logic comes from here: // x/staking/keeper/querier.go DelegationToDelegationResponse - /// https://github.com/line/lfb-sdk/blob/3ccf3913f53e2a9ccb4be8429bee32e67669e89a/x/staking/keeper/querier.go#L450 - val, found := keeper.GetValidator(ctx, valAddr) + /// https://github.com/cosmos/cosmos-sdk/blob/3ccf3913f53e2a9ccb4be8429bee32e67669e89a/x/staking/keeper/querier.go#L450 + val, found := keeper.GetValidator(ctx, sdk.ValAddress(d.ValidatorAddress)) if !found { return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") } amount := sdk.NewCoin(bondDenom, val.TokensFromShares(d.Shares).TruncateInt()) result[i] = wasmvmtypes.Delegation{ - Delegator: delAddr.String(), - Validator: valAddr.String(), + Delegator: sdk.AccAddress(d.DelegatorAddress).String(), + Validator: sdk.ValAddress(d.ValidatorAddress).String(), Amount: convertSdkCoinToWasmCoin(amount), } } @@ -408,15 +409,15 @@ func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations [ } func sdkToFullDelegation(ctx sdk.Context, keeper types.StakingKeeper, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) (*wasmvmtypes.FullDelegation, error) { - delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + err := sdk.ValidateAccAddress(delegation.DelegatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "delegator address") } - valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + err = sdk.ValidateValAddress(delegation.ValidatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "validator address") } - val, found := keeper.GetValidator(ctx, valAddr) + val, found := keeper.GetValidator(ctx, sdk.ValAddress(delegation.ValidatorAddress)) if !found { return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") } @@ -431,7 +432,8 @@ func sdkToFullDelegation(ctx sdk.Context, keeper types.StakingKeeper, distKeeper // otherwise, it can redelegate the full amount // (there are cases of partial funds redelegated, but this is a start) redelegateCoins := wasmvmtypes.NewCoin(0, bondDenom) - if !keeper.HasReceivingRedelegation(ctx, delAddr, valAddr) { + if !keeper.HasReceivingRedelegation(ctx, sdk.AccAddress(delegation.DelegatorAddress), + sdk.ValAddress(delegation.ValidatorAddress)) { redelegateCoins = delegationCoins } @@ -445,8 +447,8 @@ func sdkToFullDelegation(ctx sdk.Context, keeper types.StakingKeeper, distKeeper } return &wasmvmtypes.FullDelegation{ - Delegator: delAddr.String(), - Validator: valAddr.String(), + Delegator: sdk.AccAddress(delegation.DelegatorAddress).String(), + Validator: sdk.ValAddress(delegation.ValidatorAddress).String(), Amount: delegationCoins, AccumulatedRewards: accRewards, CanRedelegate: redelegateCoins, @@ -481,18 +483,18 @@ func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper, func WasmQuerier(wasm wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { return func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { if request.Smart != nil { - addr, err := sdk.AccAddressFromBech32(request.Smart.ContractAddr) + err := sdk.ValidateAccAddress(request.Smart.ContractAddr) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Smart.ContractAddr) } - return wasm.QuerySmart(ctx, addr, request.Smart.Msg) + return wasm.QuerySmart(ctx, sdk.AccAddress(request.Smart.ContractAddr), request.Smart.Msg) } if request.Raw != nil { - addr, err := sdk.AccAddressFromBech32(request.Raw.ContractAddr) + err := sdk.ValidateAccAddress(request.Raw.ContractAddr) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Raw.ContractAddr) } - return wasm.QueryRaw(ctx, addr, request.Raw.Key), nil + return wasm.QueryRaw(ctx, sdk.AccAddress(request.Raw.ContractAddr), request.Raw.Key), nil } return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown WasmQuery variant"} } diff --git a/x/wasm/keeper/reflect_test.go b/x/wasm/keeper/reflect_test.go index 551434ba06..77ef418599 100644 --- a/x/wasm/keeper/reflect_test.go +++ b/x/wasm/keeper/reflect_test.go @@ -108,7 +108,7 @@ func TestReflectContractSend(t *testing.T) { // creator instantiates a contract and gives it tokens reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) + reflectAddr, _, err := keeper.Instantiate(ctx, reflectID, creator, "", []byte("{}"), "reflect contract 2", reflectStart) require.NoError(t, err) require.NotEmpty(t, reflectAddr) @@ -120,7 +120,7 @@ func TestReflectContractSend(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) escrowStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 25000)) - escrowAddr, _, err := keeper.Instantiate(ctx, escrowID, creator, nil, initMsgBz, "escrow contract 2", escrowStart) + escrowAddr, _, err := keeper.Instantiate(ctx, escrowID, creator, "", initMsgBz, "escrow contract 2", escrowStart) require.NoError(t, err) require.NotEmpty(t, escrowAddr) @@ -184,7 +184,7 @@ func TestReflectCustomMsg(t *testing.T) { // creator instantiates a contract and gives it tokens contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - contractAddr, _, err := keeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keeper.Instantiate(ctx, codeID, creator, "", []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -275,7 +275,7 @@ func TestMaskReflectCustomQuery(t *testing.T) { // creator instantiates a contract and gives it tokens contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -326,7 +326,7 @@ func TestReflectStargateQuery(t *testing.T) { require.Equal(t, uint64(1), codeID) // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -402,7 +402,7 @@ func TestMaskReflectWasmQueries(t *testing.T) { // creator instantiates a contract and gives it tokens reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) + reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, "", []byte("{}"), "reflect contract 2", reflectStart) require.NoError(t, err) require.NotEmpty(t, reflectAddr) @@ -474,7 +474,7 @@ func TestWasmRawQueryWithNil(t *testing.T) { // creator instantiates a contract and gives it tokens reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) + reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, "", []byte("{}"), "reflect contract 2", reflectStart) require.NoError(t, err) require.NotEmpty(t, reflectAddr) diff --git a/x/wasm/keeper/staking_test.go b/x/wasm/keeper/staking_test.go index 819c1a8546..83d855f52f 100644 --- a/x/wasm/keeper/staking_test.go +++ b/x/wasm/keeper/staking_test.go @@ -123,7 +123,7 @@ func TestInitializeStaking(t *testing.T) { initBz, err := json.Marshal(&initMsg) require.NoError(t, err) - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) + stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, "", initBz, "staking derivates - DRV", nil) require.NoError(t, err) require.NotEmpty(t, stakingAddr) @@ -136,14 +136,14 @@ func TestInitializeStaking(t *testing.T) { Name: "Missing Validator", Symbol: "MISS", Decimals: 0, - Validator: sdk.ValAddress(bob), + Validator: bob.ToValAddress(), ExitTax: sdk.MustNewDecFromStr("0.10"), MinWithdrawl: "100", } badBz, err := json.Marshal(&badInitMsg) require.NoError(t, err) - _, _, err = k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, badBz, "missing validator", nil) + _, _, err = k.ContractKeeper.Instantiate(ctx, stakingID, creator, "", badBz, "missing validator", nil) require.Error(t, err) // no changes to bonding shares @@ -205,7 +205,7 @@ func initializeStaking(t *testing.T) initInfo { initBz, err := json.Marshal(&initMsg) require.NoError(t, err) - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) + stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, "", initBz, "staking derivates - DRV", nil) require.NoError(t, err) require.NotEmpty(t, stakingAddr) @@ -451,7 +451,7 @@ func TestQueryStakingInfo(t *testing.T) { require.Equal(t, uint64(2), maskID) // creator instantiates a contract and gives it tokens - maskAddr, _, err := initInfo.contractKeeper.Instantiate(ctx, maskID, creator, nil, []byte("{}"), "mask contract 2", nil) + maskAddr, _, err := initInfo.contractKeeper.Instantiate(ctx, maskID, creator, "", []byte("{}"), "mask contract 2", nil) require.NoError(t, err) require.NotEmpty(t, maskAddr) @@ -511,7 +511,7 @@ func TestQueryStakingInfo(t *testing.T) { require.Contains(t, valInfo.MaxChangeRate, "0.010") // missing validator - noVal := sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()) + noVal := sdk.BytesToValAddress(secp256k1.GenPrivKey().PubKey().Address()) reflectNoValidatorQuery := ReflectQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ Validator: &wasmvmtypes.ValidatorQuery{ Address: noVal.String(), @@ -655,7 +655,7 @@ func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper stakingkeeper.Kee privKey := secp256k1.GenPrivKey() pubKey := privKey.PubKey() - addr := sdk.ValAddress(pubKey.Address()) + addr := sdk.BytesToValAddress(pubKey.Address()) pkAny, err := codectypes.NewAnyWithValue(pubKey) require.NoError(t, err) diff --git a/x/wasm/keeper/submsg_test.go b/x/wasm/keeper/submsg_test.go index 3420a054a6..8ebd35079d 100644 --- a/x/wasm/keeper/submsg_test.go +++ b/x/wasm/keeper/submsg_test.go @@ -36,7 +36,7 @@ func TestDispatchSubMsgSuccessCase(t *testing.T) { require.Equal(t, uint64(1), codeID) // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -153,7 +153,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { } initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - hackatomAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, hackatomID, uploader, nil, initMsgBz, "hackatom demo", contractStart) + hackatomAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, hackatomID, uploader, "", initMsgBz, "hackatom demo", contractStart) require.NoError(t, err) validBankSend := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { @@ -239,7 +239,6 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { // data field is the raw canonical address // QUESTION: why not types.MsgInstantiateContractResponse? difference between calling Router and Service? - assert.Len(t, response.Ok.Data, 20) resAddr := sdk.AccAddress(response.Ok.Data) assert.Equal(t, eventAddr, resAddr.String()) } @@ -314,7 +313,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, contractStart) _, _, empty := keyPubAddr() - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), fmt.Sprintf("contract %s", name), contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, "", []byte("{}"), fmt.Sprintf("contract %s", name), contractStart) require.NoError(t, err) msg := tc.msg(contractAddr.String(), empty.String()) @@ -405,7 +404,7 @@ func TestDispatchSubMsgEncodeToNoSdkMsg(t *testing.T) { require.NoError(t, err) // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -473,7 +472,7 @@ func TestDispatchSubMsgConditionalReplyOn(t *testing.T) { require.NoError(t, err) // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) goodSend := wasmvmtypes.CosmosMsg{ diff --git a/x/wasm/keeper/test_common.go b/x/wasm/keeper/test_common.go index dcdd7c6e24..056d590c31 100644 --- a/x/wasm/keeper/test_common.go +++ b/x/wasm/keeper/test_common.go @@ -364,11 +364,12 @@ func TestHandler(k types.ContractOpsKeeper) sdk.Handler { } func handleStoreCode(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgStoreCode) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - codeID, err := k.Create(ctx, senderAddr, msg.WASMByteCode, msg.Source, msg.Builder, msg.InstantiatePermission) + codeID, err := k.Create(ctx, sdk.AccAddress(msg.Sender), msg.WASMByteCode, msg.Source, msg.Builder, + msg.InstantiatePermission) if err != nil { return nil, err } @@ -380,38 +381,38 @@ func handleStoreCode(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgS } func handleInstantiate(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgInstantiateContract) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - var adminAddr sdk.AccAddress if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { + if err = sdk.ValidateAccAddress(msg.Admin); err != nil { return nil, sdkerrors.Wrap(err, "admin") } } - contractAddr, _, err := k.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.InitMsg, msg.Label, msg.Funds) + contractAddr, _, err := k.Instantiate(ctx, msg.CodeID, sdk.AccAddress(msg.Sender), sdk.AccAddress(msg.Admin), + msg.InitMsg, msg.Label, msg.Funds) if err != nil { return nil, err } return &sdk.Result{ - Data: contractAddr, + Data: contractAddr.Bytes(), Events: ctx.EventManager().Events().ToABCIEvents(), }, nil } func handleExecute(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgExecuteContract) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + err := sdk.ValidateAccAddress(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) + err = sdk.ValidateAccAddress(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "admin") } - res, err := k.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) + res, err := k.Execute(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), msg.Msg, msg.Funds) if err != nil { return nil, err } @@ -623,6 +624,6 @@ func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { key := ed25519.GenPrivKeyFromSecret(seed) pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) + addr := sdk.BytesToAccAddress(pub.Address()) return key, pub, addr } diff --git a/x/wasm/keeper/test_fuzz.go b/x/wasm/keeper/test_fuzz.go index 0cc209d0da..96bcfc9136 100644 --- a/x/wasm/keeper/test_fuzz.go +++ b/x/wasm/keeper/test_fuzz.go @@ -12,9 +12,11 @@ import ( var ModelFuzzers = []interface{}{FuzzAddr, FuzzAddrString, FuzzAbsoluteTxPosition, FuzzContractInfo, FuzzStateModel, FuzzAccessType, FuzzAccessConfig, FuzzContractCodeHistory} func FuzzAddr(m *sdk.AccAddress, c fuzz.Continue) { - *m = make([]byte, 20) - c.Read(*m) + addrBytes := make([]byte, 20) + c.Read(addrBytes) + *m = sdk.BytesToAccAddress(addrBytes) } + func FuzzAddrString(m *string, c fuzz.Continue) { var x sdk.AccAddress FuzzAddr(&x, c) diff --git a/x/wasm/linkwasmd/app/export.go b/x/wasm/linkwasmd/app/export.go index 97ac3891be..e74c8a799a 100644 --- a/x/wasm/linkwasmd/app/export.go +++ b/x/wasm/linkwasmd/app/export.go @@ -79,16 +79,17 @@ func (app *LinkApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ // withdraw all delegator rewards dels := app.StakingKeeper.GetAllDelegations(ctx) for _, delegation := range dels { - valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + err := sdk.ValidateValAddress(delegation.ValidatorAddress) if err != nil { panic(err) } - delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + err := sdk.ValidateAccAddress(delegation.DelegatorAddress) if err != nil { panic(err) } - _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(delegation.DelegatorAddress), + sdk.ValAddress(delegation.ValidatorAddress)) } // clear validator slash events @@ -115,14 +116,8 @@ func (app *LinkApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ // reinitialize all delegations for _, del := range dels { - valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) - if err != nil { - panic(err) - } - delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - panic(err) - } + valAddr := sdk.ValAddress(del.ValidatorAddress) + delAddr := sdk.AccAddress(del.DelegatorAddress) app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) } diff --git a/x/wasm/linkwasmd/app/test_helpers.go b/x/wasm/linkwasmd/app/test_helpers.go index 3b952bd449..c92945441f 100644 --- a/x/wasm/linkwasmd/app/test_helpers.go +++ b/x/wasm/linkwasmd/app/test_helpers.go @@ -199,7 +199,7 @@ func createRandomAccounts(accNum int) []sdk.AccAddress { testAddrs := make([]sdk.AccAddress, accNum) for i := 0; i < accNum; i++ { pk := ed25519.GenPrivKey().PubKey() - testAddrs[i] = sdk.AccAddress(pk.Address()) + testAddrs[i] = sdk.BytesToAccAddress(pk.Address()) } return testAddrs @@ -235,7 +235,7 @@ func AddTestAddrsFromPubKeys(app *LinkApp, ctx sdk.Context, pubKeys []cryptotype // fill all the addresses with some coins, set the loose pool tokens simultaneously for _, pubKey := range pubKeys { - saveAccount(app, ctx, sdk.AccAddress(pubKey.Address()), initCoins) + saveAccount(app, ctx, sdk.BytesAccAddress(pubKey.Address()), initCoins) } } @@ -296,19 +296,19 @@ func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress { func TestAddr(addr string, bech string) (sdk.AccAddress, error) { res, err := sdk.AccAddressFromHex(addr) if err != nil { - return nil, err + return "", err } bechexpected := res.String() if bech != bechexpected { - return nil, fmt.Errorf("bech encoding doesn't match reference") + return "", fmt.Errorf("bech encoding doesn't match reference") } - bechres, err := sdk.AccAddressFromBech32(bech) + err = sdk.ValidateAccAddress(bech) if err != nil { - return nil, err + return "", err } - if !bytes.Equal(bechres, res) { - return nil, err + if !bytes.Equal(sdk.AccAddress(bech), res) { + return "", err } return res, nil diff --git a/x/wasm/linkwasmd/cmd/linkwasmd/cmd/genaccounts.go b/x/wasm/linkwasmd/cmd/linkwasmd/cmd/genaccounts.go index 76384da146..b130f93897 100644 --- a/x/wasm/linkwasmd/cmd/linkwasmd/cmd/genaccounts.go +++ b/x/wasm/linkwasmd/cmd/linkwasmd/cmd/genaccounts.go @@ -48,7 +48,8 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa config.SetRoot(clientCtx.HomeDir) - addr, err := sdk.AccAddressFromBech32(args[0]) + addr := sdk.AccAddress(args[0]) + err := sdk.ValidateAccAddress(args[0]) if err != nil { inBuf := bufio.NewReader(cmd.InOrStdin()) keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend) diff --git a/x/wasm/module_test.go b/x/wasm/module_test.go index 066045f2b5..702e2a72b5 100644 --- a/x/wasm/module_test.go +++ b/x/wasm/module_test.go @@ -48,7 +48,7 @@ func setupTest(t *testing.T) testData { func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { key := ed25519.GenPrivKey() pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) + addr := sdk.BytesToAccAddress(pub.Address()) return key, pub, addr } @@ -433,7 +433,7 @@ func TestHandleExecute(t *testing.T) { assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, creatorAcct.GetAddress())) // ensure contract has updated balance - contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) + contractAddr := sdk.AccAddress(contractBech32Addr) contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) require.NotNil(t, contractAcct) assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) @@ -557,7 +557,7 @@ func TestHandleExecuteEscrow(t *testing.T) { assert.Equal(t, deposit.Add(topUp...), balance) // ensure contract has updated balance - contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) + contractAddr := sdk.AccAddress(contractBech32Addr) contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) require.NotNil(t, contractAcct) assert.Equal(t, sdk.Coins(nil), data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) diff --git a/x/wasm/types/genesis.go b/x/wasm/types/genesis.go index b56f8705e1..8873f107a7 100644 --- a/x/wasm/types/genesis.go +++ b/x/wasm/types/genesis.go @@ -54,7 +54,7 @@ func (c Code) ValidateBasic() error { } func (c Contract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(c.ContractAddress); err != nil { + if err := sdk.ValidateAccAddress(c.ContractAddress); err != nil { return sdkerrors.Wrap(err, "contract address") } if err := c.ContractInfo.ValidateBasic(); err != nil { diff --git a/x/wasm/types/keys.go b/x/wasm/types/keys.go index 56f6cdea61..0172288a28 100644 --- a/x/wasm/types/keys.go +++ b/x/wasm/types/keys.go @@ -56,10 +56,10 @@ func GetContractStorePrefix(addr sdk.AccAddress) []byte { func GetContractByCreatedSecondaryIndexKey(contractAddr sdk.AccAddress, c ContractCodeHistoryEntry) []byte { prefix := GetContractByCodeIDSecondaryIndexPrefix(c.CodeID) prefixLen := len(prefix) - r := make([]byte, prefixLen+AbsoluteTxPositionLen+sdk.AddrLen) + r := make([]byte, prefixLen+AbsoluteTxPositionLen+len(contractAddr.Bytes())) copy(r[0:], prefix) copy(r[prefixLen:], c.Updated.Bytes()) - copy(r[prefixLen+AbsoluteTxPositionLen:], contractAddr) + copy(r[prefixLen+AbsoluteTxPositionLen:], contractAddr.Bytes()) return r } @@ -85,10 +85,8 @@ func GetContractCodeHistoryElementKey(contractAddr sdk.AccAddress, pos uint64) [ // GetContractCodeHistoryElementPrefix returns the key prefix for a contract code history entry: `` func GetContractCodeHistoryElementPrefix(contractAddr sdk.AccAddress) []byte { - prefixLen := len(ContractCodeHistoryElementPrefix) - r := make([]byte, prefixLen+sdk.AddrLen) - copy(r[0:], ContractCodeHistoryElementPrefix) - copy(r[prefixLen:], contractAddr) + r := sdk.CopyBytes(ContractCodeHistoryElementPrefix) + r = append(r, contractAddr.Bytes()...) return r } diff --git a/x/wasm/types/keys_test.go b/x/wasm/types/keys_test.go index 5a271aed6a..0fb997d5e2 100644 --- a/x/wasm/types/keys_test.go +++ b/x/wasm/types/keys_test.go @@ -33,13 +33,13 @@ func TestGetContractByCreatedSecondaryIndexKey(t *testing.T) { CodeID: 1, Updated: &AbsoluteTxPosition{2 + 1<<(8*7), 3 + 1<<(8*7)}, } - addr := bytes.Repeat([]byte{4}, sdk.AddrLen) + addr := sdk.BytesToAccAddress(bytes.Repeat([]byte{4}, sdk.BytesAddrLen)) got := GetContractByCreatedSecondaryIndexKey(addr, e) exp := []byte{6, // prefix 0, 0, 0, 0, 0, 0, 0, 1, // codeID 1, 0, 0, 0, 0, 0, 0, 2, // height 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address + 0x6c, 0x69, 0x6e, 0x6b, 0x31, 0x71, 0x73, 0x7a, 0x71, 0x67, 0x70, 0x71, 0x79, 0x71, 0x73, 0x7a, 0x71, 0x67, 0x70, 0x71, 0x79, 0x71, 0x73, 0x7a, 0x71, 0x67, 0x70, 0x71, 0x79, 0x71, 0x73, 0x7a, 0x71, 0x67, 0x70, 0x71, 0x79, 0x68, 0x65, 0x70, 0x61, 0x73, 0x6c, // address } assert.Equal(t, exp, got) } diff --git a/x/wasm/types/params.go b/x/wasm/types/params.go index dcec948e5c..0d665b5ed9 100644 --- a/x/wasm/types/params.go +++ b/x/wasm/types/params.go @@ -51,7 +51,8 @@ func (a AccessType) With(addr sdk.AccAddress) AccessConfig { case AccessTypeNobody: return AllowNobody case AccessTypeOnlyAddress: - if err := sdk.VerifyAddressFormat(addr); err != nil { + addrBytes, _ := sdk.AccAddressToBytes(addr.String()) + if err := sdk.VerifyAddressFormat(addrBytes); err != nil { panic(err) } return AccessConfig{Permission: AccessTypeOnlyAddress, Address: addr.String()} @@ -246,7 +247,7 @@ func (a AccessConfig) ValidateBasic() error { } return nil case AccessTypeOnlyAddress: - _, err := sdk.AccAddressFromBech32(a.Address) + err := sdk.ValidateAccAddress(a.Address) return err } return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", a.Permission) diff --git a/x/wasm/types/params_test.go b/x/wasm/types/params_test.go index 9ffd926390..cfbc0abb25 100644 --- a/x/wasm/types/params_test.go +++ b/x/wasm/types/params_test.go @@ -13,8 +13,8 @@ import ( func TestValidateParams(t *testing.T) { var ( - anyAddress sdk.AccAddress = make([]byte, sdk.AddrLen) - invalidAddress = "invalid address" + anyAddress = sdk.BytesToAccAddress(make([]byte, sdk.BytesAddrLen)) + invalidAddress = "invalid address" ) specs := map[string]struct { diff --git a/x/wasm/types/proposal.go b/x/wasm/types/proposal.go index 93aea40f3a..366c7c8698 100644 --- a/x/wasm/types/proposal.go +++ b/x/wasm/types/proposal.go @@ -92,7 +92,7 @@ func (p StoreCodeProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { + if err := sdk.ValidateAccAddress(p.RunAs); err != nil { return sdkerrors.Wrap(err, "run as") } @@ -167,7 +167,7 @@ func (p InstantiateContractProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { + if err := sdk.ValidateAccAddress(p.RunAs); err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "run as") } @@ -184,7 +184,7 @@ func (p InstantiateContractProposal) ValidateBasic() error { } if len(p.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { + if err := sdk.ValidateAccAddress(p.Admin); err != nil { return err } } @@ -252,10 +252,10 @@ func (p MigrateContractProposal) ValidateBasic() error { if p.CodeID == 0 { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code_id is required") } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { + if err := sdk.ValidateAccAddress(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { + if err := sdk.ValidateAccAddress(p.RunAs); err != nil { return sdkerrors.Wrap(err, "run as") } if !json.Valid(p.MigrateMsg) { @@ -312,10 +312,10 @@ func (p UpdateAdminProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { + if err := sdk.ValidateAccAddress(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } - if _, err := sdk.AccAddressFromBech32(p.NewAdmin); err != nil { + if err := sdk.ValidateAccAddress(p.NewAdmin); err != nil { return sdkerrors.Wrap(err, "new admin") } return nil @@ -348,7 +348,7 @@ func (p ClearAdminProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { + if err := sdk.ValidateAccAddress(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } return nil @@ -444,7 +444,7 @@ func (p UpdateContractStatusProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { + if err := sdk.ValidateAccAddress(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } found := false diff --git a/x/wasm/types/proposal_test.go b/x/wasm/types/proposal_test.go index b18eaf2bb2..cae6a564dd 100644 --- a/x/wasm/types/proposal_test.go +++ b/x/wasm/types/proposal_test.go @@ -95,8 +95,8 @@ func TestValidateProposalCommons(t *testing.T) { func TestValidateStoreCodeProposal(t *testing.T) { var ( - anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, sdk.AddrLen) - invalidAddress = "invalid address" + anyAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x0}, sdk.BytesAddrLen)) + invalidAddress = "invalid address" ) specs := map[string]struct { diff --git a/x/wasm/types/test_fixtures.go b/x/wasm/types/test_fixtures.go index 2f8fd19bd0..c8fe3ee32e 100644 --- a/x/wasm/types/test_fixtures.go +++ b/x/wasm/types/test_fixtures.go @@ -200,7 +200,7 @@ func StoreCodeProposalFixture(mutators ...func(*StoreCodeProposal)) *StoreCodePr func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractProposal)) *InstantiateContractProposal { var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) + anyValidAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, sdk.BytesAddrLen)) initMsg = struct { Verifier sdk.AccAddress `json:"verifier"` @@ -235,7 +235,7 @@ func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractP func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal)) *MigrateContractProposal { var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) + anyValidAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, sdk.BytesAddrLen)) migMsg = struct { Verifier sdk.AccAddress `json:"verifier"` diff --git a/x/wasm/types/tx.go b/x/wasm/types/tx.go index cfa12b1292..a67878ad84 100644 --- a/x/wasm/types/tx.go +++ b/x/wasm/types/tx.go @@ -17,7 +17,7 @@ func (msg MsgStoreCode) Type() string { } func (msg MsgStoreCode) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return err } @@ -46,10 +46,7 @@ func (msg MsgStoreCode) GetSignBytes() []byte { } func (msg MsgStoreCode) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} } @@ -62,7 +59,7 @@ func (msg MsgInstantiateContract) Type() string { } func (msg MsgInstantiateContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } @@ -80,7 +77,7 @@ func (msg MsgInstantiateContract) ValidateBasic() error { } if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { + if err := sdk.ValidateAccAddress(msg.Admin); err != nil { return sdkerrors.Wrap(err, "admin") } } @@ -96,10 +93,7 @@ func (msg MsgInstantiateContract) GetSignBytes() []byte { } func (msg MsgInstantiateContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} } @@ -113,7 +107,7 @@ func (msg MsgStoreCodeAndInstantiateContract) Type() string { } func (msg MsgStoreCodeAndInstantiateContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return err } @@ -135,7 +129,7 @@ func (msg MsgStoreCodeAndInstantiateContract) ValidateBasic() error { } } - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } @@ -148,7 +142,7 @@ func (msg MsgStoreCodeAndInstantiateContract) ValidateBasic() error { } if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { + if err := sdk.ValidateAccAddress(msg.Admin); err != nil { return sdkerrors.Wrap(err, "admin") } } @@ -164,10 +158,7 @@ func (msg MsgStoreCodeAndInstantiateContract) GetSignBytes() []byte { } func (msg MsgStoreCodeAndInstantiateContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} } @@ -180,10 +171,10 @@ func (msg MsgExecuteContract) Type() string { } func (msg MsgExecuteContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { + if err := sdk.ValidateAccAddress(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } @@ -202,12 +193,8 @@ func (msg MsgExecuteContract) GetSignBytes() []byte { } func (msg MsgExecuteContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} - } func (msg MsgMigrateContract) Route() string { @@ -222,10 +209,10 @@ func (msg MsgMigrateContract) ValidateBasic() error { if msg.CodeID == 0 { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") } - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { + if err := sdk.ValidateAccAddress(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } if !json.Valid(msg.MigrateMsg) { @@ -241,10 +228,7 @@ func (msg MsgMigrateContract) GetSignBytes() []byte { } func (msg MsgMigrateContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} } @@ -258,13 +242,13 @@ func (msg MsgUpdateAdmin) Type() string { } func (msg MsgUpdateAdmin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { + if err := sdk.ValidateAccAddress(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } - if _, err := sdk.AccAddressFromBech32(msg.NewAdmin); err != nil { + if err := sdk.ValidateAccAddress(msg.NewAdmin); err != nil { return sdkerrors.Wrap(err, "new admin") } if strings.EqualFold(msg.Sender, msg.NewAdmin) { @@ -279,12 +263,8 @@ func (msg MsgUpdateAdmin) GetSignBytes() []byte { } func (msg MsgUpdateAdmin) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} - } func (msg MsgClearAdmin) Route() string { @@ -296,10 +276,10 @@ func (msg MsgClearAdmin) Type() string { } func (msg MsgClearAdmin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { + if err := sdk.ValidateAccAddress(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } return nil @@ -311,12 +291,8 @@ func (msg MsgClearAdmin) GetSignBytes() []byte { } func (msg MsgClearAdmin) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} - } func (msg MsgUpdateContractStatus) Route() string { @@ -328,10 +304,10 @@ func (msg MsgUpdateContractStatus) Type() string { } func (msg MsgUpdateContractStatus) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { + if err := sdk.ValidateAccAddress(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { + if err := sdk.ValidateAccAddress(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } found := false @@ -352,10 +328,7 @@ func (msg MsgUpdateContractStatus) GetSignBytes() []byte { } func (msg MsgUpdateContractStatus) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } + senderAddr := sdk.AccAddress(msg.Sender) return []sdk.AccAddress{senderAddr} } diff --git a/x/wasm/types/tx_test.go b/x/wasm/types/tx_test.go index d0a2681430..be8495b7cf 100644 --- a/x/wasm/types/tx_test.go +++ b/x/wasm/types/tx_test.go @@ -44,7 +44,7 @@ func TestStoreCodeValidation(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() cases := map[string]struct { msg MsgStoreCode @@ -137,7 +137,7 @@ func TestInstantiateContractValidation(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() cases := map[string]struct { msg MsgInstantiateContract @@ -245,7 +245,7 @@ func TestStoreCodeAndInstantiateContractValidation(t *testing.T) { badAddress := bad.String() require.NoError(t, err) // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() cases := map[string]struct { msg MsgStoreCodeAndInstantiateContract @@ -394,7 +394,7 @@ func TestExecuteContractValidation(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() cases := map[string]struct { msg MsgExecuteContract @@ -503,9 +503,9 @@ func TestMsgUpdateAdministrator(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - otherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x1}, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() + otherGoodAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, 20)).String() + anotherGoodAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, 20)).String() specs := map[string]struct { src MsgUpdateAdmin @@ -575,8 +575,8 @@ func TestMsgClearAdministrator(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() + anotherGoodAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, 20)).String() specs := map[string]struct { src MsgClearAdmin @@ -626,8 +626,8 @@ func TestMsgMigrateContract(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() + anotherGoodAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, 20)).String() specs := map[string]struct { src MsgMigrateContract @@ -713,8 +713,8 @@ func TestMsgUpdateContractStatus(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() + goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() + anotherGoodAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, 20)).String() specs := map[string]struct { src MsgUpdateContractStatus diff --git a/x/wasm/types/types.go b/x/wasm/types/types.go index fb0f02dde8..70f1865563 100644 --- a/x/wasm/types/types.go +++ b/x/wasm/types/types.go @@ -68,7 +68,7 @@ func (c CodeInfo) ValidateBasic() error { if len(c.CodeHash) == 0 { return sdkerrors.Wrap(ErrEmpty, "code hash") } - if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { + if err := sdk.ValidateAccAddress(c.Creator); err != nil { return sdkerrors.Wrap(err, "creator") } if err := validateSourceURL(c.Source); err != nil { @@ -124,11 +124,11 @@ func (c *ContractInfo) ValidateBasic() error { if c.CodeID == 0 { return sdkerrors.Wrap(ErrEmpty, "code id") } - if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { + if err := sdk.ValidateAccAddress(c.Creator); err != nil { return sdkerrors.Wrap(err, "creator") } if len(c.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(c.Admin); err != nil { + if err := sdk.ValidateAccAddress(c.Admin); err != nil { return sdkerrors.Wrap(err, "admin") } } @@ -237,12 +237,9 @@ func (c *ContractInfo) ResetFromGenesis(ctx sdk.Context) ContractCodeHistoryEntr // AdminAddr convert into sdk.AccAddress or nil when not set func (c *ContractInfo) AdminAddr() sdk.AccAddress { if c.Admin == "" { - return nil - } - admin, err := sdk.AccAddressFromBech32(c.Admin) - if err != nil { // should never happen - panic(err.Error()) + return "" } + admin := sdk.AccAddress(c.Admin) return admin } diff --git a/x/wasm/types/types_test.go b/x/wasm/types/types_test.go index 18eb2cf756..94f2c2277b 100644 --- a/x/wasm/types/types_test.go +++ b/x/wasm/types/types_test.go @@ -193,8 +193,8 @@ func TestContractInfoSetExtension(t *testing.T) { } func TestContractInfoMarshalUnmarshal(t *testing.T) { - var myAddr sdk.AccAddress = rand.Bytes(sdk.AddrLen) - var myOtherAddr sdk.AccAddress = rand.Bytes(sdk.AddrLen) + var myAddr = sdk.BytesToAccAddress(rand.Bytes(sdk.BytesAddrLen)) + var myOtherAddr = sdk.BytesToAccAddress(rand.Bytes(sdk.BytesAddrLen)) var anyPos = AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} anyTime := time.Now().UTC() @@ -314,7 +314,7 @@ func TestContractInfoReadExtension(t *testing.T) { func TestNewEnv(t *testing.T) { myTime := time.Unix(0, 1619700924259075000) t.Logf("++ unix: %d", myTime.UnixNano()) - var myContractAddr sdk.AccAddress = randBytes(sdk.AddrLen) + var myContractAddr = sdk.BytesToAccAddress(rand.Bytes(sdk.BytesAddrLen)) specs := map[string]struct { srcCtx sdk.Context exp wasmvmtypes.Env