diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e5da624cd..63713d82b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Breaking Changes * (proto) [\#564](https://github.com/line/lbm-sdk/pull/564) change gRPC path to original cosmos path +* (global) [\#603](https://github.com/line/lbm-sdk/pull/603) apply types/address.go from cosmos-sdk@v0.45.1 ### Build, CI diff --git a/baseapp/accountwgs_test.go b/baseapp/accountwgs_test.go index d2e99d24de..e7d98089f0 100644 --- a/baseapp/accountwgs_test.go +++ b/baseapp/accountwgs_test.go @@ -88,7 +88,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.BytesToAccAddress(priv.PubKey().Address())) + addrs = append(addrs, sdk.AccAddress(priv.PubKey().Address())) } return addrs } diff --git a/baseapp/block_gas_test.go b/baseapp/block_gas_test.go index 00d5243339..0a7a060518 100644 --- a/baseapp/block_gas_test.go +++ b/baseapp/block_gas_test.go @@ -124,7 +124,7 @@ func TestBaseApp_BlockGas(t *testing.T) { require.Equal(t, []byte("ok"), okValue) } // check block gas is always consumed - baseGas := uint64(40043) // baseGas is the gas consumed before tx msg + baseGas := uint64(37352) // baseGas is the gas consumed before tx msg expGasConsumed := addUint64Saturating(tc.gasToConsume, baseGas) if expGasConsumed > txtypes.MaxGasWanted { // capped by gasLimit diff --git a/client/cmd.go b/client/cmd.go index cacf7e0465..d5e9f86952 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -220,15 +220,16 @@ func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err clientCtx = clientCtx.WithSignModeStr(signModeStr) } - if clientCtx.FeeGranter == "" || flagSet.Changed(flags.FlagFeeAccount) { + if clientCtx.FeeGranter == nil || flagSet.Changed(flags.FlagFeeAccount) { granter, _ := flagSet.GetString(flags.FlagFeeAccount) if granter != "" { - err := sdk.ValidateAccAddress(granter) + granterAcc, err := sdk.AccAddressFromBech32(granter) if err != nil { return clientCtx, err } - clientCtx = clientCtx.WithFeeGranterAddress(sdk.AccAddress(granter)) + + clientCtx = clientCtx.WithFeeGranterAddress(granterAcc) } } diff --git a/client/context.go b/client/context.go index ebb4a29156..575610a959 100644 --- a/client/context.go +++ b/client/context.go @@ -335,28 +335,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 "", "", 0, nil + return nil, "", 0, nil } if genOnly { - err := sdk.ValidateAccAddress(from) + addr, err := sdk.AccAddressFromBech32(from) if err != nil { - return sdk.AccAddress(from), "", 0, errors.Wrap(err, "must provide a valid Bech32 address in generate-only mode") + return nil, "", 0, errors.Wrap(err, "must provide a valid Bech32 address in generate-only mode") } - return sdk.AccAddress(from), "", 0, nil + return addr, "", 0, nil } var info keyring.Info - if err := sdk.ValidateAccAddress(from); err == nil { - info, err = kr.KeyByAddress(sdk.AccAddress(from)) + if addr, err := sdk.AccAddressFromBech32(from); err == nil { + info, err = kr.KeyByAddress(addr) if err != nil { - return sdk.AccAddress(from), "", 0, err + return nil, "", 0, err } } else { info, err = kr.Key(from) if err != nil { - return "", "", 0, err + return nil, "", 0, err } } diff --git a/client/debug/main.go b/client/debug/main.go index 9f8cbaff6f..fb80b93d6e 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -72,17 +72,17 @@ $ %s debug addr link19wgf6ymq2ur6r59st95e04e49m69z4al4fc982 RunE: func(cmd *cobra.Command, args []string) error { addrString := args[0] - var addrBytes []byte + var addr []byte // try hex, then bech32 var err error - addrBytes, err = hex.DecodeString(addrString) + addr, err = hex.DecodeString(addrString) if err != nil { var err2 error - addrBytes, err2 = sdk.AccAddressToBytes(addrString) + addr, err2 = sdk.AccAddressFromBech32(addrString) if err2 != nil { var err3 error - addrBytes, err3 = sdk.ValAddressToBytes(addrString) + addr, err3 = sdk.ValAddressFromBech32(addrString) if err3 != nil { return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3) @@ -91,13 +91,10 @@ $ %s debug addr link19wgf6ymq2ur6r59st95e04e49m69z4al4fc982 } } - accAddr := sdk.BytesToAccAddress(addrBytes) - valAddr := sdk.BytesToValAddress(addrBytes) - - 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) + cmd.Println("Address:", addr) + cmd.Printf("Address (hex): %X\n", addr) + cmd.Printf("Bech32 Acc: %s\n", sdk.AccAddress(addr)) + cmd.Printf("Bech32 Val: %s\n", sdk.ValAddress(addr)) return nil }, } diff --git a/client/keys/show.go b/client/keys/show.go index 367aca8df5..693b473529 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -169,11 +169,10 @@ func fetchKey(kb keyring.Keyring, keyref string) (keyring.Info, error) { if err == nil || !sdkerr.IsOf(err, sdkerr.ErrIO, sdkerr.ErrKeyNotFound) { return info, err } - err = sdk.ValidateAccAddress(keyref) + accAddr, err := sdk.AccAddressFromBech32(keyref) if err != nil { return info, err } - accAddr := sdk.AccAddress(keyref) info, err = kb.KeyByAddress(accAddr) return info, sdkerr.Wrap(err, "Invalid key") diff --git a/client/keys/show_test.go b/client/keys/show_test.go index 6a155d1577..0354f1844a 100644 --- a/client/keys/show_test.go +++ b/client/keys/show_test.go @@ -30,9 +30,7 @@ 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()) - acc := tmp.GetAddress() - addrBytes, _ := sdk.AccAddressToBytes(acc.String()) - require.Equal(t, "link1hhcvsf7nfj3ejxw8dz8tt22ns0rqkdr3rrh7xy", sdk.MustBech32ifyAddressBytes("link", addrBytes)) + require.Equal(t, "link1hhcvsf7nfj3ejxw8dz8tt22ns0rqkdr3rrh7xy", sdk.MustBech32ifyAddressBytes("link", tmp.GetAddress())) } func Test_showKeysCmd(t *testing.T) { diff --git a/client/query_test.go b/client/query_test.go index 234e4732dd..df17963e9b 100644 --- a/client/query_test.go +++ b/client/query_test.go @@ -50,7 +50,7 @@ func (s *IntegrationTestSuite) TestQueryABCIHeight() { req := abci.RequestQuery{ Path: fmt.Sprintf("store/%s/key", banktypes.StoreKey), Height: tc.reqHeight, - Data: banktypes.CreateAccountBalancesPrefix(val.Address.Bytes()), + Data: banktypes.CreateAccountBalancesPrefix(val.Address), Prove: true, } diff --git a/client/rpc/validators.go b/client/rpc/validators.go index 1cad03c164..06c826921a 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -110,7 +110,7 @@ func validatorOutput(validator *octypes.Validator) (ValidatorOutput, error) { } return ValidatorOutput{ - Address: sdk.BytesToConsAddress(validator.Address), + Address: sdk.ConsAddress(validator.Address), PubKey: pk, ProposerPriority: validator.ProposerPriority, VotingPower: validator.VotingPower, diff --git a/crypto/keyring/info.go b/crypto/keyring/info.go index eed60ff9c6..956e64a76d 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 types.BytesToAccAddress(i.PubKey.Address()) + return i.PubKey.Address().Bytes() } // 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 types.BytesToAccAddress(i.PubKey.Address()) + return i.PubKey.Address().Bytes() } // 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 types.BytesToAccAddress(i.PubKey.Address()) + return i.PubKey.Address().Bytes() } // GetPath implements Info interface @@ -222,7 +222,7 @@ func (i multiInfo) GetPubKey() cryptotypes.PubKey { // GetAddress implements Info interface func (i multiInfo) GetAddress() types.AccAddress { - return types.BytesToAccAddress(i.PubKey.Address()) + return i.PubKey.Address().Bytes() } // GetPath implements Info interface diff --git a/crypto/keyring/keyring.go b/crypto/keyring/keyring.go index b476d17f5c..61652bd11a 100644 --- a/crypto/keyring/keyring.go +++ b/crypto/keyring/keyring.go @@ -551,7 +551,7 @@ func (ks keystore) NewAccount(name string, mnemonic string, bip39Passphrase stri // check if the a key already exists with the same address and return an error // if found - address := sdk.BytesToAccAddress(privKey.PubKey().Address()) + address := sdk.AccAddress(privKey.PubKey().Address()) if _, err := ks.KeyByAddress(address); err == nil { return nil, fmt.Errorf("account with address %s already exists in keyring, delete the key first if you want to recreate it", address) } diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 2c4c104a83..e7e8a98114 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -79,8 +79,7 @@ func TestKeyManagementKeyRing(t *testing.T) { require.NotNil(t, err) _, err = kb.KeyByAddress(accAddr(i2)) require.NoError(t, err) - addr := sdk.AccAddress("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") - err = sdk.ValidateAccAddress(addr.String()) + addr, err := sdk.AccAddressFromBech32("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") require.NoError(t, err) _, err = kb.KeyByAddress(addr) require.NotNil(t, err) @@ -433,8 +432,7 @@ func TestInMemoryKeyManagement(t *testing.T) { require.NotNil(t, err) _, err = cstore.KeyByAddress(accAddr(i2)) require.NoError(t, err) - addr := sdk.AccAddress("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") - err = sdk.ValidateAccAddress(addr.String()) + addr, err := sdk.AccAddressFromBech32("link1yxfu3fldlgux939t0gwaqs82l4x77v2kasa7jf") 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 391ffc1d98..678a5c8ca6 100644 --- a/crypto/keyring/output.go +++ b/crypto/keyring/output.go @@ -41,14 +41,14 @@ func NewKeyOutput(name string, keyType KeyType, a sdk.Address, pk cryptotypes.Pu // MkConsKeyOutput create a KeyOutput in with "cons" Bech32 prefixes. func MkConsKeyOutput(keyInfo Info) (KeyOutput, error) { pk := keyInfo.GetPubKey() - addr := sdk.BytesToConsAddress(pk.Address()) + addr := sdk.ConsAddress(pk.Address()) return NewKeyOutput(keyInfo.GetName(), keyInfo.GetType(), addr, pk) } // MkValKeyOutput create a KeyOutput in with "val" Bech32 prefixes. func MkValKeyOutput(keyInfo Info) (KeyOutput, error) { pk := keyInfo.GetPubKey() - addr := sdk.BytesToValAddress(pk.Address()) + addr := sdk.ValAddress(pk.Address()) return NewKeyOutput(keyInfo.GetName(), keyInfo.GetType(), addr, pk) } @@ -57,7 +57,7 @@ func MkValKeyOutput(keyInfo Info) (KeyOutput, error) { // public keys will be added. func MkAccKeyOutput(keyInfo Info) (KeyOutput, error) { pk := keyInfo.GetPubKey() - addr := sdk.BytesToAccAddress(pk.Address()) + addr := sdk.AccAddress(pk.Address()) return NewKeyOutput(keyInfo.GetName(), keyInfo.GetType(), addr, pk) } diff --git a/crypto/keyring/output_test.go b/crypto/keyring/output_test.go index e106870d62..72ebf0fcf4 100644 --- a/crypto/keyring/output_test.go +++ b/crypto/keyring/output_test.go @@ -19,7 +19,7 @@ func TestBech32KeysOutput(t *testing.T) { info, err := NewMultiInfo("multisig", multisigPk) require.NoError(t, err) - accAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) + accAddr := sdk.AccAddress(info.GetPubKey().Address()) expectedOutput, err := NewKeyOutput(info.GetName(), info.GetType(), accAddr, multisigPk) require.NoError(t, err) diff --git a/crypto/keys/multisig/multisig_test.go b/crypto/keys/multisig/multisig_test.go index 1877750eac..4f276e5961 100644 --- a/crypto/keys/multisig/multisig_test.go +++ b/crypto/keys/multisig/multisig_test.go @@ -453,6 +453,6 @@ func TestProtoMarshalJSON(t *testing.T) { require.NoError(err) ko, err := keyring.MkAccKeyOutput(info) require.NoError(err) - require.Equal(ko.Address, sdk.BytesToAccAddress(pk2.Address()).String()) + require.Equal(ko.Address, sdk.AccAddress(pk2.Address()).String()) require.Equal(ko.PubKey, string(bz)) } diff --git a/crypto/ledger/ledger_mock.go b/crypto/ledger/ledger_mock.go index 0c25b622ad..953c12d365 100644 --- a/crypto/ledger/ledger_mock.go +++ b/crypto/ledger/ledger_mock.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/go-bip39" secp256k1 "github.com/tendermint/btcd/btcec" - + "github.com/line/ostracon/crypto" "github.com/line/lbm-sdk/crypto/hd" @@ -83,7 +83,7 @@ func (mock LedgerSECP256K1Mock) GetAddressPubKeySECP256K1(derivationPath []uint3 // Generate the bech32 addr using existing occrypto/etc. pub := &csecp256k1.PubKey{Key: compressedPublicKey} - addr := sdk.BytesToAccAddress(pub.Address()).String() + addr := sdk.AccAddress(pub.Address()).String() return pk, addr, err } diff --git a/crypto/ledger/ledger_test.go b/crypto/ledger/ledger_test.go index 11384d7548..afd79c5ee2 100644 --- a/crypto/ledger/ledger_test.go +++ b/crypto/ledger/ledger_test.go @@ -35,9 +35,9 @@ func checkDefaultPubKey(t *testing.T, priv types.LedgerPrivKey) { fmt.Sprintf("%x", cdc.Amino.MustMarshalBinaryBare(priv.PubKey())), "Is your device using test mnemonic: %s ?", testdata.TestMnemonic) require.Equal(t, expectedPkStr, priv.PubKey().String()) - addr := sdk.BytesToAccAddress(priv.PubKey().Address()) + addr := sdk.AccAddress(priv.PubKey().Address()).String() require.Equal(t, "link1tdl7n2acgmec0y5nng0q2fahl9khyct3cgsktn", - addr.String(), "Is your device using test mnemonic: %s ?", testdata.TestMnemonic) + addr, "Is your device using test mnemonic: %s ?", testdata.TestMnemonic) } func TestPublicKeyUnsafeHDPath(t *testing.T) { @@ -102,7 +102,7 @@ func TestPublicKeySafe(t *testing.T) { require.Nil(t, ShowAddress(path, priv.PubKey(), sdk.GetConfig().GetBech32AccountAddrPrefix())) checkDefaultPubKey(t, priv) - addr2 := sdk.BytesToAccAddress(priv.PubKey().Address()).String() + addr2 := sdk.AccAddress(priv.PubKey().Address()).String() require.Equal(t, addr, addr2) } @@ -147,7 +147,7 @@ func TestPublicKeyHDPath(t *testing.T) { require.NotNil(t, addr) require.NotNil(t, priv) - addr2 := sdk.BytesToAccAddress(priv.PubKey().Address()).String() + addr2 := sdk.AccAddress(priv.PubKey().Address()).String() require.Equal(t, addr2, addr) require.Equal(t, expectedAddrs[i], addr, diff --git a/go.mod b/go.mod index 110644c7df..69f8e9a9b9 100644 --- a/go.mod +++ b/go.mod @@ -26,6 +26,7 @@ require ( github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 + github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d github.com/hdevalence/ed25519consensus v0.0.0-20220222234857-c00d1f31bab3 github.com/improbable-eng/grpc-web v0.15.0 github.com/jhump/protoreflect v1.10.3 diff --git a/server/config/config.go b/server/config/config.go index 110a7f7973..b8bab29b9f 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -224,7 +224,6 @@ func DefaultConfig() *Config { InterBlockCache: true, InterBlockCacheSize: cache.DefaultCommitKVStoreCacheSize, IAVLCacheSize: iavl.DefaultIAVLCacheSize, - Bech32CacheSize: sdk.DefaultBech32CacheSize, Pruning: storetypes.PruningOptionDefault, PruningKeepRecent: "0", PruningKeepEvery: "0", diff --git a/server/init.go b/server/init.go index 301fbf6015..a13b65b037 100644 --- a/server/init.go +++ b/server/init.go @@ -19,9 +19,10 @@ func GenerateCoinKey(algo keyring.SignatureAlgo) (sdk.AccAddress, string, error) algo, ) if err != nil { - return sdk.AccAddress(""), "", err + return sdk.AccAddress{}, "", err } - return sdk.BytesToAccAddress(info.GetPubKey().Address()), secret, nil + + return sdk.AccAddress(info.GetPubKey().Address()), secret, nil } // Deprecated: GenerateSaveCoinKey generates a new key mnemonic with its addrress. @@ -43,20 +44,20 @@ func GenerateSaveCoinKey( // ensure no overwrite if !overwrite && exists { - return sdk.AccAddress(""), "", fmt.Errorf("key already exists, overwrite is disabled") + return sdk.AccAddress{}, "", fmt.Errorf("key already exists, overwrite is disabled") } // remove the old key by name if it exists if exists { if err := keybase.Delete(keyName); err != nil { - return sdk.AccAddress(""), "", fmt.Errorf("failed to overwrite key") + return sdk.AccAddress{}, "", fmt.Errorf("failed to overwrite key") } } k, mnemonic, err := keybase.NewMnemonic(keyName, keyring.English, sdk.GetConfig().GetFullBIP44Path(), keyring.DefaultBIP39Passphrase, algo) if err != nil { - return sdk.AccAddress(""), "", err + return sdk.AccAddress{}, "", err } - return sdk.BytesToAccAddress(k.GetPubKey().Address()), mnemonic, nil + return k.GetAddress(), mnemonic, nil } diff --git a/server/rosetta/converter.go b/server/rosetta/converter.go index 25a57dfe30..56acf067c5 100644 --- a/server/rosetta/converter.go +++ b/server/rosetta/converter.go @@ -340,8 +340,7 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] default: return nil, false case banktypes.EventTypeCoinSpent: - spender := sdk.BytesToAccAddress(event.Attributes[0].Value) - err := sdk.ValidateAccAddress(spender.String()) + spender, err := sdk.AccAddressFromBech32((string)(event.Attributes[0].Value)) if err != nil { panic(err) } @@ -355,8 +354,7 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] accountIdentifier = spender.String() case banktypes.EventTypeCoinReceived: - receiver := sdk.BytesToAccAddress(event.Attributes[0].Value) - err := sdk.ValidateAccAddress(receiver.String()) + receiver, err := sdk.AccAddressFromBech32((string)(event.Attributes[0].Value)) if err != nil { panic(err) } @@ -710,7 +708,7 @@ func (c converter) SigningComponents(tx authsigning.Tx, metadata *ConstructionMe if err != nil { return nil, nil, err } - if !bytes.Equal(sdk.BytesToAccAddress(pubKey.Address()).Bytes(), signer.Bytes()) { + if !bytes.Equal(pubKey.Address().Bytes(), signer.Bytes()) { return nil, nil, crgerrs.WrapError( crgerrs.ErrBadArgument, fmt.Sprintf("public key at index %d does not match the expected transaction signer: %X <-> %X", i, rosPubKeys[i].Bytes, signer.Bytes()), diff --git a/server/rosetta/converter_test.go b/server/rosetta/converter_test.go index e5feac012f..5c1f1d846b 100644 --- a/server/rosetta/converter_test.go +++ b/server/rosetta/converter_test.go @@ -3,10 +3,11 @@ package rosetta_test import ( "encoding/hex" "encoding/json" + "testing" + "github.com/line/lbm-sdk/testutil/testdata" "github.com/line/lbm-sdk/types/tx/signing" authtx "github.com/line/lbm-sdk/x/auth/tx" - "testing" rosettatypes "github.com/coinbase/rosetta-sdk-go/types" "github.com/stretchr/testify/suite" @@ -104,18 +105,18 @@ func (s *ConverterTestSuite) SetupTest() { } func (s *ConverterTestSuite) TestFromRosettaOpsToTxSuccess() { - addr1 := sdk.BytesToAccAddress([]byte("address1")) - addr2 := sdk.BytesToAccAddress([]byte("address2")) + addr1 := sdk.AccAddress("address1").String() + addr2 := sdk.AccAddress("address2").String() msg1 := &bank.MsgSend{ - FromAddress: addr1.String(), - ToAddress: addr2.String(), + FromAddress: addr1, + ToAddress: addr2, Amount: sdk.NewCoins(sdk.NewInt64Coin("test", 10)), } msg2 := &bank.MsgSend{ - FromAddress: addr2.String(), - ToAddress: addr1.String(), + FromAddress: addr2, + ToAddress: addr1, Amount: sdk.NewCoins(sdk.NewInt64Coin("utxo", 10)), } diff --git a/simapp/export.go b/simapp/export.go index 2a87e49250..72573c4ffd 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.ValidateValAddress(addr) + _, err := sdk.ValAddressFromBech32(addr) if err != nil { log.Fatal(err) } @@ -79,9 +79,15 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] // withdraw all delegator rewards dels := app.StakingKeeper.GetAllDelegations(ctx) for _, delegation := range dels { - valAddr := sdk.ValAddress(delegation.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + if err != nil { + panic(err) + } - delAddr := sdk.AccAddress(delegation.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) } @@ -109,8 +115,14 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] // reinitialize all delegations for _, del := range dels { - valAddr := sdk.ValAddress(del.ValidatorAddress) - delAddr := sdk.AccAddress(del.DelegatorAddress) + valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) + if err != nil { + panic(err) + } + delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + if err != nil { + panic(err) + } 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 b521502724..1314416370 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.BytesToAccAddress(pubkey.Address()) + addr := sdk.AccAddress(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.BytesToAccAddress(crypto.AddressHash([]byte("testmod"))), nil, 0, 0), + BaseAccount: authtypes.NewBaseAccount(sdk.AccAddress(crypto.AddressHash([]byte("testmod"))), nil, 0, 0), ModuleName: "testmod", }, false, diff --git a/simapp/simd/cmd/genaccounts.go b/simapp/simd/cmd/genaccounts.go index 4d4ac04c7f..2eab3fd2e9 100644 --- a/simapp/simd/cmd/genaccounts.go +++ b/simapp/simd/cmd/genaccounts.go @@ -41,11 +41,11 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa clientCtx := client.GetClientContextFromCmd(cmd) serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config + config.SetRoot(clientCtx.HomeDir) var kb keyring.Keyring - addr := sdk.AccAddress(args[0]) - err := sdk.ValidateAccAddress(args[0]) + addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { inBuf := bufio.NewReader(cmd.InOrStdin()) keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 0d147ed398..308e6d97bf 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -244,11 +244,6 @@ func (a appCreator) newApp(logger log.Logger, db tmdb.DB, traceStore io.Writer, cast.ToInt(appOpts.Get(server.FlagInterBlockCacheSize)), ibCacheMetricsProvider) } - bech32CacheSize := cast.ToInt(appOpts.Get(server.FlagBech32CacheSize)) - if bech32CacheSize > 0 { - sdk.SetBech32Cache(int64(bech32CacheSize)) - } - skipUpgradeHeights := make(map[int64]bool) for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { skipUpgradeHeights[int64(h)] = true diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 805bd8eea9..bc15745a36 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -210,7 +210,7 @@ func InitTestnet( valTokens := sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction) createValMsg, err := stakingtypes.NewMsgCreateValidator( - addr.ToValAddress(), + sdk.ValAddress(addr), valPubKeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 696b235359..5c86e243aa 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -104,9 +104,8 @@ func SetupWithGenesisValSet(t *testing.T, valSet *octypes.ValidatorSet, genAccs require.NoError(t, err) pkAny, err := codectypes.NewAnyWithValue(pk) require.NoError(t, err) - valAddr := sdk.BytesToValAddress(val.Address) validator := stakingtypes.Validator{ - OperatorAddress: valAddr.String(), + OperatorAddress: sdk.ValAddress(val.Address).String(), ConsensusPubkey: pkAny, Jailed: false, Status: stakingtypes.Bonded, @@ -119,7 +118,7 @@ func SetupWithGenesisValSet(t *testing.T, valSet *octypes.ValidatorSet, genAccs MinSelfDelegation: sdk.ZeroInt(), } validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), valAddr, sdk.OneDec())) + delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) } // set validators and delegations @@ -207,7 +206,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.BytesToAccAddress(pk.Address()) + testAddrs[i] = sdk.AccAddress(pk.Address()) } return testAddrs @@ -240,8 +239,8 @@ func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) // fill all the addresses with some coins, set the loose pool tokens simultaneously - for _, pubKey := range pubKeys { - initAccountWithCoins(app, ctx, sdk.BytesToAccAddress(pubKey.Address()), initCoins) + for _, pk := range pubKeys { + initAccountWithCoins(app, ctx, sdk.AccAddress(pk.Address()), initCoins) } } @@ -256,7 +255,7 @@ func SortAddresses(addrs []sdk.AccAddress) { SortByteArrays(byteAddrs) for i, byteAddr := range byteAddrs { - addrs[i] = sdk.AccAddress(string(byteAddr)) + addrs[i] = sdk.AccAddress(byteAddr) } } @@ -332,7 +331,7 @@ func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress { valAddrs := make([]sdk.ValAddress, len(addrs)) for i, addr := range addrs { - valAddrs[i] = addr.ToValAddress() + valAddrs[i] = sdk.ValAddress(addr) } return valAddrs @@ -341,19 +340,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 "", err + return nil, err } bechexpected := res.String() if bech != bechexpected { - return "", fmt.Errorf("bech encoding doesn't match reference") + return nil, fmt.Errorf("bech encoding doesn't match reference") } - err = sdk.ValidateAccAddress(bech) + bechres, err := sdk.AccAddressFromBech32(bech) if err != nil { - return "", err + return nil, err } - if !sdk.AccAddress(bech).Equals(res) { - return "", err + if !bytes.Equal(bechres, res) { + return nil, err } return res, nil diff --git a/testutil/key.go b/testutil/key.go index bd3d2ea915..c2128e0982 100644 --- a/testutil/key.go +++ b/testutil/key.go @@ -18,7 +18,7 @@ func GenerateCoinKey(algo keyring.SignatureAlgo) (sdk.AccAddress, string, error) algo, ) if err != nil { - return sdk.AccAddress(""), "", err + return sdk.AccAddress{}, "", err } return sdk.AccAddress(info.GetPubKey().Address()), secret, nil @@ -42,12 +42,12 @@ func GenerateSaveCoinKey( // ensure no overwrite if !overwrite && exists { - return sdk.AccAddress(""), "", fmt.Errorf("key already exists, overwrite is disabled") + return sdk.AccAddress{}, "", fmt.Errorf("key already exists, overwrite is disabled") } if exists { if err := keybase.Delete(keyName); err != nil { - return sdk.AccAddress(""), "", fmt.Errorf("failed to overwrite key") + return sdk.AccAddress{}, "", fmt.Errorf("failed to overwrite key") } } @@ -75,7 +75,7 @@ func GenerateSaveCoinKey( ) } if err != nil { - return sdk.AccAddress(""), "", err + return sdk.AccAddress{}, "", err } return info.GetAddress(), secret, nil diff --git a/testutil/key_test.go b/testutil/key_test.go index 709b3f7793..07655cb6ac 100644 --- a/testutil/key_test.go +++ b/testutil/key_test.go @@ -18,7 +18,7 @@ func TestGenerateCoinKey(t *testing.T) { // Test creation info, err := keyring.NewInMemory().NewAccount("xxx", mnemonic, "", hd.NewFundraiserParams(0, types.GetConfig().GetCoinType(), 0).String(), hd.Secp256k1) require.NoError(t, err) - require.Equal(t, types.BytesToAccAddress(addr.Bytes()), info.GetAddress()) + require.Equal(t, addr, info.GetAddress()) } func TestGenerateSaveCoinKey(t *testing.T) { diff --git a/testutil/network/network.go b/testutil/network/network.go index 7d7ecde739..84a3a4c5ff 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -314,7 +314,7 @@ func New(t *testing.T, cfg Config) *Network { require.NoError(t, err) createValMsg, err := stakingtypes.NewMsgCreateValidator( - addr.ToValAddress(), + sdk.ValAddress(addr), valPubKeys[i], sdk.NewCoin(cfg.BondDenom, cfg.BondedTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), @@ -373,7 +373,7 @@ func New(t *testing.T, cfg Config) *Network { P2PAddress: tmCfg.P2P.ListenAddress, APIAddress: apiAddr, Address: addr, - ValAddress: addr.ToValAddress(), + ValAddress: sdk.ValAddress(addr), } } diff --git a/testutil/testdata/tx.go b/testutil/testdata/tx.go index f6a642f16a..d4171db1b1 100644 --- a/testutil/testdata/tx.go +++ b/testutil/testdata/tx.go @@ -15,7 +15,7 @@ import ( func KeyTestPubAddr() (cryptotypes.PrivKey, cryptotypes.PubKey, sdk.AccAddress) { key := secp256k1.GenPrivKey() pub := key.PubKey() - addr := sdk.BytesToAccAddress(pub.Address()) + addr := sdk.AccAddress(pub.Address()) return key, pub, addr } @@ -24,7 +24,7 @@ func KeyTestPubAddrSecp256R1(require *require.Assertions) (cryptotypes.PrivKey, key, err := secp256r1.GenPrivKey() require.NoError(err) pub := key.PubKey() - addr := sdk.BytesToAccAddress(pub.Address()) + addr := sdk.AccAddress(pub.Address()) return key, pub, addr } @@ -65,12 +65,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 { - err := sdk.ValidateAccAddress(in) + addr, err := sdk.AccAddressFromBech32(in) if err != nil { panic(err) } - addrs[i] = sdk.AccAddress(in) + addrs[i] = addr } return addrs diff --git a/types/address.go b/types/address.go index 6a2802ea84..42035a6cf0 100644 --- a/types/address.go +++ b/types/address.go @@ -1,17 +1,19 @@ package types import ( + "bytes" "encoding/hex" "encoding/json" "errors" "fmt" "strings" + "sync" - "github.com/dgraph-io/ristretto" + "github.com/hashicorp/golang-lru/simplelru" yaml "gopkg.in/yaml.v2" - "github.com/line/lbm-sdk/codec/legacy" cryptotypes "github.com/line/lbm-sdk/crypto/types" + "github.com/line/lbm-sdk/internal/conv" "github.com/line/lbm-sdk/types/address" "github.com/line/lbm-sdk/types/bech32" sdkerrors "github.com/line/lbm-sdk/types/errors" @@ -30,7 +32,6 @@ const ( // config.SetCoinType(yourCoinType) // config.Seal() - BytesAddrLen = 20 // Bech32MainPrefix defines the main SDK Bech32 prefix of an account's address Bech32MainPrefix = "link" @@ -72,7 +73,32 @@ const ( Bech32PrefixConsPub = Bech32MainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic ) -const DefaultBech32CacheSize = 1 << 30 // maximum size of cache (1GB) +// cache variables +var ( + // AccAddress.String() is expensive and if unoptimized dominantly showed up in profiles, + // yet has no mechanisms to trivially cache the result given that AccAddress is a []byte type. + accAddrMu sync.Mutex + accAddrCache *simplelru.LRU + consAddrMu sync.Mutex + consAddrCache *simplelru.LRU + valAddrMu sync.Mutex + valAddrCache *simplelru.LRU +) + +func init() { + var err error + // in total the cache size is 61k entries. Key is 32 bytes and value is around 50-70 bytes. + // That will make around 92 * 61k * 2 (LRU) bytes ~ 11 MB + if accAddrCache, err = simplelru.NewLRU(60000, nil); err != nil { + panic(err) + } + if consAddrCache, err = simplelru.NewLRU(500, nil); err != nil { + panic(err) + } + if valAddrCache, err = simplelru.NewLRU(500, nil); err != nil { + panic(err) + } +} // Address is a common interface for different types of addresses used by the SDK type Address interface { @@ -86,87 +112,26 @@ 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 // ---------------------------------------------------------------------------- -// TODO We should add a layer to choose whether to access the cache or to run actual conversion -// bech32 encoding and decoding takes a lot of time, so memoize it -var bech32Cache Bech32Cache - -type Bech32Cache struct { - bech32ToAddrCache *ristretto.Cache - addrToBech32Cache *ristretto.Cache -} - -func SetBech32Cache(size int64) { - var err error - config := &ristretto.Config{ - NumCounters: 1e7, // number of keys to track frequency of (10M). - MaxCost: size, - BufferItems: 64, // number of keys per Get buffer. - } - bech32Cache.bech32ToAddrCache, err = ristretto.NewCache(config) - if err != nil { - panic(err) - } - bech32Cache.addrToBech32Cache, err = ristretto.NewCache(config) - if err != nil { - panic(err) - } -} - -// 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) - if ok { - return rawAddr.([]byte), ok - } - } - return nil, false -} - -func (cache *Bech32Cache) GetBech32(rawAddr []byte) (string, bool) { - if cache.addrToBech32Cache != nil { - bech32Addr, ok := cache.addrToBech32Cache.Get(string(rawAddr)) - if ok { - return bech32Addr.(string), ok - } - } - return "", false -} - -func (cache *Bech32Cache) Set(bech32Addr string, rawAddr []byte) { - if cache.bech32ToAddrCache != nil { - cache.bech32ToAddrCache.Set(bech32Addr, rawAddr, int64(len(rawAddr))) - } - if cache.addrToBech32Cache != nil { - cache.addrToBech32Cache.Set(string(rawAddr), bech32Addr, int64(len(bech32Addr))) - } -} - // AccAddress a wrapper around bytes meant to represent an account address. // When marshaled to a string or JSON, it uses Bech32. -type AccAddress string +type AccAddress []byte // AccAddressFromHex creates an AccAddress from a hex string. -func AccAddressFromHex(addressBytesHex string) (addr AccAddress, err error) { - bz, err := addressBytesFromHexString(addressBytesHex) - return BytesToAccAddress(bz), err +func AccAddressFromHex(address string) (addr AccAddress, err error) { + bz, err := addressBytesFromHexString(address) + return AccAddress(bz), err } // VerifyAddressFormat verifies that the provided bytes form a valid address @@ -189,30 +154,51 @@ func VerifyAddressFormat(bz []byte) error { return nil } +// AccAddressFromBech32 creates an AccAddress from a Bech32 string. +func AccAddressFromBech32(address string) (addr AccAddress, err error) { + if len(strings.TrimSpace(address)) == 0 { + return AccAddress{}, errors.New("empty address string is not allowed") + } + + bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix() + + bz, err := GetFromBech32(address, bech32PrefixAccAddr) + if err != nil { + return nil, err + } + + err = VerifyAddressFormat(bz) + if err != nil { + return nil, err + } + + return AccAddress(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 strings.EqualFold(aa.String(), aa2.String()) + return bytes.Equal(aa.Bytes(), aa2.Bytes()) } // Returns boolean for whether an AccAddress is empty func (aa AccAddress) Empty() bool { - return len(string(aa)) == 0 + return aa == nil || len(aa) == 0 } // Marshal returns the raw address bytes. It is needed for protobuf // compatibility. func (aa AccAddress) Marshal() ([]byte, error) { - return []byte(aa.String()), nil + return aa, nil } // Unmarshal sets the address to the given data. It is needed for protobuf // compatibility. func (aa *AccAddress) Unmarshal(data []byte) error { - *aa = AccAddress(data) + *aa = data return nil } @@ -230,11 +216,21 @@ 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 } - // TODO: address validation? - *aa = AccAddress(s) + if s == "" { + *aa = AccAddress{} + return nil + } + + aa2, err := AccAddressFromBech32(s) + if err != nil { + return err + } + + *aa = aa2 return nil } @@ -245,29 +241,39 @@ func (aa *AccAddress) UnmarshalYAML(data []byte) error { if err != nil { return err } - // TODO: address validation? - *aa = AccAddress(s) + if s == "" { + *aa = AccAddress{} + return nil + } + + aa2, err := AccAddressFromBech32(s) + if err != nil { + return err + } + + *aa = aa2 return nil } // Bytes returns the raw address bytes. func (aa AccAddress) Bytes() []byte { - return []byte(aa.String()) + return aa } // String implements the Stringer interface. func (aa AccAddress) String() string { - return string(aa) -} - -func (aa AccAddress) ToValAddress() ValAddress { - bytes, _ := AccAddressToBytes(aa.String()) - return BytesToValAddress(bytes) -} + if aa.Empty() { + return "" + } -func (aa AccAddress) ToConsAddress() ConsAddress { - bytes, _ := AccAddressToBytes(aa.String()) - return BytesToConsAddress(bytes) + var key = conv.UnsafeBytesToStr(aa) + accAddrMu.Lock() + defer accAddrMu.Unlock() + addr, ok := accAddrCache.Get(key) + if ok { + return addr.(string) + } + return cacheBech32Addr(GetConfig().GetBech32AccountAddrPrefix(), aa, accAddrCache, key) } // Format implements the fmt.Formatter interface. @@ -283,77 +289,29 @@ 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 string +type ValAddress []byte -func BytesToValAddress(addrBytes []byte) ValAddress { - bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix() - - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixValAddr, addrBytes) - if err != nil { - panic(err) - } - return ValAddress(bech32Addr) +// 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 ValAddressToBytes(bech32Addr string) ([]byte, error) { - if len(strings.TrimSpace(bech32Addr)) == 0 { - return nil, errors.New("empty address string is not allowed") +// 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") } bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix() - bz, err := GetFromBech32(bech32Addr, bech32PrefixValAddr) + bz, err := GetFromBech32(address, bech32PrefixValAddr) if err != nil { return nil, err } @@ -362,18 +320,8 @@ func ValAddressToBytes(bech32Addr string) ([]byte, error) { if err != nil { return nil, err } - return 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 + return ValAddress(bz), nil } // Returns boolean for whether two ValAddresses are Equal @@ -382,24 +330,24 @@ func (va ValAddress) Equals(va2 Address) bool { return true } - return strings.EqualFold(va.String(), va2.String()) + return bytes.Equal(va.Bytes(), va2.Bytes()) } // Returns boolean for whether an AccAddress is empty func (va ValAddress) Empty() bool { - return va == "" + return va == nil || len(va) == 0 } // Marshal returns the raw address bytes. It is needed for protobuf // compatibility. func (va ValAddress) Marshal() ([]byte, error) { - return []byte(va), nil + return va, nil } // Unmarshal sets the address to the given data. It is needed for protobuf // compatibility. func (va *ValAddress) Unmarshal(data []byte) error { - *va = ValAddress(data) + *va = data return nil } @@ -416,33 +364,66 @@ 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 } - *va = ValAddress(s) + if s == "" { + *va = ValAddress{} + return nil + } + + va2, err := ValAddressFromBech32(s) + if err != nil { + return err + } + + *va = va2 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 } - *va = ValAddress(s) + if s == "" { + *va = ValAddress{} + return nil + } + + va2, err := ValAddressFromBech32(s) + if err != nil { + return err + } + + *va = va2 return nil } // Bytes returns the raw address bytes. func (va ValAddress) Bytes() []byte { - return []byte(va.String()) + return va } // String implements the Stringer interface. func (va ValAddress) String() string { - return string(va) + if va.Empty() { + return "" + } + + var key = conv.UnsafeBytesToStr(va) + valAddrMu.Lock() + defer valAddrMu.Unlock() + addr, ok := valAddrCache.Get(key) + if ok { + return addr.(string) + } + return cacheBech32Addr(GetConfig().GetBech32ValidatorAddrPrefix(), va, valAddrCache, key) } // Format implements the fmt.Formatter interface. @@ -458,42 +439,29 @@ 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 string +type ConsAddress []byte -func BytesToConsAddress(addrBytes []byte) ConsAddress { - bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix() - - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixConsAddr, addrBytes) - if err != nil { - panic(err) - } - return ConsAddress(bech32Addr) +// 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 ConsAddressToBytes(bech32Addr string) ([]byte, error) { - if len(strings.TrimSpace(bech32Addr)) == 0 { - return nil, errors.New("empty address string is not allowed") +// 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") } bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix() - bz, err := GetFromBech32(bech32Addr, bech32PrefixConsAddr) + bz, err := GetFromBech32(address, bech32PrefixConsAddr) if err != nil { return nil, err } @@ -502,23 +470,13 @@ func ConsAddressToBytes(bech32Addr string) ([]byte, error) { if err != nil { return nil, err } - return 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 + return ConsAddress(bz), nil } // get ConsAddress from pubkey func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress { - return BytesToConsAddress(pubkey.Address()) + return ConsAddress(pubkey.Address()) } // Returns boolean for whether two ConsAddress are Equal @@ -527,24 +485,24 @@ func (ca ConsAddress) Equals(ca2 Address) bool { return true } - return strings.EqualFold(ca.String(), ca2.String()) + return bytes.Equal(ca.Bytes(), ca2.Bytes()) } // Returns boolean for whether an ConsAddress is empty func (ca ConsAddress) Empty() bool { - return ca == "" + return ca == nil || len(ca) == 0 } // Marshal returns the raw address bytes. It is needed for protobuf // compatibility. func (ca ConsAddress) Marshal() ([]byte, error) { - return []byte(ca), nil + return ca, nil } // Unmarshal sets the address to the given data. It is needed for protobuf // compatibility. func (ca *ConsAddress) Unmarshal(data []byte) error { - *ca = ConsAddress(data) + *ca = data return nil } @@ -561,33 +519,66 @@ 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 } - *ca = ConsAddress(s) + if s == "" { + *ca = ConsAddress{} + return nil + } + + ca2, err := ConsAddressFromBech32(s) + if err != nil { + return err + } + + *ca = ca2 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 } - *ca = ConsAddress(s) + if s == "" { + *ca = ConsAddress{} + return nil + } + + ca2, err := ConsAddressFromBech32(s) + if err != nil { + return err + } + + *ca = ca2 return nil } // Bytes returns the raw address bytes. func (ca ConsAddress) Bytes() []byte { - return []byte(ca) + return ca } // String implements the Stringer interface. func (ca ConsAddress) String() string { - return string(ca) + if ca.Empty() { + return "" + } + + var key = conv.UnsafeBytesToStr(ca) + consAddrMu.Lock() + defer consAddrMu.Unlock() + addr, ok := consAddrCache.Get(key) + if ok { + return addr.(string) + } + return cacheBech32Addr(GetConfig().GetBech32ConsensusAddrPrefix(), ca, consAddrCache, key) } // Bech32ifyAddressBytes returns a bech32 representation of address bytes. @@ -633,82 +624,6 @@ func (ca ConsAddress) Format(s fmt.State, verb rune) { var errBech32EmptyAddress = errors.New("decoding Bech32 address failed: must provide a non empty address") -// Bech32PubKeyType defines a string type alias for a Bech32 public key type. -type Bech32PubKeyType string - -// Bech32 conversion constants -const ( - Bech32PubKeyTypeAccPub Bech32PubKeyType = "accpub" - Bech32PubKeyTypeValPub Bech32PubKeyType = "valpub" - Bech32PubKeyTypeConsPub Bech32PubKeyType = "conspub" -) - -// Bech32ifyPubKey returns a Bech32 encoded string containing the appropriate -// prefix based on the key type provided for a given PublicKey. -// TODO: Remove Bech32ifyPubKey and all usages (cosmos/cosmos-sdk/issues/#7357) -func Bech32ifyPubKey(pkt Bech32PubKeyType, pubkey cryptotypes.PubKey) (string, error) { - var bech32Prefix string - - switch pkt { - case Bech32PubKeyTypeAccPub: - bech32Prefix = GetConfig().GetBech32AccountPubPrefix() - - case Bech32PubKeyTypeValPub: - bech32Prefix = GetConfig().GetBech32ValidatorPubPrefix() - - case Bech32PubKeyTypeConsPub: - bech32Prefix = GetConfig().GetBech32ConsensusPubPrefix() - - } - - return bech32.ConvertAndEncode(bech32Prefix, legacy.Cdc.MustMarshal(pubkey)) -} - -// MustBech32ifyPubKey calls Bech32ifyPubKey except it panics on error. -func MustBech32ifyPubKey(pkt Bech32PubKeyType, pubkey cryptotypes.PubKey) string { - res, err := Bech32ifyPubKey(pkt, pubkey) - if err != nil { - panic(err) - } - - return res -} - -// GetPubKeyFromBech32 returns a PublicKey from a bech32-encoded PublicKey with -// a given key type. -func GetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) (cryptotypes.PubKey, error) { - var bech32Prefix string - - switch pkt { - case Bech32PubKeyTypeAccPub: - bech32Prefix = GetConfig().GetBech32AccountPubPrefix() - - case Bech32PubKeyTypeValPub: - bech32Prefix = GetConfig().GetBech32ValidatorPubPrefix() - - case Bech32PubKeyTypeConsPub: - bech32Prefix = GetConfig().GetBech32ConsensusPubPrefix() - - } - - bz, err := GetFromBech32(pubkeyStr, bech32Prefix) - if err != nil { - return nil, err - } - - return legacy.PubKeyFromBytes(bz) -} - -// MustGetPubKeyFromBech32 calls GetPubKeyFromBech32 except it panics on error. -func MustGetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) cryptotypes.PubKey { - res, err := GetPubKeyFromBech32(pkt, pubkeyStr) - if err != nil { - panic(err) - } - - return res -} - // GetFromBech32 decodes a bytestring from a Bech32 encoded string. func GetFromBech32(bech32str, prefix string) ([]byte, error) { if len(bech32str) == 0 { @@ -734,3 +649,13 @@ func addressBytesFromHexString(address string) ([]byte, error) { return hex.DecodeString(address) } + +// cacheBech32Addr is not concurrency safe. Concurrent access to cache causes race condition. +func cacheBech32Addr(prefix string, addr []byte, cache *simplelru.LRU, cacheKey string) string { + bech32Addr, err := bech32.ConvertAndEncode(prefix, addr) + if err != nil { + panic(err) + } + cache.Add(cacheKey, bech32Addr) + return bech32Addr +} diff --git a/types/address_race_test.go b/types/address_race_test.go index bc66319158..f5920eb07b 100644 --- a/types/address_race_test.go +++ b/types/address_race_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - sdk "github.com/line/lbm-sdk/types" + "github.com/line/lbm-sdk/types" "github.com/stretchr/testify/require" ) @@ -24,7 +24,7 @@ func addressStringCaller(require *require.Assertions, prefix byte, max uint32, c return default: binary.BigEndian.PutUint32(bz[1:], i) - str := sdk.BytesToAccAddress(bz).String() + str := types.AccAddress(bz).String() require.True(str != "") } diff --git a/types/address_test.go b/types/address_test.go index 7fe8dedeb6..f3e4f76a1f 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -15,8 +15,8 @@ import ( "github.com/line/lbm-sdk/crypto/keys/ed25519" "github.com/line/lbm-sdk/crypto/keys/secp256k1" cryptotypes "github.com/line/lbm-sdk/crypto/types" - sdk "github.com/line/lbm-sdk/types" - legacybech32 "github.com/line/lbm-sdk/types/bech32/legacybech32" + "github.com/line/lbm-sdk/types" + "github.com/line/lbm-sdk/types/bech32/legacybech32" ) type addressTestSuite struct { @@ -35,12 +35,12 @@ var invalidStrs = []string{ "hello, world!", "0xAA", "AAA", - sdk.Bech32PrefixAccAddr + "AB0C", - sdk.Bech32PrefixAccPub + "1234", - sdk.Bech32PrefixValAddr + "5678", - sdk.Bech32PrefixValPub + "BBAB", - sdk.Bech32PrefixConsAddr + "FF04", - sdk.Bech32PrefixConsPub + "6789", + types.Bech32PrefixAccAddr + "AB0C", + types.Bech32PrefixAccPub + "1234", + types.Bech32PrefixValAddr + "5678", + types.Bech32PrefixValPub + "BBAB", + types.Bech32PrefixConsAddr + "FF04", + types.Bech32PrefixConsPub + "6789", } func (s *addressTestSuite) testMarshal(original interface{}, res interface{}, marshal func() ([]byte, error), unmarshal func([]byte) error) { @@ -52,32 +52,29 @@ func (s *addressTestSuite) testMarshal(original interface{}, res interface{}, ma func (s *addressTestSuite) TestEmptyAddresses() { s.T().Parallel() - s.Require().Equal(sdk.AccAddress("").String(), "") - s.Require().Equal(sdk.ValAddress("").String(), "") - s.Require().Equal(sdk.ConsAddress("").String(), "") + s.Require().Equal((types.AccAddress{}).String(), "") + s.Require().Equal((types.ValAddress{}).String(), "") + s.Require().Equal((types.ConsAddress{}).String(), "") - accAddr := sdk.AccAddress("") + accAddr, err := types.AccAddressFromBech32("") s.Require().True(accAddr.Empty()) - err := sdk.ValidateAccAddress(accAddr.String()) s.Require().Error(err) - valAddr := sdk.ValAddress("") + valAddr, err := types.ValAddressFromBech32("") s.Require().True(valAddr.Empty()) - err = sdk.ValidateValAddress(valAddr.String()) s.Require().Error(err) - consAddr := sdk.ConsAddress("") + consAddr, err := types.ConsAddressFromBech32("") s.Require().True(consAddr.Empty()) - err = sdk.ValidateConsAddress(consAddr.String()) s.Require().Error(err) } func (s *addressTestSuite) TestYAMLMarshalers() { addr := secp256k1.GenPrivKey().PubKey().Address() - acc := sdk.BytesToAccAddress(addr) - val := sdk.BytesToValAddress(addr) - cons := sdk.BytesToConsAddress(addr) + acc := types.AccAddress(addr) + val := types.ValAddress(addr) + cons := types.ConsAddress(addr) got, _ := yaml.Marshal(&acc) s.Require().Equal(acc.String()+"\n", string(got)) @@ -96,38 +93,35 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { for i := 0; i < 1000; i++ { rand.Read(pub.Key) - acc := sdk.BytesToAccAddress(pub.Address()) - res := sdk.AccAddress("") + acc := types.AccAddress(pub.Address()) + res := types.AccAddress{} s.testMarshal(&acc, &res, acc.MarshalJSON, (&res).UnmarshalJSON) s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - err := sdk.ValidateAccAddress(str) + res, err := types.AccAddressFromBech32(str) s.Require().Nil(err) - s.Require().Equal(acc, sdk.AccAddress(str)) + s.Require().Equal(acc, res) - bytes, err := sdk.AccAddressToBytes(acc.String()) - s.Require().NoError(err) - str = hex.EncodeToString(bytes) - res, err = sdk.AccAddressFromHex(str) + str = hex.EncodeToString(acc) + res, err = types.AccAddressFromHex(str) s.Require().Nil(err) s.Require().Equal(acc, res) } for _, str := range invalidStrs { - _, err := sdk.AccAddressFromHex(str) + _, err := types.AccAddressFromHex(str) s.Require().NotNil(err) - err = sdk.ValidateAccAddress(str) + _, err = types.AccAddressFromBech32(str) s.Require().NotNil(err) - addr := sdk.AccAddress("") - err = (&addr).UnmarshalJSON([]byte("\"" + str + "\"")) - s.Require().Nil(err) + err = (*types.AccAddress)(nil).UnmarshalJSON([]byte("\"" + str + "\"")) + s.Require().NotNil(err) } - _, err := sdk.AccAddressFromHex("") + _, err := types.AccAddressFromHex("") s.Require().Equal("decoding Bech32 address failed: must provide an address", err.Error()) } @@ -138,39 +132,37 @@ func (s *addressTestSuite) TestValAddr() { for i := 0; i < 20; i++ { rand.Read(pub.Key) - acc := sdk.BytesToValAddress(pub.Address()) - res := sdk.ValAddress("") + acc := types.ValAddress(pub.Address()) + res := types.ValAddress{} s.testMarshal(&acc, &res, acc.MarshalJSON, (&res).UnmarshalJSON) s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res2, err := sdk.ValAddressToBytes(str) + res, err := types.ValAddressFromBech32(str) s.Require().Nil(err) - s.Require().Equal(acc, sdk.BytesToValAddress(res2)) + s.Require().Equal(acc, res) - bytes, _ := sdk.ValAddressToBytes(acc.String()) - str = hex.EncodeToString(bytes) - res, err = sdk.ValAddressFromHex(str) + str = hex.EncodeToString(acc) + res, err = types.ValAddressFromHex(str) s.Require().Nil(err) s.Require().Equal(acc, res) } for _, str := range invalidStrs { - _, err := sdk.ValAddressFromHex(str) + _, err := types.ValAddressFromHex(str) s.Require().NotNil(err) - err = sdk.ValidateValAddress(str) + _, err = types.ValAddressFromBech32(str) s.Require().NotNil(err) - addr := sdk.ValAddress("") - err = (&addr).UnmarshalJSON([]byte("\"" + str + "\"")) - s.Require().Nil(err) + err = (*types.ValAddress)(nil).UnmarshalJSON([]byte("\"" + str + "\"")) + s.Require().NotNil(err) } // test empty string - _, err := sdk.ValAddressFromHex("") + _, err := types.ValAddressFromHex("") s.Require().Equal("decoding Bech32 address failed: must provide an address", err.Error()) } @@ -181,38 +173,36 @@ func (s *addressTestSuite) TestConsAddress() { for i := 0; i < 20; i++ { rand.Read(pub.Key[:]) - acc := sdk.BytesToConsAddress(pub.Address()) - res := sdk.ConsAddress("") + acc := types.ConsAddress(pub.Address()) + res := types.ConsAddress{} s.testMarshal(&acc, &res, acc.MarshalJSON, (&res).UnmarshalJSON) s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res2, err := sdk.ConsAddressToBytes(str) + res, err := types.ConsAddressFromBech32(str) s.Require().Nil(err) - s.Require().Equal(acc, sdk.BytesToConsAddress(res2)) + s.Require().Equal(acc, res) - bytes, _ := sdk.ConsAddressToBytes(acc.String()) - str = hex.EncodeToString(bytes) - res, err = sdk.ConsAddressFromHex(str) + str = hex.EncodeToString(acc) + res, err = types.ConsAddressFromHex(str) s.Require().Nil(err) s.Require().Equal(acc, res) } for _, str := range invalidStrs { - _, err := sdk.ConsAddressFromHex(str) + _, err := types.ConsAddressFromHex(str) s.Require().NotNil(err) - err = sdk.ValidateConsAddress(str) + _, err = types.ConsAddressFromBech32(str) s.Require().NotNil(err) - consAddr := sdk.ConsAddress("") - err = (&consAddr).UnmarshalJSON([]byte("\"" + str + "\"")) - s.Require().Nil(err) + err = (*types.ConsAddress)(nil).UnmarshalJSON([]byte("\"" + str + "\"")) + s.Require().NotNil(err) } // test empty string - _, err := sdk.ConsAddressFromHex("") + _, err := types.ConsAddressFromHex("") s.Require().Equal("decoding Bech32 address failed: must provide an address", err.Error()) } @@ -236,48 +226,48 @@ func (s *addressTestSuite) TestConfiguredPrefix() { prefix := RandString(length) // Assuming that GetConfig is not sealed. - config := sdk.GetConfig() + config := types.GetConfig() config.SetBech32PrefixForAccount( - prefix+sdk.PrefixAccount, - prefix+sdk.PrefixPublic) + prefix+types.PrefixAccount, + prefix+types.PrefixPublic) - acc := sdk.BytesToAccAddress(pub.Address()) + acc := types.AccAddress(pub.Address()) s.Require().True(strings.HasPrefix( acc.String(), - prefix+sdk.PrefixAccount), acc.String()) + prefix+types.PrefixAccount), acc.String()) bech32Pub := legacybech32.MustMarshalPubKey(legacybech32.AccPK, pub) s.Require().True(strings.HasPrefix( bech32Pub, - prefix+sdk.PrefixPublic)) + prefix+types.PrefixPublic)) config.SetBech32PrefixForValidator( - prefix+sdk.PrefixValidator+sdk.PrefixAddress, - prefix+sdk.PrefixValidator+sdk.PrefixPublic) + prefix+types.PrefixValidator+types.PrefixAddress, + prefix+types.PrefixValidator+types.PrefixPublic) - val := sdk.BytesToValAddress(pub.Address()) + val := types.ValAddress(pub.Address()) s.Require().True(strings.HasPrefix( val.String(), - prefix+sdk.PrefixValidator+sdk.PrefixAddress)) + prefix+types.PrefixValidator+types.PrefixAddress)) bech32ValPub := legacybech32.MustMarshalPubKey(legacybech32.ValPK, pub) s.Require().True(strings.HasPrefix( bech32ValPub, - prefix+sdk.PrefixValidator+sdk.PrefixPublic)) + prefix+types.PrefixValidator+types.PrefixPublic)) config.SetBech32PrefixForConsensusNode( - prefix+sdk.PrefixConsensus+sdk.PrefixAddress, - prefix+sdk.PrefixConsensus+sdk.PrefixPublic) + prefix+types.PrefixConsensus+types.PrefixAddress, + prefix+types.PrefixConsensus+types.PrefixPublic) - cons := sdk.BytesToConsAddress(pub.Address()) + cons := types.ConsAddress(pub.Address()) s.Require().True(strings.HasPrefix( cons.String(), - prefix+sdk.PrefixConsensus+sdk.PrefixAddress)) + prefix+types.PrefixConsensus+types.PrefixAddress)) bech32ConsPub := legacybech32.MustMarshalPubKey(legacybech32.ConsPK, pub) s.Require().True(strings.HasPrefix( bech32ConsPub, - prefix+sdk.PrefixConsensus+sdk.PrefixPublic)) + prefix+types.PrefixConsensus+types.PrefixPublic)) } } } @@ -287,22 +277,22 @@ func (s *addressTestSuite) TestAddressInterface() { pub := &ed25519.PubKey{Key: pubBz} rand.Read(pub.Key) - addrs := []sdk.Address{ - sdk.BytesToConsAddress(pub.Address()), - sdk.BytesToValAddress(pub.Address()), - sdk.BytesToAccAddress(pub.Address()), + addrs := []types.Address{ + types.ConsAddress(pub.Address()), + types.ValAddress(pub.Address()), + types.AccAddress(pub.Address()), } for _, addr := range addrs { switch addr := addr.(type) { - case sdk.AccAddress: - err := sdk.ValidateAccAddress(addr.String()) + case types.AccAddress: + _, err := types.AccAddressFromBech32(addr.String()) s.Require().Nil(err) - case sdk.ValAddress: - err := sdk.ValidateValAddress(addr.String()) + case types.ValAddress: + _, err := types.ValAddressFromBech32(addr.String()) s.Require().Nil(err) - case sdk.ConsAddress: - err := sdk.ValidateConsAddress(addr.String()) + case types.ConsAddress: + _, err := types.ConsAddressFromBech32(addr.String()) s.Require().Nil(err) default: s.T().Fail() @@ -318,55 +308,57 @@ func (s *addressTestSuite) TestVerifyAddressFormat() { addr32 := make([]byte, 32) addr256 := make([]byte, 256) - err := sdk.VerifyAddressFormat(addr0) + err := types.VerifyAddressFormat(addr0) s.Require().EqualError(err, "addresses cannot be empty: unknown address") - err = sdk.VerifyAddressFormat(addr5) + err = types.VerifyAddressFormat(addr5) s.Require().NoError(err) - err = sdk.VerifyAddressFormat(addr20) + err = types.VerifyAddressFormat(addr20) s.Require().NoError(err) - err = sdk.VerifyAddressFormat(addr32) + err = types.VerifyAddressFormat(addr32) s.Require().NoError(err) - err = sdk.VerifyAddressFormat(addr256) + err = types.VerifyAddressFormat(addr256) s.Require().EqualError(err, "address max length is 255, got 256: unknown address") } func (s *addressTestSuite) TestCustomAddressVerifier() { // Create a 10 byte address addr := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - accBech := sdk.BytesToAccAddress(addr).String() - valBech := sdk.BytesToValAddress(addr).String() - consBech := sdk.BytesToConsAddress(addr).String() - // Verifiy that the default logic rejects this 10 byte address - err := sdk.VerifyAddressFormat(addr) + accBech := types.AccAddress(addr).String() + valBech := types.ValAddress(addr).String() + consBech := types.ConsAddress(addr).String() + // Verify that the default logic doesn't reject this 10 byte address + // The default verifier is nil, we're only checking address length is + // between 1-255 bytes. + err := types.VerifyAddressFormat(addr) s.Require().Nil(err) - err = sdk.ValidateAccAddress(accBech) + _, err = types.AccAddressFromBech32(accBech) s.Require().Nil(err) - err = sdk.ValidateValAddress(valBech) + _, err = types.ValAddressFromBech32(valBech) s.Require().Nil(err) - err = sdk.ValidateConsAddress(consBech) + _, err = types.ConsAddressFromBech32(consBech) s.Require().Nil(err) // Set a custom address verifier only accepts 20 byte addresses - sdk.GetConfig().SetAddressVerifier(func(bz []byte) error { + types.GetConfig().SetAddressVerifier(func(bz []byte) error { n := len(bz) - if n == sdk.BytesAddrLen { + if n == 20 { return nil } return fmt.Errorf("incorrect address length %d", n) }) // Verifiy that the custom logic rejects this 10 byte address - err = sdk.VerifyAddressFormat(addr) + err = types.VerifyAddressFormat(addr) s.Require().NotNil(err) - err = sdk.ValidateAccAddress(accBech) + _, err = types.AccAddressFromBech32(accBech) s.Require().NotNil(err) - err = sdk.ValidateValAddress(valBech) + _, err = types.ValAddressFromBech32(valBech) s.Require().NotNil(err) - err = sdk.ValidateConsAddress(consBech) + _, err = types.ConsAddressFromBech32(consBech) s.Require().NotNil(err) // Reinitialize the global config to default address verifier (nil) - sdk.GetConfig().SetAddressVerifier(nil) + types.GetConfig().SetAddressVerifier(nil) } func (s *addressTestSuite) TestBech32ifyAddressBytes() { @@ -392,7 +384,7 @@ func (s *addressTestSuite) TestBech32ifyAddressBytes() { for _, tt := range tests { tt := tt s.T().Run(tt.name, func(t *testing.T) { - got, err := sdk.Bech32ifyAddressBytes(tt.args.prefix, tt.args.bs) + got, err := types.Bech32ifyAddressBytes(tt.args.prefix, tt.args.bs) if (err != nil) != tt.wantErr { t.Errorf("Bech32ifyBytes() error = %v, wantErr %v", err, tt.wantErr) return @@ -426,24 +418,24 @@ func (s *addressTestSuite) TestMustBech32ifyAddressBytes() { tt := tt s.T().Run(tt.name, func(t *testing.T) { if tt.wantPanic { - require.Panics(t, func() { sdk.MustBech32ifyAddressBytes(tt.args.prefix, tt.args.bs) }) + require.Panics(t, func() { types.MustBech32ifyAddressBytes(tt.args.prefix, tt.args.bs) }) return } - require.Equal(t, tt.want, sdk.MustBech32ifyAddressBytes(tt.args.prefix, tt.args.bs)) + require.Equal(t, tt.want, types.MustBech32ifyAddressBytes(tt.args.prefix, tt.args.bs)) }) } } func (s *addressTestSuite) TestAddressTypesEquals() { addr1 := secp256k1.GenPrivKey().PubKey().Address() - accAddr1 := sdk.BytesToAccAddress(addr1) - consAddr1 := sdk.BytesToConsAddress(addr1) - valAddr1 := sdk.BytesToValAddress(addr1) + accAddr1 := types.AccAddress(addr1) + consAddr1 := types.ConsAddress(addr1) + valAddr1 := types.ValAddress(addr1) addr2 := secp256k1.GenPrivKey().PubKey().Address() - accAddr2 := sdk.BytesToAccAddress(addr2) - consAddr2 := sdk.BytesToConsAddress(addr2) - valAddr2 := sdk.BytesToValAddress(addr2) + accAddr2 := types.AccAddress(addr2) + consAddr2 := types.ConsAddress(addr2) + valAddr2 := types.ValAddress(addr2) // equality s.Require().True(accAddr1.Equals(accAddr1)) @@ -451,9 +443,20 @@ func (s *addressTestSuite) TestAddressTypesEquals() { s.Require().True(valAddr1.Equals(valAddr1)) // emptiness - s.Require().True(sdk.AccAddress("").Equals(sdk.AccAddress(""))) - s.Require().True(sdk.ConsAddress("").Equals(sdk.ConsAddress(""))) - s.Require().True(sdk.ValAddress("").Equals(sdk.ValAddress(""))) + 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().False(accAddr1.Equals(accAddr2)) s.Require().Equal(accAddr1.Equals(accAddr2), accAddr2.Equals(accAddr1)) @@ -464,57 +467,23 @@ func (s *addressTestSuite) TestAddressTypesEquals() { } func (s *addressTestSuite) TestNilAddressTypesEmpty() { - s.Require().True(sdk.AccAddress("").Empty()) - s.Require().True(sdk.ConsAddress("").Empty()) - s.Require().True(sdk.ValAddress("").Empty()) + s.Require().True(types.AccAddress(nil).Empty()) + s.Require().True(types.ConsAddress(nil).Empty()) + s.Require().True(types.ValAddress(nil).Empty()) } func (s *addressTestSuite) TestGetConsAddress() { pk := secp256k1.GenPrivKey().PubKey() - s.Require().NotEqual(sdk.GetConsAddress(pk), pk.Address()) - consBytes, _ := sdk.ConsAddressToBytes(sdk.GetConsAddress(pk).String()) - s.Require().True(bytes.Equal(consBytes, pk.Address())) - s.Require().Panics(func() { sdk.GetConsAddress(cryptotypes.PubKey(nil)) }) + s.Require().NotEqual(types.GetConsAddress(pk), pk.Address()) + s.Require().True(bytes.Equal(types.GetConsAddress(pk).Bytes(), pk.Address().Bytes())) + s.Require().Panics(func() { types.GetConsAddress(cryptotypes.PubKey(nil)) }) } func (s *addressTestSuite) TestGetFromBech32() { - _, err := sdk.GetFromBech32("", "prefix") + _, err := types.GetFromBech32("", "prefix") s.Require().Error(err) s.Require().Equal("decoding Bech32 address failed: must provide a non empty address", err.Error()) - _, err = sdk.GetFromBech32("link1qqqsyqcyq5rqwzqf97tnae", "x") + _, err = types.GetFromBech32("link1qqqsyqcyq5rqwzqf97tnae", "x") s.Require().Error(err) s.Require().Equal("invalid Bech32 prefix; expected x, got link", err.Error()) } - -func (s *addressTestSuite) TestBech32Cache() { - pubBz := make([]byte, ed25519.PubKeySize) - pub := &ed25519.PubKey{Key: pubBz} - - s.T().Log("access bech32ToAddrCache before access addrToBech32Cache") - { - rand.Read(pub.Key) - addr := sdk.BytesToAccAddress(pub.Address()) - bech32Addr := addr.String() - sdk.SetBech32Cache(sdk.DefaultBech32CacheSize) - - rawAddr, err := sdk.AccAddressToBytes(bech32Addr) - s.Require().Nil(err) - require.Equal(s.T(), addr, sdk.BytesToAccAddress(rawAddr)) - - require.Equal(s.T(), bech32Addr, addr.String()) - } - s.T().Log("access addrToBech32Cache before access bech32ToAddrCache") - { - rand.Read(pub.Key) - addr := sdk.BytesToAccAddress(pub.Address()) - bech32Addr := addr.String() - sdk.SetBech32Cache(sdk.DefaultBech32CacheSize) - - require.Equal(s.T(), bech32Addr, addr.String()) - - rawAddr, err := sdk.AccAddressToBytes(bech32Addr) - s.Require().Nil(err) - require.Equal(s.T(), addr, sdk.BytesToAccAddress(rawAddr)) - } - sdk.InvalidateBech32Cache() -} diff --git a/types/query/filtered_pagination_test.go b/types/query/filtered_pagination_test.go index eb493ca0d7..b016ec53b4 100644 --- a/types/query/filtered_pagination_test.go +++ b/types/query/filtered_pagination_test.go @@ -12,7 +12,7 @@ import ( "github.com/line/lbm-sdk/x/bank/types" ) -var addr1 = sdk.BytesToAccAddress([]byte("addr1")) +var addr1 = sdk.AccAddress([]byte("addr1")) func (s *paginationTestSuite) TestFilteredPaginations() { app, ctx, appCodec := setupTest() @@ -29,7 +29,7 @@ func (s *paginationTestSuite) TestFilteredPaginations() { } balances = balances.Sort() - addr1 := sdk.BytesToAccAddress([]byte("addr1")) + addr1 := sdk.AccAddress([]byte("addr1")) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) s.Require().NoError(simapp.FundAccount(app, ctx, addr1, balances)) @@ -104,7 +104,7 @@ func (s *paginationTestSuite) TestReverseFilteredPaginations() { } balances = balances.Sort() - addr1 := sdk.BytesToAccAddress([]byte("addr1")) + addr1 := sdk.AccAddress([]byte("addr1")) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) s.Require().NoError(simapp.FundAccount(app, ctx, addr1, balances)) @@ -196,7 +196,7 @@ func ExampleFilteredPaginate() { pageReq := &query.PageRequest{Key: nil, Limit: 1, CountTotal: true} store := ctx.KVStore(app.GetKey(types.StoreKey)) balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1.Bytes())) + accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) var balResult sdk.Coins pageRes, err := query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { @@ -228,7 +228,7 @@ func ExampleFilteredPaginate() { func execFilterPaginate(store sdk.KVStore, pageReq *query.PageRequest, appCodec codec.Codec) (balances sdk.Coins, res *query.PageResponse, err error) { balancesStore := prefix.NewStore(store, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1.Bytes())) + accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(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 cad8384d87..45c1502038 100644 --- a/types/query/pagination_test.go +++ b/types/query/pagination_test.go @@ -74,7 +74,7 @@ func (s *paginationTestSuite) TestPagination() { } balances = balances.Sort() - addr1 := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) s.Require().NoError(simapp.FundAccount(app, ctx, addr1, balances)) @@ -183,7 +183,7 @@ func (s *paginationTestSuite) TestReversePagination() { } balances = balances.Sort() - addr1 := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr1 := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) s.Require().NoError(simapp.FundAccount(app, ctx, addr1, balances)) @@ -317,7 +317,7 @@ func ExamplePaginate() { balResult := sdk.NewCoins() authStore := ctx.KVStore(app.GetKey(types.StoreKey)) balancesStore := prefix.NewStore(authStore, types.BalancesPrefix) - accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1.Bytes())) + accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) pageRes, err := query.Paginate(accountStore, request.Pagination, func(key []byte, value []byte) error { var tempRes sdk.Coin err := app.AppCodec().Unmarshal(value, &tempRes) diff --git a/types/rest/rest.go b/types/rest/rest.go index f280bdfe0d..2a6988bcd4 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.ValidateAccAddress(br.From); err != nil || len(br.From) == 0 { + if _, err := sdk.AccAddressFromBech32(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/simulation/account.go b/types/simulation/account.go index eea8b360d1..050b36f0a3 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.BytesToAccAddress(accs[i].PubKey.Address()) + accs[i].Address = sdk.AccAddress(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 59ad970ab1..d4495196d4 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.Equal(t, acc.Address, sdk.AccAddress("")) + require.Nil(t, acc.Address) require.Nil(t, acc.PrivKey) require.Nil(t, acc.PubKey) } diff --git a/types/tx/types.go b/types/tx/types.go index be53fe1120..875eae8fd3 100644 --- a/types/tx/types.go +++ b/types/tx/types.go @@ -77,7 +77,7 @@ func (t *Tx) ValidateBasic() error { } if fee.Payer != "" { - err := sdk.ValidateAccAddress(fee.Payer) + _, err := sdk.AccAddressFromBech32(fee.Payer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid fee payer address (%s)", err) } @@ -118,7 +118,11 @@ 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] { - signers = append(signers, sdk.AccAddress(feePayer)) + payerAddr, err := sdk.AccAddressFromBech32(feePayer) + if err != nil { + panic(err) + } + signers = append(signers, payerAddr) seen[feePayer] = true } @@ -134,11 +138,10 @@ func (t *Tx) GetFee() sdk.Coins { func (t *Tx) FeePayer() sdk.AccAddress { feePayer := t.AuthInfo.Fee.Payer if feePayer != "" { - err := sdk.ValidateAccAddress(feePayer) + payerAddr, err := sdk.AccAddressFromBech32(feePayer) if err != nil { panic(err) } - payerAddr := sdk.AccAddress(feePayer) return payerAddr } // use first signer as default if no payer specified @@ -148,14 +151,13 @@ func (t *Tx) FeePayer() sdk.AccAddress { func (t *Tx) FeeGranter() sdk.AccAddress { feePayer := t.AuthInfo.Fee.Granter if feePayer != "" { - err := sdk.ValidateAccAddress(feePayer) + granterAddr, err := sdk.AccAddressFromBech32(feePayer) if err != nil { panic(err) } - granterAddr := sdk.AccAddress(feePayer) return granterAddr } - return sdk.AccAddress("") + return nil } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method diff --git a/types/tx_msg_test.go b/types/tx_msg_test.go index fa658e7a2a..eea8195969 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.BytesToAccAddress(addr) + accAddr := sdk.AccAddress(addr) msg := testdata.NewTestMsg(accAddr) s.Require().NotNil(msg) diff --git a/x/auth/ante/fee.go b/x/auth/ante/fee.go index 4c4ed253b7..6d71f06d0d 100644 --- a/x/auth/ante/fee.go +++ b/x/auth/ante/fee.go @@ -90,7 +90,7 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bo // if feegranter set deduct fee from feegranter account. // this works with only when feegrant enabled. - if feeGranter != "" { + if feeGranter != nil { if dfd.feegrantKeeper == nil { return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "fee grants are not enabled") } else if !feeGranter.Equals(feePayer) { diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index b7744ae0e3..47c68a7e44 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -77,7 +77,7 @@ func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b pk = simSecp256k1Pubkey } // Only make check if simulate=false - if !simulate && !sdk.BytesToAccAddress(pk.Address()).Equals(signers[i]) { + if !simulate && !bytes.Equal(pk.Address(), 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 ac4b776f10..5d05d87db1 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -314,7 +314,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.BytesToAccAddress(priv.PubKey().Address()) + addr := sdk.AccAddress(priv.PubKey().Address()) acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) suite.Require().NoError(acc.SetAccountNumber(uint64(i))) suite.app.AccountKeeper.SetAccount(suite.ctx, acc) diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 5efa6836a3..2480b67b1c 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -91,10 +91,11 @@ func GetAccountCmd() *cobra.Command { if err != nil { return err } - if err = sdk.ValidateAccAddress(args[0]); err != nil { + key, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { return err } - key := sdk.AccAddress(args[0]) + queryClient := types.NewQueryClient(clientCtx) res, err := queryClient.Account(cmd.Context(), &types.QueryAccountRequest{Address: key.String()}) if err != nil { diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index b2c2dec83f..7b8e751624 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.BytesToAccAddress(pubKey.Address()) + sigAddr = sdk.AccAddress(pubKey.Address()) sigSanity = "OK" ) diff --git a/x/auth/client/rest/query.go b/x/auth/client/rest/query.go index e661c54554..2dde034d7a 100644 --- a/x/auth/client/rest/query.go +++ b/x/auth/client/rest/query.go @@ -24,7 +24,10 @@ func QueryAccountRequestHandlerFn(storeName string, clientCtx client.Context) ht vars := mux.Vars(r) bech32addr := vars["address"] - addr := sdk.AccAddress(bech32addr) + addr, err := sdk.AccAddressFromBech32(bech32addr) + if rest.CheckInternalServerError(w, err) { + return + } clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { diff --git a/x/auth/client/testutil/suite.go b/x/auth/client/testutil/suite.go index 504331672e..58056cd79f 100644 --- a/x/auth/client/testutil/suite.go +++ b/x/auth/client/testutil/suite.go @@ -1117,12 +1117,11 @@ func TestGetBroadcastCommandWithoutOfflineFlag(t *testing.T) { // Create new file with tx builder := txCfg.NewTxBuilder() builder.SetGasLimit(200000) - fromBytes, err := sdk.AccAddressToBytes("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") + from, err := sdk.AccAddressFromBech32("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") require.NoError(t, err) - toBytes, err := sdk.AccAddressToBytes("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") + to, err := sdk.AccAddressFromBech32("link1xpesesq0zddk2ersedyezgtywr0q92a34ddfku") require.NoError(t, err) - err = builder.SetMsgs(banktypes.NewMsgSend(sdk.BytesToAccAddress(fromBytes), - sdk.BytesToAccAddress(toBytes), sdk.Coins{sdk.NewInt64Coin("stake", 10000)})) + err = builder.SetMsgs(banktypes.NewMsgSend(from, to, sdk.Coins{sdk.NewInt64Coin("stake", 10000)})) require.NoError(t, err) txContents, err := txCfg.TxJSONEncoder()(builder.GetTx()) require.NoError(t, err) diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 88e95ee634..4a88644d14 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, txBuild txFactory = txFactory.WithSignMode(signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON) } - addr := sdk.BytesToAccAddress(info.GetPubKey().Address()) + addr := sdk.AccAddress(info.GetPubKey().Address()) if !isTxSigner(addr, txBuilder.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 19093594a7..d9674ae3a0 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.BytesToAccAddress(priv.PubKey().Address()) + addr = sdk.AccAddress(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 219e853850..da27163eb2 100644 --- a/x/auth/keeper/grpc_query.go +++ b/x/auth/keeper/grpc_query.go @@ -55,10 +55,12 @@ func (ak AccountKeeper) Account(c context.Context, req *types.QueryAccountReques } ctx := sdk.UnwrapSDKContext(c) - if err := sdk.ValidateAccAddress(req.Address); err != nil { + addr, err := sdk.AccAddressFromBech32(req.Address) + + if err != nil { return nil, err } - account := ak.GetAccount(ctx, sdk.AccAddress(req.Address)) + account := ak.GetAccount(ctx, addr) 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 b7e2fb56e2..dce06217a6 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -160,7 +160,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 "" + return nil } return permAddr.GetAddress() diff --git a/x/auth/keeper/querier.go b/x/auth/keeper/querier.go index 71e3d8b13a..8e13585e77 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()) } - err := sdk.ValidateAccAddress(params.Address) + addr, err := sdk.AccAddressFromBech32(params.Address) if err != nil { return nil, err } - account := k.GetAccount(ctx, sdk.AccAddress(params.Address)) + account := k.GetAccount(ctx, addr) 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 d998135f1f..56fea23677 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.BytesToAccAddress(priv1.PubKey().Address()) + addr1 := sdk.AccAddress(priv1.PubKey().Address()) priv2 := secp256k1.GenPrivKey() - addr2 := sdk.BytesToAccAddress(priv2.PubKey().Address()) + addr2 := sdk.AccAddress(priv2.PubKey().Address()) coins := sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} diff --git a/x/auth/legacy/legacytx/stdtx.go b/x/auth/legacy/legacytx/stdtx.go index 68bfea0dca..9998341bf8 100644 --- a/x/auth/legacy/legacytx/stdtx.go +++ b/x/auth/legacy/legacytx/stdtx.go @@ -216,12 +216,12 @@ func (tx StdTx) FeePayer() sdk.AccAddress { if tx.GetSigners() != nil { return tx.GetSigners()[0] } - return "" + return sdk.AccAddress{} } // FeeGranter always returns nil for StdTx func (tx StdTx) FeeGranter() sdk.AccAddress { - return "" + return nil } 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 efcad5ad98..4e9c0c5e17 100644 --- a/x/auth/legacy/legacytx/stdtx_test.go +++ b/x/auth/legacy/legacytx/stdtx_test.go @@ -22,7 +22,7 @@ import ( var ( priv = ed25519.GenPrivKey() - addr = sdk.BytesToAccAddress(priv.PubKey().Address()) + addr = sdk.AccAddress(priv.PubKey().Address()) ) func init() { diff --git a/x/auth/legacy/v040/store.go b/x/auth/legacy/v040/store.go index 765c2b94ea..9fb81b60a7 100644 --- a/x/auth/legacy/v040/store.go +++ b/x/auth/legacy/v040/store.go @@ -1,5 +1,4 @@ package v040 // AddrLen defines a valid address length -const AddrLen = 43 -const ValAddrLen = 50 +const AddrLen = 20 diff --git a/x/auth/signing/handler_map_test.go b/x/auth/signing/handler_map_test.go index 307d67187e..a454db80fd 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.BytesToAccAddress(priv1.PubKey().Address()) + addr1 := sdk.AccAddress(priv1.PubKey().Address()) priv2 := secp256k1.GenPrivKey() - addr2 := sdk.BytesToAccAddress(priv2.PubKey().Address()) + addr2 := sdk.AccAddress(priv2.PubKey().Address()) coins := sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} diff --git a/x/auth/simulation/decoder_test.go b/x/auth/simulation/decoder_test.go index d2080abac3..87789ec147 100644 --- a/x/auth/simulation/decoder_test.go +++ b/x/auth/simulation/decoder_test.go @@ -17,7 +17,7 @@ import ( var ( delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.BytesToAccAddress(delPk1.Address()) + delAddr1 = sdk.AccAddress(delPk1.Address()) ) func TestDecodeStore(t *testing.T) { diff --git a/x/auth/testutil/suite.go b/x/auth/testutil/suite.go index a15a81cde8..3e7b384760 100644 --- a/x/auth/testutil/suite.go +++ b/x/auth/testutil/suite.go @@ -86,7 +86,7 @@ func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { // set test msg msg := testdata.NewTestMsg(addr) - msigAddr := sdk.BytesToAccAddress(multisigPk.Address()) + msigAddr := sdk.AccAddress(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 fc7296f558..cea5a52150 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -134,7 +134,11 @@ func (w *wrapper) GetFee() sdk.Coins { func (w *wrapper) FeePayer() sdk.AccAddress { feePayer := w.tx.AuthInfo.Fee.Payer if feePayer != "" { - return sdk.AccAddress(feePayer) + payerAddr, err := sdk.AccAddressFromBech32(feePayer) + if err != nil { + panic(err) + } + return payerAddr } // use first signer as default if no payer specified return w.GetSigners()[0] @@ -143,9 +147,13 @@ func (w *wrapper) FeePayer() sdk.AccAddress { func (w *wrapper) FeeGranter() sdk.AccAddress { feePayer := w.tx.AuthInfo.Fee.Granter if feePayer != "" { - return sdk.AccAddress(feePayer) + granterAddr, err := sdk.AccAddressFromBech32(feePayer) + if err != nil { + panic(err) + } + return granterAddr } - return "" + return nil } func (w *wrapper) GetMemo() string { diff --git a/x/auth/types/account.go b/x/auth/types/account.go index e7940112e7..667969f8a0 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -1,6 +1,7 @@ package types import ( + "bytes" "encoding/json" "errors" "fmt" @@ -56,7 +57,8 @@ func NewBaseAccountWithAddress(addr sdk.AccAddress) *BaseAccount { // GetAddress - Implements sdk.AccountI. func (acc BaseAccount) GetAddress() sdk.AccAddress { - return sdk.AccAddress(acc.Address) + addr, _ := sdk.AccAddressFromBech32(acc.Address) + return addr } // SetAddress - Implements sdk.AccountI. @@ -122,7 +124,12 @@ func (acc BaseAccount) Validate() error { return nil } - if !sdk.AccAddress(acc.Address).Equals(sdk.BytesToAccAddress(acc.GetPubKey().Address())) { + accAddr, err := sdk.AccAddressFromBech32(acc.Address) + if err != nil { + return err + } + + if !bytes.Equal(acc.GetPubKey().Address().Bytes(), accAddr.Bytes()) { return errors.New("account address and pubkey address do not match") } @@ -154,7 +161,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.BytesToAccAddress(crypto.AddressHash([]byte(name))) + return sdk.AccAddress(crypto.AddressHash([]byte(name))) } // NewEmptyModuleAccount creates a empty ModuleAccount from a string @@ -217,7 +224,7 @@ func (ma ModuleAccount) Validate() error { return errors.New("module account name cannot be blank") } - if ma.Address != sdk.BytesToAccAddress(crypto.AddressHash([]byte(ma.Name))).String() { + if ma.Address != sdk.AccAddress(crypto.AddressHash([]byte(ma.Name))).String() { return fmt.Errorf("address %s cannot be derived from the module name '%s'", ma.Address, ma.Name) } @@ -240,13 +247,13 @@ func (ma ModuleAccount) String() string { // MarshalYAML returns the YAML representation of a ModuleAccount. func (ma ModuleAccount) MarshalYAML() (interface{}, error) { - err := sdk.ValidateAccAddress(ma.Address) + accAddr, err := sdk.AccAddressFromBech32(ma.Address) if err != nil { return nil, err } bs, err := yaml.Marshal(moduleAccountPretty{ - Address: sdk.AccAddress(ma.Address), + Address: accAddr, PubKey: "", AccountNumber: ma.AccountNumber, Sequence: ma.Sequence, @@ -262,13 +269,13 @@ func (ma ModuleAccount) MarshalYAML() (interface{}, error) { // MarshalJSON returns the JSON representation of a ModuleAccount. func (ma ModuleAccount) MarshalJSON() ([]byte, error) { - err := sdk.ValidateAccAddress(ma.Address) + accAddr, err := sdk.AccAddressFromBech32(ma.Address) if err != nil { return nil, err } return json.Marshal(moduleAccountPretty{ - Address: sdk.AccAddress(ma.Address), + Address: accAddr, PubKey: "", AccountNumber: ma.AccountNumber, Sequence: ma.Sequence, diff --git a/x/auth/types/account_test.go b/x/auth/types/account_test.go index a86a28be92..6399360839 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.BytesToAccAddress(pubkey.Address()) + addr := sdk.AccAddress(pubkey.Address()) baseAcc := types.NewBaseAccount(addr, pubkey, 0, 0) tests := []struct { @@ -146,7 +146,7 @@ func TestHasPermissions(t *testing.T) { } func TestValidate(t *testing.T) { - addr := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) baseAcc := types.NewBaseAccount(addr, nil, 0, 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.BytesToAccAddress(pubkey.Address()) + addr := sdk.AccAddress(pubkey.Address()) baseAcc := types.NewBaseAccount(addr, nil, 10, 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.BytesToAccAddress(pubkey.Address()) + addr := sdk.AccAddress(pubkey.Address()) acc := types.NewBaseAccount(addr, secp256k1.GenPrivKey().PubKey(), 0, 0) genAccounts := types.GenesisAccounts{} diff --git a/x/auth/types/genesis_test.go b/x/auth/types/genesis_test.go index 7ffd034e8f..525e85bc0f 100644 --- a/x/auth/types/genesis_test.go +++ b/x/auth/types/genesis_test.go @@ -14,12 +14,12 @@ import ( ) func TestSanitize(t *testing.T) { - addr1 := sdk.BytesToAccAddress(ed25519.GenPrivKey().PubKey().Address()) + addr1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) authAcc1 := types.NewBaseAccountWithAddress(addr1) err := authAcc1.SetAccountNumber(1) require.NoError(t, err) - addr2 := sdk.BytesToAccAddress(ed25519.GenPrivKey().PubKey().Address()) + addr2 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) authAcc2 := types.NewBaseAccountWithAddress(addr2) genAccs := types.GenesisAccounts{authAcc1, authAcc2} @@ -35,8 +35,8 @@ func TestSanitize(t *testing.T) { var ( pk1 = ed25519.GenPrivKey().PubKey() pk2 = ed25519.GenPrivKey().PubKey() - addr1 = sdk.BytesToValAddress(pk1.Address()) - addr2 = sdk.BytesToValAddress(pk2.Address()) + addr1 = sdk.ValAddress(pk1.Address()) + addr2 = sdk.ValAddress(pk2.Address()) ) // require duplicate accounts fails validation diff --git a/x/auth/types/msgs.go b/x/auth/types/msgs.go index e25e1372c2..771650e40c 100644 --- a/x/auth/types/msgs.go +++ b/x/auth/types/msgs.go @@ -23,7 +23,7 @@ func (msg MsgEmpty) Route() string { return ModuleName } func (msg MsgEmpty) Type() string { return TypeMsgEmpty } func (msg MsgEmpty) ValidateBasic() error { - err := sdk.ValidateAccAddress(msg.FromAddress) + _, err := sdk.AccAddressFromBech32(msg.FromAddress) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) } @@ -37,9 +37,9 @@ func (msg MsgEmpty) GetSignBytes() []byte { // GetSigners Implements Msg. func (msg MsgEmpty) GetSigners() []sdk.AccAddress { - err := sdk.ValidateAccAddress(msg.FromAddress) + addr, err := sdk.AccAddressFromBech32(msg.FromAddress) if err != nil { panic(err) } - return []sdk.AccAddress{sdk.AccAddress(msg.FromAddress)} + return []sdk.AccAddress{addr} } diff --git a/x/auth/types/msgs_test.go b/x/auth/types/msgs_test.go index 58dfd83f77..04e4b693e7 100644 --- a/x/auth/types/msgs_test.go +++ b/x/auth/types/msgs_test.go @@ -18,9 +18,9 @@ func TestMsgSendRoute(t *testing.T) { } func TestMsgSendValidation(t *testing.T) { - addr1 := sdk.BytesToAccAddress([]byte("from________________")) + addr1 := sdk.AccAddress([]byte("from________________")) addrEmpty := sdk.AccAddress("") - addrLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) + addrLong := sdk.AccAddress([]byte("Accidentally used 33 bytes pubkey")) cases := []struct { expectedErr string // empty means no error expected @@ -42,14 +42,14 @@ func TestMsgSendValidation(t *testing.T) { } func TestMsgSendGetSignBytes(t *testing.T) { - res := NewMsgEmpty(sdk.BytesToAccAddress([]byte("input"))).GetSignBytes() + res := NewMsgEmpty(sdk.AccAddress([]byte("input"))).GetSignBytes() expected := `{"type":"cosmos-sdk/MsgEmpty","value":{"from_address":"link1d9h8qat5fnwd3e"}}` require.Equal(t, expected, string(res)) } func TestMsgSendGetSigners(t *testing.T) { - res := NewMsgEmpty(sdk.BytesToAccAddress([]byte("input111111111111111"))).GetSigners() - bytes, _ := sdk.AccAddressToBytes(res[0].String()) - require.Equal(t, fmt.Sprintf("%v", hex.EncodeToString(bytes)), "696e707574313131313131313131313131313131") + res := NewMsgEmpty(sdk.AccAddress([]byte("input111111111111111"))).GetSigners() + bytes, _ := sdk.AccAddressFromBech32(res[0].String()) + require.Equal(t, "696e707574313131313131313131313131313131", fmt.Sprintf("%v", hex.EncodeToString(bytes))) } diff --git a/x/auth/vesting/client/cli/tx.go b/x/auth/vesting/client/cli/tx.go index 4eb4552130..988c26311c 100644 --- a/x/auth/vesting/client/cli/tx.go +++ b/x/auth/vesting/client/cli/tx.go @@ -51,7 +51,10 @@ timestamp.`, if err != nil { return err } - toAddr := sdk.AccAddress(args[0]) + toAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } amount, err := sdk.ParseCoinsNormalized(args[1]) if err != nil { diff --git a/x/auth/vesting/client/testutil/suite.go b/x/auth/vesting/client/testutil/suite.go index c14d782c72..dfc3f93233 100644 --- a/x/auth/vesting/client/testutil/suite.go +++ b/x/auth/vesting/client/testutil/suite.go @@ -49,7 +49,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }{ "create a continuous vesting account": { args: []string{ - sdk.BytesToAccAddress([]byte("addr2_______________")).String(), + sdk.AccAddress("addr2_______________").String(), sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -63,7 +63,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "create a delayed vesting account": { args: []string{ - sdk.BytesToAccAddress([]byte("addr3_______________")).String(), + sdk.AccAddress("addr3_______________").String(), sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -78,7 +78,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "invalid address": { args: []string{ - sdk.BytesToAccAddress([]byte("addr4")).String(), + sdk.AccAddress("addr4").String(), sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String(), "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -89,7 +89,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "invalid coins": { args: []string{ - sdk.BytesToAccAddress([]byte("addr4_______________")).String(), + sdk.AccAddress("addr4_______________").String(), "fooo", "4070908800", fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address), @@ -100,7 +100,7 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { }, "invalid end time": { args: []string{ - sdk.BytesToAccAddress([]byte("addr4_______________")).String(), + sdk.AccAddress("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/handler_test.go b/x/auth/vesting/handler_test.go index 5d6c900d2b..c99a0225f0 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, ocproto.Header{Height: suite.app.LastBlockHeight() + 1}) balances := sdk.NewCoins(sdk.NewInt64Coin("test", 1000)) - addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) - addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) - addr3 := sdk.BytesToAccAddress([]byte("addr3_______________")) + addr1 := sdk.AccAddress([]byte("addr1_______________")) + addr2 := sdk.AccAddress([]byte("addr2_______________")) + addr3 := sdk.AccAddress([]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) - err := sdk.ValidateAccAddress(tc.msg.ToAddress) + toAddr, err := sdk.AccAddressFromBech32(tc.msg.ToAddress) suite.Require().NoError(err) - accI := suite.app.AccountKeeper.GetAccount(ctx, sdk.AccAddress(tc.msg.ToAddress)) + accI := suite.app.AccountKeeper.GetAccount(ctx, toAddr) 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 2a1f8d8a56..08a4437d0e 100644 --- a/x/auth/vesting/msg_server.go +++ b/x/auth/vesting/msg_server.go @@ -36,8 +36,14 @@ func (s msgServer) CreateVestingAccount(goCtx context.Context, msg *types.MsgCre return nil, err } - from := sdk.AccAddress(msg.FromAddress) - to := sdk.AccAddress(msg.ToAddress) + 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 bk.BlockedAddr(to) { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress) @@ -78,7 +84,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 b5cd8808c7..645318d367 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.BytesToValAddress(pk1.Address()) - addr2 = sdk.BytesToValAddress(pk2.Address()) + addr1 = sdk.ValAddress(pk1.Address()) + addr2 = sdk.ValAddress(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.BytesToAccAddress(pk2.Address())) + acc2 := authtypes.NewBaseAccountWithAddress(sdk.AccAddress(addr2)) // 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 6db0b97283..0d04e99a65 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.AccAddressToBytes(msg.FromAddress) + from, err := sdk.AccAddressFromBech32(msg.FromAddress) if err != nil { return err } - to, err := sdk.AccAddressToBytes(msg.ToAddress) + to, err := sdk.AccAddressFromBech32(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 { - err := sdk.ValidateAccAddress(msg.FromAddress) + from, err := sdk.AccAddressFromBech32(msg.FromAddress) if err != nil { panic(err) } - return []sdk.AccAddress{sdk.AccAddress(msg.FromAddress)} + return []sdk.AccAddress{from} } diff --git a/x/auth/vesting/types/test_common.go b/x/auth/vesting/types/test_common.go index 7f18302cbd..ad5cdff066 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.BytesToAccAddress(pub.Address()) + addr := sdk.AccAddress(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 bf5648b4c2..8a6f31a3cb 100644 --- a/x/auth/vesting/types/vesting_account.go +++ b/x/auth/vesting/types/vesting_account.go @@ -183,8 +183,13 @@ 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 + } + out := vestingAccountYAML{ - Address: sdk.AccAddress(bva.Address), + Address: accAddr, AccountNumber: bva.AccountNumber, PubKey: getPKString(bva), Sequence: bva.Sequence, @@ -291,8 +296,13 @@ 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 + } + out := vestingAccountYAML{ - Address: sdk.AccAddress(cva.Address), + Address: accAddr, AccountNumber: cva.AccountNumber, PubKey: getPKString(cva), Sequence: cva.Sequence, @@ -429,8 +439,13 @@ 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 + } + out := vestingAccountYAML{ - Address: sdk.AccAddress(pva.Address), + Address: accAddr, AccountNumber: pva.AccountNumber, PubKey: getPKString(pva), Sequence: pva.Sequence, diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 557213b008..0b4b6c0962 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -661,7 +661,7 @@ func TestTrackUndelegationPermLockedVestingAcc(t *testing.T) { func TestGenesisAccountValidate(t *testing.T) { pubkey := secp256k1.GenPrivKey().PubKey() - addr := sdk.BytesToAccAddress(pubkey.Address()) + addr := sdk.AccAddress(pubkey.Address()) baseAcc := authtypes.NewBaseAccount(addr, pubkey, 0, 0) initialVesting := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)) baseVestingWithCoins := types.NewBaseVestingAccount(baseAcc, initialVesting, 100) diff --git a/x/authz/client/cli/query.go b/x/authz/client/cli/query.go index a03a58e5a6..3e7586e8dd 100644 --- a/x/authz/client/cli/query.go +++ b/x/authz/client/cli/query.go @@ -55,23 +55,18 @@ $ %s query %s grants link1skjw.. link1skjwj.. %s } queryClient := authz.NewQueryClient(clientCtx) - err = sdk.ValidateAccAddress(args[0]) + granter, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } - granter := sdk.AccAddress(args[0]) - - err = sdk.ValidateAccAddress(args[1]) + grantee, err := sdk.AccAddressFromBech32(args[1]) if err != nil { return err } - grantee := sdk.AccAddress(args[1]) - var msgAuthorized = "" if len(args) >= 3 { msgAuthorized = args[2] } - pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { return err diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index 6ee497ae2a..5bc1146c33 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -70,11 +70,10 @@ Examples: return err } - err = sdk.ValidateAccAddress(args[0]) + grantee, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } - grantee := sdk.AccAddress(args[0]) exp, err := cmd.Flags().GetInt64(FlagExpiration) if err != nil { @@ -135,12 +134,12 @@ Examples: delegateLimit = &spendLimit[0] } - allowed, err := toValidatorAddresses(allowValidators) + allowed, err := bech32toValidatorAddresses(allowValidators) if err != nil { return err } - denied, err := toValidatorAddresses(denyValidators) + denied, err := bech32toValidatorAddresses(denyValidators) if err != nil { return err } @@ -195,11 +194,10 @@ Example: return err } - err = sdk.ValidateAccAddress(args[0]) + grantee, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } - grantee := sdk.AccAddress(args[0]) granter := clientCtx.GetFromAddress() msgAuthorized := args[1] @@ -251,14 +249,13 @@ Example: return cmd } -func toValidatorAddresses(validators []string) ([]sdk.ValAddress, error) { +func bech32toValidatorAddresses(validators []string) ([]sdk.ValAddress, error) { vals := make([]sdk.ValAddress, len(validators)) for i, validator := range validators { - err := sdk.ValidateValAddress(validator) + addr, err := sdk.ValAddressFromBech32(validator) if err != nil { return nil, err } - addr := sdk.ValAddress([]byte(validator)) vals[i] = addr } return vals, nil diff --git a/x/authz/client/rest/grpc_query_test.go b/x/authz/client/rest/grpc_query_test.go index 602e7a48ed..0918f99aa2 100644 --- a/x/authz/client/rest/grpc_query_test.go +++ b/x/authz/client/rest/grpc_query_test.go @@ -47,7 +47,7 @@ func (s *IntegrationTestSuite) SetupSuite() { // Create new account in the keyring. info, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) - newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) // Send some funds to the new account. out, err := banktestutil.MsgSendExec( diff --git a/x/authz/client/testutil/tx.go b/x/authz/client/testutil/tx.go index f8879c6ea8..52c2b484bc 100644 --- a/x/authz/client/testutil/tx.go +++ b/x/authz/client/testutil/tx.go @@ -45,7 +45,7 @@ func (s *IntegrationTestSuite) SetupSuite() { // Create new account in the keyring. info, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) - newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address().Bytes()) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) // Send some funds to the new account. _, err = banktestutil.MsgSendExec( diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index 987150fc97..6ed4e29319 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -33,8 +33,8 @@ func (suite *GenesisTestSuite) SetupTest() { var ( granteePub = secp256k1.GenPrivKey().PubKey() granterPub = secp256k1.GenPrivKey().PubKey() - granteeAddr = sdk.BytesToAccAddress(granteePub.Address().Bytes()) - granterAddr = sdk.BytesToAccAddress(granterPub.Address().Bytes()) + granteeAddr = sdk.AccAddress(granteePub.Address()) + granterAddr = sdk.AccAddress(granterPub.Address()) ) func (suite *GenesisTestSuite) TestImportExportGenesis() { diff --git a/x/authz/keeper/grpc_query.go b/x/authz/keeper/grpc_query.go index 4e65444c09..945a13d227 100644 --- a/x/authz/keeper/grpc_query.go +++ b/x/authz/keeper/grpc_query.go @@ -24,19 +24,17 @@ func (k Keeper) Grants(c context.Context, req *authz.QueryGrantsRequest) (*authz return nil, status.Errorf(codes.InvalidArgument, "empty request") } - err := sdk.ValidateAccAddress(req.Granter) + granter, err := sdk.AccAddressFromBech32(req.Granter) if err != nil { return nil, err } - granter := sdk.AccAddress(req.Granter) - err = sdk.ValidateAccAddress(req.Grantee) + grantee, err := sdk.AccAddressFromBech32(req.Grantee) if err != nil { return nil, err } - grantee := sdk.AccAddress(req.Grantee) - ctx := sdk.UnwrapSDKContext(c) + store := ctx.KVStore(k.storeKey) key := grantStoreKey(grantee, granter, "") authStore := prefix.NewStore(store, key) diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index db9b37cc69..41b3885eb6 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -232,18 +232,14 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) *authz.GenesisState { // InitGenesis new authz genesis func (k Keeper) InitGenesis(ctx sdk.Context, data *authz.GenesisState) { for _, entry := range data.Authorization { - err := sdk.ValidateAccAddress(entry.Grantee) + grantee, err := sdk.AccAddressFromBech32(entry.Grantee) if err != nil { panic(err) } - grantee := sdk.AccAddress(entry.Grantee) - - err = sdk.ValidateAccAddress(entry.Granter) + granter, err := sdk.AccAddressFromBech32(entry.Granter) if err != nil { panic(err) } - granter := sdk.AccAddress(entry.Granter) - a, ok := entry.Authorization.GetCachedValue().(authz.Authorization) if !ok { panic("expected authorization") diff --git a/x/authz/keeper/keys.go b/x/authz/keeper/keys.go index 6c48fb90ff..1c017eea8d 100644 --- a/x/authz/keeper/keys.go +++ b/x/authz/keeper/keys.go @@ -21,8 +21,8 @@ const StoreKey = authz.ModuleName // - 0x01: Grant func grantStoreKey(grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) []byte { m := conv.UnsafeStrToBytes(msgType) - granter = sdk.AccAddress(address.MustLengthPrefix(granter.Bytes())) - grantee = sdk.AccAddress(address.MustLengthPrefix(grantee.Bytes())) + granter = address.MustLengthPrefix(granter) + grantee = address.MustLengthPrefix(grantee) l := 1 + len(grantee) + len(granter) + len(m) var key = make([]byte, l) diff --git a/x/authz/keeper/msg_server.go b/x/authz/keeper/msg_server.go index e9fa5af49a..aca57d26db 100644 --- a/x/authz/keeper/msg_server.go +++ b/x/authz/keeper/msg_server.go @@ -13,17 +13,14 @@ var _ authz.MsgServer = Keeper{} // GrantAuthorization implements the MsgServer.Grant method to create a new grant. func (k Keeper) Grant(goCtx context.Context, msg *authz.MsgGrant) (*authz.MsgGrantResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return nil, err } - grantee := sdk.AccAddress(msg.Grantee) - - err = sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { return nil, err } - granter := sdk.AccAddress(msg.Granter) authorization := msg.GetAuthorization() if authorization == nil { @@ -45,17 +42,14 @@ func (k Keeper) Grant(goCtx context.Context, msg *authz.MsgGrant) (*authz.MsgGra // RevokeAuthorization implements the MsgServer.Revoke method. func (k Keeper) Revoke(goCtx context.Context, msg *authz.MsgRevoke) (*authz.MsgRevokeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return nil, err } - grantee := sdk.AccAddress(msg.Grantee) - - err = sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { return nil, err } - granter := sdk.AccAddress(msg.Granter) err = k.DeleteGrant(ctx, grantee, granter, msg.MsgTypeUrl) if err != nil { @@ -68,11 +62,10 @@ func (k Keeper) Revoke(goCtx context.Context, msg *authz.MsgRevoke) (*authz.MsgR // Exec implements the MsgServer.Exec method. func (k Keeper) Exec(goCtx context.Context, msg *authz.MsgExec) (*authz.MsgExecResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return nil, err } - grantee := sdk.AccAddress(msg.Grantee) msgs, err := msg.GetMessages() if err != nil { return nil, err diff --git a/x/authz/msgs.go b/x/authz/msgs.go index 52d77062e8..cc0a0046d4 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -43,27 +43,23 @@ func NewMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a Authorization // GetSigners implements Msg func (msg MsgGrant) GetSigners() []sdk.AccAddress { - err := sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { panic(err) } - granter := sdk.AccAddress(msg.Granter) return []sdk.AccAddress{granter} } // ValidateBasic implements Msg func (msg MsgGrant) ValidateBasic() error { - err := sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "invalid granter address") } - granter := sdk.AccAddress(msg.Granter) - - err = sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "invalid granter address") } - grantee := sdk.AccAddress(msg.Grantee) if granter.Equals(grantee) { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "granter and grantee cannot be same") @@ -135,27 +131,23 @@ func NewMsgRevoke(granter sdk.AccAddress, grantee sdk.AccAddress, msgTypeURL str // GetSigners implements Msg func (msg MsgRevoke) GetSigners() []sdk.AccAddress { - err := sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { panic(err) } - granter := sdk.AccAddress(msg.Granter) return []sdk.AccAddress{granter} } // ValidateBasic implements MsgRequest.ValidateBasic func (msg MsgRevoke) ValidateBasic() error { - err := sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "invalid granter address") } - granter := sdk.AccAddress(msg.Granter) - - err = sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "invalid grantee address") } - grantee := sdk.AccAddress(msg.Grantee) if granter.Equals(grantee) { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "granter and grantee cannot be same") @@ -218,17 +210,16 @@ func (msg MsgExec) GetMessages() ([]sdk.Msg, error) { // GetSigners implements Msg func (msg MsgExec) GetSigners() []sdk.AccAddress { - err := sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { panic(err) } - grantee := sdk.AccAddress(msg.Grantee) return []sdk.AccAddress{grantee} } // ValidateBasic implements Msg func (msg MsgExec) ValidateBasic() error { - err := sdk.ValidateAccAddress(msg.Grantee) + _, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "invalid grantee address") } diff --git a/x/authz/msgs_test.go b/x/authz/msgs_test.go index b37e37cbd4..a7006d11b5 100644 --- a/x/authz/msgs_test.go +++ b/x/authz/msgs_test.go @@ -14,8 +14,8 @@ import ( var ( coinsPos = sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) - granter = sdk.BytesToAccAddress([]byte("_______granter______")) - grantee = sdk.BytesToAccAddress([]byte("_______grantee______")) + granter = sdk.AccAddress("_______granter______") + grantee = sdk.AccAddress("_______grantee______") ) func TestMsgExecAuthorized(t *testing.T) { @@ -25,7 +25,7 @@ func TestMsgExecAuthorized(t *testing.T) { msgs []sdk.Msg expectPass bool }{ - {"nil grantee address", "", []sdk.Msg{}, false}, + {"nil grantee address", nil, []sdk.Msg{}, false}, {"zero-messages test: should fail", grantee, []sdk.Msg{}, false}, {"valid test: msg type", grantee, []sdk.Msg{ &banktypes.MsgSend{ @@ -51,9 +51,9 @@ func TestMsgRevokeAuthorization(t *testing.T) { msgType string expectPass bool }{ - {"nil Granter address", "", grantee, "hello", false}, - {"nil Grantee address", granter, "", "hello", false}, - {"nil Granter and Grantee address", "", "", "hello", false}, + {"nil Granter address", nil, grantee, "hello", false}, + {"nil Grantee address", granter, nil, "hello", false}, + {"nil Granter and Grantee address", nil, nil, "hello", false}, {"valid test case", granter, grantee, "hello", true}, } for i, tc := range tests { @@ -75,9 +75,9 @@ func TestMsgGrantAuthorization(t *testing.T) { expectErr bool expectPass bool }{ - {"nil granter address", "", grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, - {"nil grantee address", granter, "", &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, - {"nil granter and grantee address", "", "", &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, + {"nil granter address", nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, + {"nil grantee address", granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, + {"nil granter and grantee address", nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, {"nil authorization", granter, grantee, nil, time.Now(), true, false}, {"valid test case", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true}, {"past time", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, true}, // TODO need 0.45 diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 6dab83c376..833544ca29 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -34,12 +34,12 @@ type ( var ( priv1 = secp256k1.GenPrivKey() - addr1 = sdk.BytesToAccAddress(priv1.PubKey().Address()) + addr1 = sdk.AccAddress(priv1.PubKey().Address()) priv2 = secp256k1.GenPrivKey() - addr2 = sdk.BytesToAccAddress(priv2.PubKey().Address()) - addr3 = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr2 = sdk.AccAddress(priv2.PubKey().Address()) + addr3 = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) priv4 = secp256k1.GenPrivKey() - addr4 = sdk.BytesToAccAddress(priv4.PubKey().Address()) + addr4 = sdk.AccAddress(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 f4f120ccdd..d0b5e97e03 100644 --- a/x/bank/client/cli/query.go +++ b/x/bank/client/cli/query.go @@ -65,10 +65,11 @@ Example: queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateAccAddress(args[0]); err != nil { + 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 { return err diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index 0e215f92c1..51998c55ba 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -38,7 +38,10 @@ ignored as it is implied from [from_key_or_address].`, if err != nil { return err } - toAddr := sdk.AccAddress(args[1]) + toAddr, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } 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 8d628fc343..e0578172b0 100644 --- a/x/bank/client/rest/query.go +++ b/x/bank/client/rest/query.go @@ -21,7 +21,10 @@ func QueryBalancesRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { vars := mux.Vars(r) bech32addr := vars["address"] - addr := sdk.AccAddress(bech32addr) + addr, err := sdk.AccAddressFromBech32(bech32addr) + if rest.CheckInternalServerError(w, err) { + return + } 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 41d09fbb8e..abbefecf04 100644 --- a/x/bank/client/rest/tx.go +++ b/x/bank/client/rest/tx.go @@ -25,7 +25,10 @@ func NewSendRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { vars := mux.Vars(r) bech32Addr := vars["address"] - toAddr := sdk.AccAddress(bech32Addr) + toAddr, err := sdk.AccAddressFromBech32(bech32Addr) + if rest.CheckBadRequestError(w, err) { + return + } var req SendReq if !rest.ReadRESTReq(w, r, clientCtx.LegacyAmino, &req) { @@ -37,7 +40,10 @@ func NewSendRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr := sdk.AccAddress(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + if rest.CheckBadRequestError(w, err) { + return + } msg := types.NewMsgSend(fromAddr, toAddr, req.Amount) tx.WriteGeneratedTxResponse(clientCtx, w, req.BaseReq, msg) diff --git a/x/bank/handler_test.go b/x/bank/handler_test.go index 1d94c87fee..7caec8baf6 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.BytesToAccAddress(priv1.PubKey().Address()) + addr1 := sdk.AccAddress(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 d03f574824..3b80eeb092 100644 --- a/x/bank/keeper/genesis.go +++ b/x/bank/keeper/genesis.go @@ -16,7 +16,11 @@ func (k BaseKeeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) { genState.Balances = types.SanitizeGenesisBalances(genState.Balances) for _, balance := range genState.Balances { - addr := sdk.AccAddress(balance.Address) + addr, err := sdk.AccAddressFromBech32(balance.Address) + if err != nil { + panic(err) + } + if err := k.initBalances(ctx, addr, 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 b6df1d782e..798a7e3a93 100644 --- a/x/bank/keeper/genesis_test.go +++ b/x/bank/keeper/genesis_test.go @@ -14,7 +14,7 @@ func (suite *IntegrationTestSuite) TestExportGenesis() { expectedBalances, totalSupply := suite.getTestBalancesAndSupply() for i := range []int{1, 2} { app.BankKeeper.SetDenomMetaData(ctx, expectedMetadata[i]) - err1 := sdk.ValidateAccAddress(expectedBalances[i].Address) + accAddr, err1 := sdk.AccAddressFromBech32(expectedBalances[i].Address) if err1 != nil { panic(err1) } @@ -24,7 +24,7 @@ func (suite *IntegrationTestSuite) TestExportGenesis() { NoError(app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedBalances[i].Coins)) suite. Require(). - NoError(app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, sdk.AccAddress(expectedBalances[i].Address), expectedBalances[i].Coins)) + NoError(app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, accAddr, expectedBalances[i].Coins)) } app.BankKeeper.SetParams(ctx, types.DefaultParams()) @@ -38,8 +38,8 @@ func (suite *IntegrationTestSuite) TestExportGenesis() { } func (suite *IntegrationTestSuite) getTestBalancesAndSupply() ([]types.Balance, sdk.Coins) { - addr2 := sdk.AccAddress("link1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0p662v8") - addr1 := sdk.AccAddress("link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3q4fdzl") + addr2, _ := sdk.AccAddressFromBech32("link1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0p662v8") + addr1, _ := sdk.AccAddressFromBech32("link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3q4fdzl") addr1Balance := sdk.Coins{sdk.NewInt64Coin("testcoin3", 10)} addr2Balance := sdk.Coins{sdk.NewInt64Coin("testcoin1", 32), sdk.NewInt64Coin("testcoin2", 34)} @@ -68,9 +68,9 @@ func (suite *IntegrationTestSuite) TestTotalSupply() { // Prepare some test data. defaultGenesis := types.DefaultGenesisState() balances := []types.Balance{ - {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(1))), Address: "link1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0556gh0"}, - {Coins: sdk.NewCoins(sdk.NewCoin("barcoin", sdk.NewInt(1))), Address: "link1t5u0jfg3ljsjrh2m9e47d4ny2hea7eehxrzdgd"}, - {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(10)), sdk.NewCoin("barcoin", sdk.NewInt(20))), Address: "link1m3h30wlvsf8llruxtpukdvsy0km2kum8g38c8q"}, + {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(1))), Address: "link1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0p662v8"}, + {Coins: sdk.NewCoins(sdk.NewCoin("barcoin", sdk.NewInt(1))), Address: "link1t5u0jfg3ljsjrh2m9e47d4ny2hea7eehndz0n9"}, + {Coins: sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(10)), sdk.NewCoin("barcoin", sdk.NewInt(20))), Address: "link1m3h30wlvsf8llruxtpukdvsy0km2kum8al86ug"}, } totalSupply := sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(11)), sdk.NewCoin("barcoin", sdk.NewInt(21))) diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index ac86873d64..b4f1e4b99b 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -24,16 +24,18 @@ func (k BaseKeeper) Balance(ctx context.Context, req *types.QueryBalanceRequest) return nil, status.Error(codes.InvalidArgument, "address cannot be empty") } - if err := sdk.ValidateAccAddress(req.Address); err != nil { - return nil, status.Error(codes.InvalidArgument, "invalid bech32 format") - } - if req.Denom == "" { return nil, status.Error(codes.InvalidArgument, "invalid denom") } sdkCtx := sdk.UnwrapSDKContext(ctx) - balance := k.GetBalance(sdkCtx, sdk.AccAddress(req.Address), req.Denom) + 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) + return &types.QueryBalanceResponse{Balance: &balance}, nil } @@ -47,14 +49,15 @@ func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalances return nil, status.Error(codes.InvalidArgument, "address cannot be empty") } - if err := sdk.ValidateAccAddress(req.Address); err != nil { - return nil, status.Error(codes.InvalidArgument, "invalid bech32 format") + 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() - accountStore := k.getAccountStore(sdkCtx, sdk.AccAddress(req.Address)) + accountStore := k.getAccountStore(sdkCtx, addr) pageRes, err := query.Paginate(accountStore, req.Pagination, func(_, value []byte) error { var result sdk.Coin diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 7a577e0c30..e95aaf2bf2 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -72,11 +72,6 @@ func (suite *IntegrationTestSuite) TestQueryAllBalances() { suite.Equal(res.Balances.Len(), 1) suite.NotNil(res.Pagination.NextKey) - // invalid bech32 address - invalidReq := types.NewQueryAllBalancesRequest(sdk.AccAddress(addr.String()[0:10]), pageReq) - _, err = queryClient.AllBalances(gocontext.Background(), invalidReq) - suite.Require().Error(err) - suite.T().Log("query second page with nextkey") pageReq = &query.PageRequest{ Key: res.Pagination.NextKey, diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 4b92c63693..3c12863543 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -152,7 +152,7 @@ func (suite *IntegrationTestSuite) TestSendCoinsFromModuleToAccount_Blacklist() maccPerms[multiPerm] = []string{authtypes.Burner, authtypes.Minter, authtypes.Staking} maccPerms[randomPerm] = []string{"random"} - addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) + addr1 := sdk.AccAddress([]byte("addr1_______________")) authKeeper := authkeeper.NewAccountKeeper( appCodec, app.GetKey(types.StoreKey), app.GetSubspace(types.ModuleName), @@ -353,7 +353,7 @@ func (suite *IntegrationTestSuite) TestInputOutputNewAccount() { app, ctx := suite.app, suite.ctx balances := sdk.NewCoins(newFooCoin(100), newBarCoin(50)) - addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) + addr1 := sdk.AccAddress([]byte("addr1_______________")) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) suite.Require().NoError(simapp.FundAccount(app, ctx, addr1, balances)) @@ -361,7 +361,7 @@ func (suite *IntegrationTestSuite) TestInputOutputNewAccount() { acc1Balances := app.BankKeeper.GetAllBalances(ctx, addr1) suite.Require().Equal(balances, acc1Balances) - addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) + addr2 := sdk.AccAddress([]byte("addr2_______________")) suite.Require().Nil(app.AccountKeeper.GetAccount(ctx, addr2)) suite.Require().Empty(app.BankKeeper.GetAllBalances(ctx, addr2)) @@ -385,15 +385,15 @@ func (suite *IntegrationTestSuite) TestInputOutputCoins() { app, ctx := suite.app, suite.ctx balances := sdk.NewCoins(newFooCoin(90), newBarCoin(30)) - addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) + addr1 := sdk.AccAddress([]byte("addr1_______________")) acc1 := app.AccountKeeper.NewAccountWithAddress(ctx, addr1) app.AccountKeeper.SetAccount(ctx, acc1) - addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) + addr2 := sdk.AccAddress([]byte("addr2_______________")) acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) app.AccountKeeper.SetAccount(ctx, acc2) - addr3 := sdk.BytesToAccAddress([]byte("addr3_______________")) + addr3 := sdk.AccAddress([]byte("addr3_______________")) acc3 := app.AccountKeeper.NewAccountWithAddress(ctx, addr3) app.AccountKeeper.SetAccount(ctx, acc3) @@ -604,10 +604,10 @@ func (suite *IntegrationTestSuite) TestMsgMultiSendEvents() { app.BankKeeper.SetParams(ctx, types.DefaultParams()) - addr := sdk.BytesToAccAddress([]byte("addr1_______________")) - addr2 := sdk.BytesToAccAddress([]byte("addr2_______________")) - addr3 := sdk.BytesToAccAddress([]byte("addr3_______________")) - addr4 := sdk.BytesToAccAddress([]byte("addr4_______________")) + addr := sdk.AccAddress([]byte("addr1_______________")) + addr2 := sdk.AccAddress([]byte("addr2_______________")) + addr3 := sdk.AccAddress([]byte("addr3_______________")) + addr4 := sdk.AccAddress([]byte("addr4_______________")) acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) acc2 := app.AccountKeeper.NewAccountWithAddress(ctx, addr2) @@ -1076,7 +1076,7 @@ func (suite *IntegrationTestSuite) TestBalanceTrackingEvents() { sdk.NewCoins(sdk.NewCoin("utxo", sdk.NewInt(100000)))), ) // send coins to address - addr1 := sdk.BytesToAccAddress([]byte("addr1_______________")) + addr1 := sdk.AccAddress("addr1_______________") suite.Require().NoError( suite.app.BankKeeper.SendCoinsFromModuleToAccount( suite.ctx, @@ -1115,17 +1115,15 @@ func (suite *IntegrationTestSuite) TestBalanceTrackingEvents() { case types.EventTypeCoinSpent: coinsSpent, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) suite.Require().NoError(err) - err = sdk.ValidateAccAddress(string(e.Attributes[0].Value)) + spender, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) suite.Require().NoError(err) - spender := sdk.AccAddress(e.Attributes[0].Value) balances[spender.String()] = balances[spender.String()].Sub(coinsSpent) case types.EventTypeCoinReceived: coinsRecv, err := sdk.ParseCoinsNormalized((string)(e.Attributes[1].Value)) suite.Require().NoError(err) - err = sdk.ValidateAccAddress(string(e.Attributes[0].Value)) + receiver, err := sdk.AccAddressFromBech32((string)(e.Attributes[0].Value)) suite.Require().NoError(err) - receiver := sdk.AccAddress(e.Attributes[0].Value) balances[receiver.String()] = balances[receiver.String()].Add(coinsRecv...) } } diff --git a/x/bank/keeper/msg_server.go b/x/bank/keeper/msg_server.go index 85dabc584a..2608a8d5a0 100644 --- a/x/bank/keeper/msg_server.go +++ b/x/bank/keeper/msg_server.go @@ -30,11 +30,20 @@ func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSe return nil, err } - if k.BlockedAddr(sdk.AccAddress(msg.ToAddress)) { + 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) { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress) } - err := k.SendCoins(ctx, sdk.AccAddress(msg.FromAddress), sdk.AccAddress(msg.ToAddress), msg.Amount) + err = k.SendCoins(ctx, from, to, msg.Amount) if err != nil { return nil, err } @@ -72,7 +81,11 @@ func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*t } for _, out := range msg.Outputs { - if k.BlockedAddr(sdk.AccAddress(out.Address)) { + accAddr, err := sdk.AccAddressFromBech32(out.Address) + if err != nil { + panic(err) + } + if k.BlockedAddr(accAddr) { 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 2286579b1f..e4dd48c5c7 100644 --- a/x/bank/keeper/querier.go +++ b/x/bank/keeper/querier.go @@ -38,7 +38,12 @@ func queryBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerie return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - balance := k.GetBalance(ctx, sdk.AccAddress(params.Address), params.Denom) + address, err := sdk.AccAddressFromBech32(params.Address) + if err != nil { + return nil, err + } + + balance := k.GetBalance(ctx, address, params.Denom) bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, balance) if err != nil { @@ -55,7 +60,12 @@ func queryAllBalance(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - balances := k.GetAllBalances(ctx, sdk.AccAddress(params.Address)) + address, err := sdk.AccAddressFromBech32(params.Address) + if err != nil { + return nil, err + } + + balances := k.GetAllBalances(ctx, 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 7aaa79ebd1..6aba1be430 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -58,10 +58,6 @@ 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) @@ -84,9 +80,12 @@ func (k BaseSendKeeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, } for _, in := range inputs { - inAddress := sdk.AccAddress(in.Address) + inAddress, err := sdk.AccAddressFromBech32(in.Address) + if err != nil { + return err + } - err := k.subUnlockedCoins(ctx, inAddress, in.Coins) + err = k.subUnlockedCoins(ctx, inAddress, in.Coins) if err != nil { return err } @@ -100,8 +99,11 @@ func (k BaseSendKeeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, } for _, out := range outputs { - outAddress := sdk.AccAddress(out.Address) - err := k.addCoins(ctx, outAddress, out.Coins) + outAddress, err := sdk.AccAddressFromBech32(out.Address) + if err != nil { + return err + } + err = k.addCoins(ctx, outAddress, out.Coins) if err != nil { return err } diff --git a/x/bank/legacy/v043/json_test.go b/x/bank/legacy/v043/json_test.go index 1008224ec9..abec64c30d 100644 --- a/x/bank/legacy/v043/json_test.go +++ b/x/bank/legacy/v043/json_test.go @@ -20,7 +20,8 @@ func TestMigrateJSON(t *testing.T) { WithTxConfig(encodingConfig.TxConfig). WithCodec(encodingConfig.Marshaler) - voter := sdk.AccAddress("link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh") + voter, err := sdk.AccAddressFromBech32("link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3q4fdzl") + require.NoError(t, err) bankGenState := &types.GenesisState{ Balances: []types.Balance{ { @@ -58,7 +59,7 @@ func TestMigrateJSON(t *testing.T) { expected := `{ "balances": [ { - "address": "link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", + "address": "link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3q4fdzl", "coins": [ { "amount": "20", diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 53fd4bf3e2..60e37f5a6e 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -123,7 +123,10 @@ func sendMsgSend( err error ) - from := sdk.AccAddress(msg.FromAddress) + from, err := sdk.AccAddressFromBech32(msg.FromAddress) + if err != nil { + return err + } account := ak.GetAccount(ctx, from) spendable := bk.SpendableCoins(ctx, account.GetAddress()) @@ -326,7 +329,10 @@ func sendMsgMultiSend( sequenceNumbers := make([]uint64, len(msg.Inputs)) for i := 0; i < len(msg.Inputs); i++ { - addr := sdk.AccAddress(msg.Inputs[i].Address) + addr, err := sdk.AccAddressFromBech32(msg.Inputs[i].Address) + if err != nil { + panic(err) + } acc := ak.GetAccount(ctx, addr) accountNumbers[i] = acc.GetAccountNumber() sequenceNumbers[i] = acc.GetSequence() @@ -337,7 +343,10 @@ func sendMsgMultiSend( err error ) - addr := sdk.AccAddress(msg.Inputs[0].Address) + addr, err := sdk.AccAddressFromBech32(msg.Inputs[0].Address) + if err != nil { + panic(err) + } // 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 089a2500b0..a90278d03f 100644 --- a/x/bank/types/balance.go +++ b/x/bank/types/balance.go @@ -3,6 +3,7 @@ package types import ( "bytes" "encoding/json" + "fmt" "sort" "github.com/line/lbm-sdk/codec" @@ -14,7 +15,12 @@ var _ exported.GenesisBalance = (*Balance)(nil) // GetAddress returns the account address of the Balance object. func (b Balance) GetAddress() sdk.AccAddress { - return sdk.AccAddress(b.Address) + 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 } // GetCoins returns the account coins of the Balance object. @@ -24,8 +30,7 @@ func (b Balance) GetCoins() sdk.Coins { // Validate checks for address and coins correctness. func (b Balance) Validate() error { - err := sdk.ValidateAccAddress(b.Address) - if err != nil { + if _, err := sdk.AccAddressFromBech32(b.Address); err != nil { return err } @@ -43,7 +48,7 @@ type balanceByAddress struct { func (b balanceByAddress) Len() int { return len(b.addresses) } func (b balanceByAddress) Less(i, j int) bool { - return bytes.Compare(b.addresses[i].Bytes(), b.addresses[j].Bytes()) < 0 + return bytes.Compare(b.addresses[i], b.addresses[j]) < 0 } func (b balanceByAddress) Swap(i, j int) { b.addresses[i], b.addresses[j] = b.addresses[j], b.addresses[i] @@ -64,7 +69,7 @@ func SanitizeGenesisBalances(balances []Balance) []Balance { // 1. Retrieve the address equivalents for each Balance's address. addresses := make([]sdk.AccAddress, len(balances)) for i := range balances { - addr := sdk.AccAddress(balances[i].Address) + addr, _ := sdk.AccAddressFromBech32(balances[i].Address) addresses[i] = addr } diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go index dae95fba4b..86b86c8e5c 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -118,9 +118,9 @@ func TestBalanceValidate(t *testing.T) { func TestBalance_GetAddress(t *testing.T) { tests := []struct { - name string - Address string - expErr bool + name string + Address string + wantPanic bool }{ {"empty address", "", true}, {"malformed address", "invalid", true}, @@ -130,11 +130,10 @@ func TestBalance_GetAddress(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { b := bank.Balance{Address: tt.Address} - err := sdk.ValidateAccAddress(b.GetAddress().String()) - if tt.expErr { - require.Error(t, err) + if tt.wantPanic { + require.Panics(t, func() { b.GetAddress() }) } else { - require.NoError(t, err) + require.False(t, b.GetAddress().Empty()) } }) } @@ -166,7 +165,7 @@ func TestSanitizeBalances(t *testing.T) { for j := i + 1; j < len(sorted); j++ { aj := sorted[j] - if got := bytes.Compare(ai.GetAddress().Bytes(), aj.GetAddress().Bytes()); got > 0 { + if got := bytes.Compare(ai.GetAddress(), aj.GetAddress()); got > 0 { t.Errorf("Balance(%d) > Balance(%d)", i, j) } } diff --git a/x/bank/types/key.go b/x/bank/types/key.go index 9250e025ba..a85dd983ab 100644 --- a/x/bank/types/key.go +++ b/x/bank/types/key.go @@ -26,9 +26,6 @@ var ( BalancesPrefix = []byte{0x02} SupplyKey = []byte{0x00} DenomMetadataPrefix = []byte{0x1} - - // Contract: Address must not contain this character - AddressDenomDelimiter = "," ) // DenomMetadataKey returns the denomination metadata key. @@ -44,14 +41,14 @@ func DenomMetadataKey(denom string) []byte { // If invalid key is passed, AddressFromBalancesStore returns ErrInvalidKey. func AddressFromBalancesStore(key []byte) (sdk.AccAddress, error) { if len(key) == 0 { - return "", ErrInvalidKey + return nil, ErrInvalidKey } addrLen := key[0] bound := int(addrLen) if len(key)-1 < bound { - return "", ErrInvalidKey + return nil, ErrInvalidKey } - return sdk.AccAddress(key[1 : bound+1]), nil + return key[1 : bound+1], nil } // CreateAccountBalancesPrefix creates the prefix for an account's balances. diff --git a/x/bank/types/key_test.go b/x/bank/types/key_test.go index 55f250bcc4..18f2962644 100644 --- a/x/bank/types/key_test.go +++ b/x/bank/types/key_test.go @@ -20,12 +20,11 @@ func cloneAppend(bz []byte, tail []byte) (res []byte) { } func TestAddressFromBalancesStore(t *testing.T) { - addr := sdk.AccAddress("link19tzp7e489drh9qfs9m84k2qe5a5yyknzen48tz") - err := sdk.ValidateAccAddress(addr.String()) + addr, err := sdk.AccAddressFromBech32("link19tzp7e489drh9qfs9m84k2qe5a5yyknzen48tz") require.NoError(t, err) addrLen := len(addr) - require.Equal(t, 43, addrLen) - key := cloneAppend(address.MustLengthPrefix(addr.Bytes()), []byte("stake")) + require.Equal(t, 20, addrLen) + key := cloneAppend(address.MustLengthPrefix(addr), []byte("stake")) tests := []struct { name string @@ -34,9 +33,9 @@ func TestAddressFromBalancesStore(t *testing.T) { expectedKey sdk.AccAddress }{ {"valid", key, false, addr}, - {"#9111", []byte("\xff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), false, ""}, - {"empty", []byte(""), true, ""}, - {"invalid", []byte("3AA"), true, ""}, + {"#9111", []byte("\xff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), false, nil}, + {"empty", []byte(""), true, nil}, + {"invalid", []byte("3AA"), true, nil}, } for _, tc := range tests { diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index e440952b1e..4eda612d2e 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.ValidateAccAddress(msg.FromAddress) // TODO: Is this really required? + _, err := sdk.AccAddressFromBech32(msg.FromAddress) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) } - err = sdk.ValidateAccAddress(msg.ToAddress) // TODO: Is this really required? + _, err = sdk.AccAddressFromBech32(msg.ToAddress) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid recipient address (%s)", err) } @@ -55,7 +55,11 @@ func (msg MsgSend) GetSignBytes() []byte { // GetSigners Implements Msg. func (msg MsgSend) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(msg.FromAddress)} + from, err := sdk.AccAddressFromBech32(msg.FromAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{from} } var _ sdk.Msg = &MsgMultiSend{} @@ -95,7 +99,8 @@ func (msg MsgMultiSend) GetSignBytes() []byte { func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { addrs := make([]sdk.AccAddress, len(msg.Inputs)) for i, in := range msg.Inputs { - addrs[i] = sdk.AccAddress(in.Address) + addr, _ := sdk.AccAddressFromBech32(in.Address) + addrs[i] = addr } return addrs @@ -103,7 +108,7 @@ func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { // ValidateBasic - validate transaction input func (in Input) ValidateBasic() error { - err := sdk.ValidateAccAddress(in.Address) + _, err := sdk.AccAddressFromBech32(in.Address) if err != nil { return err } @@ -130,7 +135,7 @@ func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { // ValidateBasic - validate transaction output func (out Output) ValidateBasic() error { - err := sdk.ValidateAccAddress(out.Address) + _, err := sdk.AccAddressFromBech32(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 c8a31e430a..57185a20ce 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.BytesToAccAddress([]byte("from")) - addr2 := sdk.BytesToAccAddress([]byte("to")) + addr1 := sdk.AccAddress([]byte("from")) + addr2 := sdk.AccAddress([]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.BytesToAccAddress([]byte("from________________")) - addr2 := sdk.BytesToAccAddress([]byte("to__________________")) - addrEmpty := sdk.AccAddress("") - addrLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) + addr1 := sdk.AccAddress([]byte("from________________")) + addr2 := sdk.AccAddress([]byte("to__________________")) + addrEmpty := sdk.AccAddress([]byte("")) + addrLong := sdk.AccAddress([]byte("Purposefully long address")) 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.BytesToAccAddress([]byte("input")) - addr2 := sdk.BytesToAccAddress([]byte("output")) + addr1 := sdk.AccAddress([]byte("input")) + addr2 := sdk.AccAddress([]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.NewCoins()) + var msg = NewMsgSend(sdk.AccAddress([]byte("input111111111111111")), sdk.AccAddress{}, 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.BytesToAccAddress([]byte("input")) - addr2 := sdk.BytesToAccAddress([]byte("output")) + addr1 := sdk.AccAddress([]byte("input")) + addr2 := sdk.AccAddress([]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.BytesToAccAddress([]byte("_______alice________")) - addr2 := sdk.BytesToAccAddress([]byte("________bob_________")) - addrEmpty := sdk.AccAddress("") - addrLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) + addr1 := sdk.AccAddress([]byte("_______alice________")) + addr2 := sdk.AccAddress([]byte("________bob_________")) + addrEmpty := sdk.AccAddress([]byte("")) + addrLong := sdk.AccAddress([]byte("Purposefully long address")) 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.BytesToAccAddress([]byte("_______alice________")) - addr2 := sdk.BytesToAccAddress([]byte("________bob_________")) - addrEmpty := sdk.AccAddress("") - addrLong := sdk.BytesToAccAddress([]byte("Accidentally used 33 bytes pubkey")) + addr1 := sdk.AccAddress([]byte("_______alice________")) + addr2 := sdk.AccAddress([]byte("________bob_________")) + addrEmpty := sdk.AccAddress([]byte("")) + addrLong := sdk.AccAddress([]byte("Purposefully long address")) 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.BytesToAccAddress([]byte("_______alice________")) - addr2 := sdk.BytesToAccAddress([]byte("________bob_________")) + addr1 := sdk.AccAddress([]byte("_______alice________")) + addr2 := sdk.AccAddress([]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.BytesToAccAddress([]byte("input")) - addr2 := sdk.BytesToAccAddress([]byte("output")) + addr1 := sdk.AccAddress([]byte("input")) + addr2 := sdk.AccAddress([]byte("output")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) var msg = MsgMultiSend{ Inputs: []Input{NewInput(addr1, coins)}, @@ -253,9 +253,9 @@ func TestMsgMultiSendGetSigners(t *testing.T) { func TestMsgSendSigners(t *testing.T) { signers := []sdk.AccAddress{ - "123", - "456", - "789", + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, } someCoins := sdk.NewCoins(sdk.NewInt64Coin("atom", 123)) diff --git a/x/bank/types/send_authorization_test.go b/x/bank/types/send_authorization_test.go index 8609143acd..575d7249c1 100644 --- a/x/bank/types/send_authorization_test.go +++ b/x/bank/types/send_authorization_test.go @@ -15,8 +15,8 @@ import ( var ( coins1000 = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000))) coins500 = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(500))) - fromAddr = sdk.BytesToAccAddress([]byte("_____from _____")) - toAddr = sdk.BytesToAccAddress([]byte("_______to________")) + fromAddr = sdk.AccAddress("_____from _____") + toAddr = sdk.AccAddress("_______to________") ) func TestSendAuthorization(t *testing.T) { diff --git a/x/bankplus/keeper/inactive_test.go b/x/bankplus/keeper/inactive_test.go index 37069dc962..c02bd7cd7c 100644 --- a/x/bankplus/keeper/inactive_test.go +++ b/x/bankplus/keeper/inactive_test.go @@ -22,7 +22,7 @@ import ( func genAddress() sdk.AccAddress { b := make([]byte, 20) rand.Read(b) - return sdk.BytesToAccAddress(b) + return b } func setupKeeper(storeKey *sdk.KVStoreKey) BaseKeeper { diff --git a/x/collection/client/cli/query.go b/x/collection/client/cli/query.go index 25ba5b583c..abad85c2a7 100644 --- a/x/collection/client/cli/query.go +++ b/x/collection/client/cli/query.go @@ -67,7 +67,7 @@ func NewQueryCmdBalances() *cobra.Command { } address := args[1] - if err := sdk.ValidateAccAddress(address); err != nil { + if _, err := sdk.AccAddressFromBech32(address); err != nil { return err } @@ -716,7 +716,7 @@ func NewQueryCmdGrant() *cobra.Command { } grantee := args[1] - if err := sdk.ValidateAccAddress(grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(grantee); err != nil { return err } @@ -758,7 +758,7 @@ func NewQueryCmdGranteeGrants() *cobra.Command { } grantee := args[1] - if err := sdk.ValidateAccAddress(grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(grantee); err != nil { return err } @@ -797,12 +797,12 @@ func NewQueryCmdAuthorization() *cobra.Command { } operator := args[1] - if err := sdk.ValidateAccAddress(operator); err != nil { + if _, err := sdk.AccAddressFromBech32(operator); err != nil { return err } holder := args[2] - if err := sdk.ValidateAccAddress(holder); err != nil { + if _, err := sdk.AccAddressFromBech32(holder); err != nil { return err } @@ -842,7 +842,7 @@ func NewQueryCmdOperatorAuthorizations() *cobra.Command { } operator := args[1] - if err := sdk.ValidateAccAddress(operator); err != nil { + if _, err := sdk.AccAddressFromBech32(operator); err != nil { return err } diff --git a/x/collection/client/testutil/suite.go b/x/collection/client/testutil/suite.go index 965bd044d6..b788293749 100644 --- a/x/collection/client/testutil/suite.go +++ b/x/collection/client/testutil/suite.go @@ -71,7 +71,7 @@ func (s *IntegrationTestSuite) SetupSuite() { for _, to := range []sdk.AccAddress{s.customer, s.operator, s.vendor} { s.mintFT(s.contractID, s.vendor, to, s.ftClassID, s.balance) - if to == s.vendor { + if to.Equals(s.vendor) { tokenID := collection.NewFTID(s.ftClassID) amount := collection.NewCoins(collection.NewCoin(tokenID, s.balance)) s.burn(s.contractID, s.vendor, amount) diff --git a/x/collection/genesis.go b/x/collection/genesis.go index 0851203284..d161deb168 100644 --- a/x/collection/genesis.go +++ b/x/collection/genesis.go @@ -81,7 +81,7 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidRequest.Wrap("balances cannot be empty") } for _, balance := range contractBalances.Balances { - if err := sdk.ValidateAccAddress(balance.Address); err != nil { + if _, err := sdk.AccAddressFromBech32(balance.Address); err != nil { return err } if err := balance.Amount.ValidateBasic(); err != nil { @@ -138,10 +138,10 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidRequest.Wrap("authorizations cannot be empty") } for _, authorization := range contractAuthorizations.Authorizations { - if err := sdk.ValidateAccAddress(authorization.Holder); err != nil { + if _, err := sdk.AccAddressFromBech32(authorization.Holder); err != nil { return err } - if err := sdk.ValidateAccAddress(authorization.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(authorization.Operator); err != nil { return err } } @@ -156,7 +156,7 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidRequest.Wrap("grants cannot be empty") } for _, grant := range contractGrants.Grants { - if err := sdk.ValidateAccAddress(grant.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(grant.Grantee); err != nil { return err } if err := ValidatePermission(grant.Permission); err != nil { diff --git a/x/collection/genesis_test.go b/x/collection/genesis_test.go index 0767a26522..6831231a6c 100644 --- a/x/collection/genesis_test.go +++ b/x/collection/genesis_test.go @@ -12,7 +12,7 @@ import ( ) func TestValidateGenesis(t *testing.T) { - addr := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) testCases := map[string]struct { gs *collection.GenesisState valid bool diff --git a/x/collection/keeper/genesis.go b/x/collection/keeper/genesis.go index 3c8e6d5881..304704b84b 100644 --- a/x/collection/keeper/genesis.go +++ b/x/collection/keeper/genesis.go @@ -45,10 +45,15 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *collection.GenesisState) { for _, balance := range contractBalances.Balances { for _, coin := range balance.Amount { - k.setBalance(ctx, contractID, sdk.AccAddress(balance.Address), coin.TokenId, coin.Amount) + addr, err := sdk.AccAddressFromBech32(balance.Address) + if err != nil { + panic(err) + } + + k.setBalance(ctx, contractID, addr, coin.TokenId, coin.Amount) if err := collection.ValidateNFTID(coin.TokenId); err == nil { - k.setOwner(ctx, contractID, coin.TokenId, sdk.AccAddress(balance.Address)) + k.setOwner(ctx, contractID, coin.TokenId, addr) } } } @@ -75,13 +80,25 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *collection.GenesisState) { for _, contractAuthorizations := range data.Authorizations { for _, authorization := range contractAuthorizations.Authorizations { - k.setAuthorization(ctx, contractAuthorizations.ContractId, sdk.AccAddress(authorization.Holder), sdk.AccAddress(authorization.Operator)) + holderAddr, err := sdk.AccAddressFromBech32(authorization.Holder) + if err != nil { + panic(err) + } + operatorAddr, err := sdk.AccAddressFromBech32(authorization.Operator) + if err != nil { + panic(err) + } + k.setAuthorization(ctx, contractAuthorizations.ContractId, holderAddr, operatorAddr) } } for _, contractGrants := range data.Grants { for _, grant := range contractGrants.Grants { - k.setGrant(ctx, contractGrants.ContractId, sdk.AccAddress(grant.Grantee), grant.Permission) + granteeAddr, err := sdk.AccAddressFromBech32(grant.Grantee) + if err != nil { + panic(err) + } + k.setGrant(ctx, contractGrants.ContractId, granteeAddr, grant.Permission) } } @@ -204,10 +221,10 @@ func (k Keeper) getBalances(ctx sdk.Context, contracts []collection.Contract) [] func (k Keeper) getContractBalances(ctx sdk.Context, contractID string) []collection.Balance { var balances []collection.Balance - addressToBalanceIndex := make(map[sdk.AccAddress]int) + addressToBalanceIndex := make(map[string]int) k.iterateContractBalances(ctx, contractID, func(address sdk.AccAddress, balance collection.Coin) (stop bool) { - index, ok := addressToBalanceIndex[address] + index, ok := addressToBalanceIndex[address.String()] if ok { balances[index].Amount = append(balances[index].Amount, balance) return false @@ -218,7 +235,7 @@ func (k Keeper) getContractBalances(ctx sdk.Context, contractID string) []collec Amount: collection.Coins{balance}, } balances = append(balances, accountBalance) - addressToBalanceIndex[address] = len(balances) - 1 + addressToBalanceIndex[address.String()] = len(balances) - 1 return false }) diff --git a/x/collection/keeper/grpc_query.go b/x/collection/keeper/grpc_query.go index 0dc5730d07..4d5e14d1f6 100644 --- a/x/collection/keeper/grpc_query.go +++ b/x/collection/keeper/grpc_query.go @@ -39,7 +39,8 @@ func (s queryServer) Balance(c context.Context, req *collection.QueryBalanceRequ return nil, err } - if err := sdk.ValidateAccAddress(req.Address); err != nil { + addr, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", req.Address) } @@ -48,7 +49,7 @@ func (s queryServer) Balance(c context.Context, req *collection.QueryBalanceRequ } ctx := sdk.UnwrapSDKContext(c) - balance := s.keeper.GetBalance(ctx, req.ContractId, sdk.AccAddress(req.Address), req.TokenId) + balance := s.keeper.GetBalance(ctx, req.ContractId, addr, req.TokenId) coin := collection.NewCoin(req.TokenId, balance) return &collection.QueryBalanceResponse{Balance: coin}, nil @@ -64,13 +65,14 @@ func (s queryServer) AllBalances(c context.Context, req *collection.QueryAllBala return nil, err } - if err := sdk.ValidateAccAddress(req.Address); err != nil { + addr, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", req.Address) } ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) - balanceStore := prefix.NewStore(store, balanceKeyPrefixByAddress(req.ContractId, sdk.AccAddress(req.Address))) + balanceStore := prefix.NewStore(store, balanceKeyPrefixByAddress(req.ContractId, addr)) var balances []collection.Coin pageRes, err := query.Paginate(balanceStore, req.Pagination, func(key []byte, value []byte) error { tokenID := string(key) @@ -769,7 +771,8 @@ func (s queryServer) Grant(c context.Context, req *collection.QueryGrantRequest) return nil, err } - if err := sdk.ValidateAccAddress(req.Grantee); err != nil { + granteeAddr, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.Grantee) } @@ -778,7 +781,7 @@ func (s queryServer) Grant(c context.Context, req *collection.QueryGrantRequest) } ctx := sdk.UnwrapSDKContext(c) - grant, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Grantee), req.Permission) + grant, err := s.keeper.GetGrant(ctx, req.ContractId, granteeAddr, req.Permission) if err != nil { return nil, err } @@ -795,13 +798,14 @@ func (s queryServer) GranteeGrants(c context.Context, req *collection.QueryGrant return nil, err } - if err := sdk.ValidateAccAddress(req.Grantee); err != nil { + granteeAddr, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.Grantee) } ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) - grantStore := prefix.NewStore(store, grantKeyPrefixByGrantee(req.ContractId, sdk.AccAddress(req.Grantee))) + grantStore := prefix.NewStore(store, grantKeyPrefixByGrantee(req.ContractId, granteeAddr)) var grants []collection.Grant pageRes, err := query.Paginate(grantStore, req.Pagination, func(key []byte, _ []byte) error { permission := collection.Permission(key[0]) @@ -827,15 +831,17 @@ func (s queryServer) Authorization(c context.Context, req *collection.QueryAutho return nil, err } - if err := sdk.ValidateAccAddress(req.Operator); err != nil { + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) } - if err := sdk.ValidateAccAddress(req.Holder); err != nil { + holderAddr, err := sdk.AccAddressFromBech32(req.Holder) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", req.Holder) } ctx := sdk.UnwrapSDKContext(c) - authorization, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.Holder), sdk.AccAddress(req.Operator)) + authorization, err := s.keeper.GetAuthorization(ctx, req.ContractId, holderAddr, operatorAddr) if err != nil { return nil, err } @@ -852,13 +858,14 @@ func (s queryServer) OperatorAuthorizations(c context.Context, req *collection.Q return nil, err } - if err := sdk.ValidateAccAddress(req.Operator); err != nil { + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) } ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) - authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, sdk.AccAddress(req.Operator))) + authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, operatorAddr)) var authorizations []collection.Authorization pageRes, err := query.Paginate(authorizationStore, req.Pagination, func(key []byte, value []byte) error { holder := sdk.AccAddress(key) @@ -884,15 +891,17 @@ func (s queryServer) Approved(c context.Context, req *collection.QueryApprovedRe return nil, err } - if err := sdk.ValidateAccAddress(req.Address); err != nil { + addr, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Approver); err != nil { + approverAddr, err := sdk.AccAddressFromBech32(req.Approver) + if err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) - _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.Approver), sdk.AccAddress(req.Address)) + _, err = s.keeper.GetAuthorization(ctx, req.ContractId, approverAddr, addr) approved := (err == nil) return &collection.QueryApprovedResponse{Approved: approved}, nil @@ -907,13 +916,14 @@ func (s queryServer) Approvers(c context.Context, req *collection.QueryApprovers return nil, err } - if err := sdk.ValidateAccAddress(req.Address); err != nil { + addr, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address address: %s", req.Address) } ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) - authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, sdk.AccAddress(req.Address))) + authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, addr)) var approvers []string pageRes, err := query.Paginate(authorizationStore, req.Pagination, func(key []byte, value []byte) error { holder := string(key) diff --git a/x/collection/keeper/keeper_test.go b/x/collection/keeper/keeper_test.go index af9cf0f652..9b73c75b65 100644 --- a/x/collection/keeper/keeper_test.go +++ b/x/collection/keeper/keeper_test.go @@ -38,15 +38,15 @@ type KeeperTestSuite struct { } func createRandomAccounts(accNum int) []sdk.AccAddress { - seenAddresses := make(map[sdk.AccAddress]bool, accNum) + seenAddresses := make(map[string]bool, accNum) addresses := make([]sdk.AccAddress, accNum) for i := 0; i < accNum; i++ { var address sdk.AccAddress for { pk := secp256k1.GenPrivKey().PubKey() - address = sdk.BytesToAccAddress(pk.Address()) - if !seenAddresses[address] { - seenAddresses[address] = true + address = sdk.AccAddress(pk.Address()) + if !seenAddresses[address.String()] { + seenAddresses[address.String()] = true break } } diff --git a/x/collection/keeper/msg_server.go b/x/collection/keeper/msg_server.go index d9789d1015..f277b7d604 100644 --- a/x/collection/keeper/msg_server.go +++ b/x/collection/keeper/msg_server.go @@ -38,7 +38,17 @@ func (s msgServer) Send(c context.Context, req *collection.MsgSend) (*collection } ctx.EventManager().EmitEvents(collection.NewEventTransferNFT(event)) - if err := s.keeper.SendCoins(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + if err := s.keeper.SendCoins(ctx, req.ContractId, fromAddr, toAddr, req.Amount); err != nil { return nil, err } @@ -51,7 +61,18 @@ func (s msgServer) Send(c context.Context, req *collection.MsgSend) (*collection func (s msgServer) OperatorSend(c context.Context, req *collection.MsgOperatorSend) (*collection.MsgOperatorSendResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Operator)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, operatorAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -68,7 +89,12 @@ func (s msgServer) OperatorSend(c context.Context, req *collection.MsgOperatorSe } ctx.EventManager().EmitEvents(collection.NewEventTransferNFTFrom(event)) - if err := s.keeper.SendCoins(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + if err := s.keeper.SendCoins(ctx, req.ContractId, fromAddr, toAddr, req.Amount); err != nil { return nil, err } @@ -81,7 +107,18 @@ func (s msgServer) OperatorSend(c context.Context, req *collection.MsgOperatorSe func (s msgServer) TransferFT(c context.Context, req *collection.MsgTransferFT) (*collection.MsgTransferFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.SendCoins(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + if err := s.keeper.SendCoins(ctx, req.ContractId, fromAddr, toAddr, req.Amount); err != nil { return nil, err } @@ -102,11 +139,27 @@ func (s msgServer) TransferFT(c context.Context, req *collection.MsgTransferFT) func (s msgServer) TransferFTFrom(c context.Context, req *collection.MsgTransferFTFrom) (*collection.MsgTransferFTFromResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Proxy)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, proxyAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - if err := s.keeper.SendCoins(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + if err := s.keeper.SendCoins(ctx, req.ContractId, fromAddr, toAddr, req.Amount); err != nil { return nil, err } @@ -143,7 +196,17 @@ func (s msgServer) TransferNFT(c context.Context, req *collection.MsgTransferNFT } ctx.EventManager().EmitEvents(collection.NewEventTransferNFT(event)) - if err := s.keeper.SendCoins(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), amount); err != nil { + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + if err := s.keeper.SendCoins(ctx, req.ContractId, fromAddr, toAddr, amount); err != nil { return nil, err } @@ -161,7 +224,18 @@ func (s msgServer) TransferNFTFrom(c context.Context, req *collection.MsgTransfe } ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Proxy)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, proxyAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -174,8 +248,12 @@ func (s msgServer) TransferNFTFrom(c context.Context, req *collection.MsgTransfe Amount: amount, } ctx.EventManager().EmitEvents(collection.NewEventTransferNFTFrom(event)) + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } - if err := s.keeper.SendCoins(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), amount); err != nil { + if err := s.keeper.SendCoins(ctx, req.ContractId, fromAddr, toAddr, amount); err != nil { return nil, err } @@ -188,7 +266,18 @@ func (s msgServer) TransferNFTFrom(c context.Context, req *collection.MsgTransfe func (s msgServer) AuthorizeOperator(c context.Context, req *collection.MsgAuthorizeOperator) (*collection.MsgAuthorizeOperatorResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, sdk.AccAddress(req.Holder), sdk.AccAddress(req.Operator)); err != nil { + + holderAddr, err := sdk.AccAddressFromBech32(req.Holder) + if err != nil { + return nil, err + } + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, holderAddr, operatorAddr); err != nil { return nil, err } @@ -206,7 +295,18 @@ func (s msgServer) AuthorizeOperator(c context.Context, req *collection.MsgAutho func (s msgServer) RevokeOperator(c context.Context, req *collection.MsgRevokeOperator) (*collection.MsgRevokeOperatorResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.RevokeOperator(ctx, req.ContractId, sdk.AccAddress(req.Holder), sdk.AccAddress(req.Operator)); err != nil { + + holderAddr, err := sdk.AccAddressFromBech32(req.Holder) + if err != nil { + return nil, err + } + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if err := s.keeper.RevokeOperator(ctx, req.ContractId, holderAddr, operatorAddr); err != nil { return nil, err } @@ -224,7 +324,18 @@ func (s msgServer) RevokeOperator(c context.Context, req *collection.MsgRevokeOp func (s msgServer) Approve(c context.Context, req *collection.MsgApprove) (*collection.MsgApproveResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, sdk.AccAddress(req.Approver), sdk.AccAddress(req.Proxy)); err != nil { + + approverAddr, err := sdk.AccAddressFromBech32(req.Approver) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, approverAddr, proxyAddr); err != nil { return nil, err } @@ -242,7 +353,18 @@ func (s msgServer) Approve(c context.Context, req *collection.MsgApprove) (*coll func (s msgServer) Disapprove(c context.Context, req *collection.MsgDisapprove) (*collection.MsgDisapproveResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.RevokeOperator(ctx, req.ContractId, sdk.AccAddress(req.Approver), sdk.AccAddress(req.Proxy)); err != nil { + + approverAddr, err := sdk.AccAddressFromBech32(req.Approver) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if err := s.keeper.RevokeOperator(ctx, req.ContractId, approverAddr, proxyAddr); err != nil { return nil, err } @@ -265,14 +387,26 @@ func (s msgServer) CreateContract(c context.Context, req *collection.MsgCreateCo BaseImgUri: req.BaseImgUri, Meta: req.Meta, } - id := s.keeper.CreateContract(ctx, sdk.AccAddress(req.Owner), contract) + + ownerAddr, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, err + } + + id := s.keeper.CreateContract(ctx, ownerAddr, contract) return &collection.MsgCreateContractResponse{Id: id}, nil } func (s msgServer) CreateFTClass(c context.Context, req *collection.MsgCreateFTClass) (*collection.MsgCreateFTClassResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Operator), collection.PermissionIssue); err != nil { + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, operatorAddr, collection.PermissionIssue); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -296,14 +430,21 @@ func (s msgServer) CreateFTClass(c context.Context, req *collection.MsgCreateFTC Decimals: class.Decimals, Mintable: class.Mintable, } - ctx.EventManager().EmitEvent(collection.NewEventIssueFT(event, sdk.AccAddress(req.Operator), sdk.AccAddress(req.To), req.Supply)) + + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + // Default address to send the initial supply is operator address. + toAddr = operatorAddr + } + + ctx.EventManager().EmitEvent(collection.NewEventIssueFT(event, operatorAddr, toAddr, req.Supply)) if err := ctx.EventManager().EmitTypedEvent(&event); err != nil { panic(err) } // supply tokens if req.Supply.IsPositive() { - s.keeper.mintFT(ctx, req.ContractId, sdk.AccAddress(req.To), *id, req.Supply) + s.keeper.mintFT(ctx, req.ContractId, toAddr, *id, req.Supply) event := collection.EventMintedFT{ ContractId: req.ContractId, @@ -321,7 +462,13 @@ func (s msgServer) CreateFTClass(c context.Context, req *collection.MsgCreateFTC func (s msgServer) CreateNFTClass(c context.Context, req *collection.MsgCreateNFTClass) (*collection.MsgCreateNFTClassResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Operator), collection.PermissionIssue); err != nil { + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, operatorAddr, collection.PermissionIssue); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -350,7 +497,13 @@ func (s msgServer) CreateNFTClass(c context.Context, req *collection.MsgCreateNF func (s msgServer) IssueFT(c context.Context, req *collection.MsgIssueFT) (*collection.MsgIssueFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Owner), collection.PermissionIssue); err != nil { + + ownerAddr, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, ownerAddr, collection.PermissionIssue); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -373,14 +526,20 @@ func (s msgServer) IssueFT(c context.Context, req *collection.MsgIssueFT) (*coll Decimals: class.Decimals, Mintable: class.Mintable, } - ctx.EventManager().EmitEvent(collection.NewEventIssueFT(event, sdk.AccAddress(req.Owner), sdk.AccAddress(req.To), req.Amount)) + + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvent(collection.NewEventIssueFT(event, ownerAddr, toAddr, req.Amount)) if err := ctx.EventManager().EmitTypedEvent(&event); err != nil { panic(err) } // supply tokens if req.Amount.IsPositive() { - s.keeper.mintFT(ctx, req.ContractId, sdk.AccAddress(req.To), *id, req.Amount) + s.keeper.mintFT(ctx, req.ContractId, toAddr, *id, req.Amount) event := collection.EventMintedFT{ ContractId: req.ContractId, @@ -398,7 +557,13 @@ func (s msgServer) IssueFT(c context.Context, req *collection.MsgIssueFT) (*coll func (s msgServer) IssueNFT(c context.Context, req *collection.MsgIssueNFT) (*collection.MsgIssueNFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Owner), collection.PermissionIssue); err != nil { + + ownerAddr, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, ownerAddr, collection.PermissionIssue); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -426,7 +591,7 @@ func (s msgServer) IssueNFT(c context.Context, req *collection.MsgIssueNFT) (*co collection.PermissionMint, collection.PermissionBurn, } { - s.keeper.Grant(ctx, req.ContractId, "", sdk.AccAddress(req.Owner), permission) + s.keeper.Grant(ctx, req.ContractId, []byte{}, ownerAddr, permission) } return &collection.MsgIssueNFTResponse{Id: *id}, nil @@ -434,11 +599,22 @@ func (s msgServer) IssueNFT(c context.Context, req *collection.MsgIssueNFT) (*co func (s msgServer) MintFT(c context.Context, req *collection.MsgMintFT) (*collection.MsgMintFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.From), collection.PermissionMint); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, fromAddr, collection.PermissionMint); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - if err := s.keeper.MintFT(ctx, req.ContractId, sdk.AccAddress(req.To), req.Amount); err != nil { + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + if err := s.keeper.MintFT(ctx, req.ContractId, toAddr, req.Amount); err != nil { return nil, err } @@ -458,11 +634,22 @@ func (s msgServer) MintFT(c context.Context, req *collection.MsgMintFT) (*collec func (s msgServer) MintNFT(c context.Context, req *collection.MsgMintNFT) (*collection.MsgMintNFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.From), collection.PermissionMint); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, fromAddr, collection.PermissionMint); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - tokens, err := s.keeper.MintNFT(ctx, req.ContractId, sdk.AccAddress(req.To), req.Params) + toAddr, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + + tokens, err := s.keeper.MintNFT(ctx, req.ContractId, toAddr, req.Params) if err != nil { return nil, err } @@ -487,7 +674,13 @@ func (s msgServer) MintNFT(c context.Context, req *collection.MsgMintNFT) (*coll func (s msgServer) Burn(c context.Context, req *collection.MsgBurn) (*collection.MsgBurnResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.From), collection.PermissionBurn); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, fromAddr, collection.PermissionBurn); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -503,7 +696,7 @@ func (s msgServer) Burn(c context.Context, req *collection.MsgBurn) (*collection } ctx.EventManager().EmitEvents(collection.NewEventBurnNFT(event)) - burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, sdk.AccAddress(req.From), req.Amount) + burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, fromAddr, req.Amount) if err != nil { return nil, err } @@ -519,11 +712,22 @@ func (s msgServer) Burn(c context.Context, req *collection.MsgBurn) (*collection func (s msgServer) OperatorBurn(c context.Context, req *collection.MsgOperatorBurn) (*collection.MsgOperatorBurnResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Operator)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, operatorAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Operator), collection.PermissionBurn); err != nil { + if _, err := s.keeper.GetGrant(ctx, req.ContractId, operatorAddr, collection.PermissionBurn); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -539,7 +743,7 @@ func (s msgServer) OperatorBurn(c context.Context, req *collection.MsgOperatorBu } ctx.EventManager().EmitEvents(collection.NewEventBurnNFTFrom(event)) - burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, sdk.AccAddress(req.From), req.Amount) + burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, fromAddr, req.Amount) if err != nil { return nil, err } @@ -555,11 +759,17 @@ func (s msgServer) OperatorBurn(c context.Context, req *collection.MsgOperatorBu func (s msgServer) BurnFT(c context.Context, req *collection.MsgBurnFT) (*collection.MsgBurnFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.From), collection.PermissionBurn); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, fromAddr, collection.PermissionBurn); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, sdk.AccAddress(req.From), req.Amount) + burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, fromAddr, req.Amount) if err != nil { return nil, err } @@ -582,15 +792,26 @@ func (s msgServer) BurnFT(c context.Context, req *collection.MsgBurnFT) (*collec func (s msgServer) BurnFTFrom(c context.Context, req *collection.MsgBurnFTFrom) (*collection.MsgBurnFTFromResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Proxy)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, proxyAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Proxy), collection.PermissionBurn); err != nil { + if _, err := s.keeper.GetGrant(ctx, req.ContractId, proxyAddr, collection.PermissionBurn); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, sdk.AccAddress(req.From), req.Amount) + burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, fromAddr, req.Amount) if err != nil { return nil, err } @@ -613,7 +834,13 @@ func (s msgServer) BurnFTFrom(c context.Context, req *collection.MsgBurnFTFrom) func (s msgServer) BurnNFT(c context.Context, req *collection.MsgBurnNFT) (*collection.MsgBurnNFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.From), collection.PermissionBurn); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetGrant(ctx, req.ContractId, fromAddr, collection.PermissionBurn); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -631,7 +858,7 @@ func (s msgServer) BurnNFT(c context.Context, req *collection.MsgBurnNFT) (*coll } ctx.EventManager().EmitEvents(collection.NewEventBurnNFT(event)) - burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, sdk.AccAddress(req.From), coins) + burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, fromAddr, coins) if err != nil { return nil, err } @@ -647,11 +874,22 @@ func (s msgServer) BurnNFT(c context.Context, req *collection.MsgBurnNFT) (*coll func (s msgServer) BurnNFTFrom(c context.Context, req *collection.MsgBurnNFTFrom) (*collection.MsgBurnNFTFromResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Proxy)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, proxyAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - if _, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Proxy), collection.PermissionBurn); err != nil { + if _, err := s.keeper.GetGrant(ctx, req.ContractId, proxyAddr, collection.PermissionBurn); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -669,7 +907,7 @@ func (s msgServer) BurnNFTFrom(c context.Context, req *collection.MsgBurnNFTFrom } ctx.EventManager().EmitEvents(collection.NewEventBurnNFTFrom(event)) - burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, sdk.AccAddress(req.From), coins) + burnt, err := s.keeper.BurnCoins(ctx, req.ContractId, fromAddr, coins) if err != nil { return nil, err } @@ -686,7 +924,11 @@ func (s msgServer) BurnNFTFrom(c context.Context, req *collection.MsgBurnNFTFrom func (s msgServer) ModifyContract(c context.Context, req *collection.MsgModifyContract) (*collection.MsgModifyContractResponse, error) { ctx := sdk.UnwrapSDKContext(c) - operator := sdk.AccAddress(req.Operator) + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + if _, err := s.keeper.GetGrant(ctx, req.ContractId, operator, collection.PermissionModify); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -711,7 +953,11 @@ func (s msgServer) ModifyContract(c context.Context, req *collection.MsgModifyCo func (s msgServer) ModifyTokenClass(c context.Context, req *collection.MsgModifyTokenClass) (*collection.MsgModifyTokenClassResponse, error) { ctx := sdk.UnwrapSDKContext(c) - operator := sdk.AccAddress(req.Operator) + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + if _, err := s.keeper.GetGrant(ctx, req.ContractId, operator, collection.PermissionModify); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -746,7 +992,11 @@ func (s msgServer) ModifyTokenClass(c context.Context, req *collection.MsgModify func (s msgServer) ModifyNFT(c context.Context, req *collection.MsgModifyNFT) (*collection.MsgModifyNFTResponse, error) { ctx := sdk.UnwrapSDKContext(c) - operator := sdk.AccAddress(req.Operator) + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + if _, err := s.keeper.GetGrant(ctx, req.ContractId, operator, collection.PermissionModify); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -772,7 +1022,11 @@ func (s msgServer) ModifyNFT(c context.Context, req *collection.MsgModifyNFT) (* func (s msgServer) Modify(c context.Context, req *collection.MsgModify) (*collection.MsgModifyResponse, error) { ctx := sdk.UnwrapSDKContext(c) - operator := sdk.AccAddress(req.Owner) + operator, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, err + } + if _, err := s.keeper.GetGrant(ctx, req.ContractId, operator, collection.PermissionModify); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -861,8 +1115,15 @@ func (s msgServer) Modify(c context.Context, req *collection.MsgModify) (*collec func (s msgServer) Grant(c context.Context, req *collection.MsgGrant) (*collection.MsgGrantResponse, error) { ctx := sdk.UnwrapSDKContext(c) - granter := sdk.AccAddress(req.Granter) - grantee := sdk.AccAddress(req.Grantee) + granter, err := sdk.AccAddressFromBech32(req.Granter) + if err != nil { + return nil, err + } + + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, err + } if _, err := s.keeper.GetGrant(ctx, req.ContractId, granter, req.Permission); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrapf("%s is not authorized for %s", granter, req.Permission) @@ -888,7 +1149,10 @@ func (s msgServer) Grant(c context.Context, req *collection.MsgGrant) (*collecti func (s msgServer) Abandon(c context.Context, req *collection.MsgAbandon) (*collection.MsgAbandonResponse, error) { ctx := sdk.UnwrapSDKContext(c) - grantee := sdk.AccAddress(req.Grantee) + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, err + } if _, err := s.keeper.GetGrant(ctx, req.ContractId, grantee, req.Permission); err != nil { return nil, sdkerrors.ErrNotFound.Wrapf("%s is not authorized for %s", grantee, req.Permission) @@ -910,8 +1174,16 @@ func (s msgServer) Abandon(c context.Context, req *collection.MsgAbandon) (*coll func (s msgServer) GrantPermission(c context.Context, req *collection.MsgGrantPermission) (*collection.MsgGrantPermissionResponse, error) { ctx := sdk.UnwrapSDKContext(c) - granter := sdk.AccAddress(req.From) - grantee := sdk.AccAddress(req.To) + granter, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + grantee, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + permission := collection.Permission(collection.LegacyPermissionFromString(req.Permission)) if _, err := s.keeper.GetGrant(ctx, req.ContractId, granter, permission); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrapf("%s is not authorized for %s", granter, permission) @@ -937,7 +1209,11 @@ func (s msgServer) GrantPermission(c context.Context, req *collection.MsgGrantPe func (s msgServer) RevokePermission(c context.Context, req *collection.MsgRevokePermission) (*collection.MsgRevokePermissionResponse, error) { ctx := sdk.UnwrapSDKContext(c) - grantee := sdk.AccAddress(req.From) + grantee, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + permission := collection.Permission(collection.LegacyPermissionFromString(req.Permission)) if _, err := s.keeper.GetGrant(ctx, req.ContractId, grantee, permission); err != nil { return nil, sdkerrors.ErrNotFound.Wrapf("%s is not authorized for %s", grantee, permission) @@ -972,7 +1248,12 @@ func (s msgServer) Attach(c context.Context, req *collection.MsgAttach) (*collec panic(err) } - if err := s.keeper.Attach(ctx, req.ContractId, sdk.AccAddress(req.From), req.TokenId, req.ToTokenId); err != nil { + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + if err := s.keeper.Attach(ctx, req.ContractId, fromAddr, req.TokenId, req.ToTokenId); err != nil { return nil, err } @@ -999,7 +1280,12 @@ func (s msgServer) Detach(c context.Context, req *collection.MsgDetach) (*collec panic(err) } - if err := s.keeper.Detach(ctx, req.ContractId, sdk.AccAddress(req.From), req.TokenId); err != nil { + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + if err := s.keeper.Detach(ctx, req.ContractId, fromAddr, req.TokenId); err != nil { return nil, err } @@ -1008,7 +1294,18 @@ func (s msgServer) Detach(c context.Context, req *collection.MsgDetach) (*collec func (s msgServer) OperatorAttach(c context.Context, req *collection.MsgOperatorAttach) (*collection.MsgOperatorAttachResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.Owner), sdk.AccAddress(req.Operator)); err != nil { + + ownerAddr, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, err + } + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, ownerAddr, operatorAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -1025,7 +1322,7 @@ func (s msgServer) OperatorAttach(c context.Context, req *collection.MsgOperator panic(err) } - if err := s.keeper.Attach(ctx, req.ContractId, sdk.AccAddress(req.Owner), req.Subject, req.Target); err != nil { + if err := s.keeper.Attach(ctx, req.ContractId, ownerAddr, req.Subject, req.Target); err != nil { return nil, err } @@ -1034,7 +1331,18 @@ func (s msgServer) OperatorAttach(c context.Context, req *collection.MsgOperator func (s msgServer) OperatorDetach(c context.Context, req *collection.MsgOperatorDetach) (*collection.MsgOperatorDetachResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.Owner), sdk.AccAddress(req.Operator)); err != nil { + + ownerAddr, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, err + } + + operatorAddr, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, ownerAddr, operatorAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -1055,7 +1363,7 @@ func (s msgServer) OperatorDetach(c context.Context, req *collection.MsgOperator panic(err) } - if err := s.keeper.Detach(ctx, req.ContractId, sdk.AccAddress(req.Owner), req.Subject); err != nil { + if err := s.keeper.Detach(ctx, req.ContractId, ownerAddr, req.Subject); err != nil { return nil, err } @@ -1064,7 +1372,18 @@ func (s msgServer) OperatorDetach(c context.Context, req *collection.MsgOperator func (s msgServer) AttachFrom(c context.Context, req *collection.MsgAttachFrom) (*collection.MsgAttachFromResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Proxy)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, proxyAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -1081,7 +1400,7 @@ func (s msgServer) AttachFrom(c context.Context, req *collection.MsgAttachFrom) panic(err) } - if err := s.keeper.Attach(ctx, req.ContractId, sdk.AccAddress(req.From), req.TokenId, req.ToTokenId); err != nil { + if err := s.keeper.Attach(ctx, req.ContractId, fromAddr, req.TokenId, req.ToTokenId); err != nil { return nil, err } @@ -1090,7 +1409,18 @@ func (s msgServer) AttachFrom(c context.Context, req *collection.MsgAttachFrom) func (s msgServer) DetachFrom(c context.Context, req *collection.MsgDetachFrom) (*collection.MsgDetachFromResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Proxy)); err != nil { + + fromAddr, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + + proxyAddr, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, err + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, fromAddr, proxyAddr); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -1111,7 +1441,7 @@ func (s msgServer) DetachFrom(c context.Context, req *collection.MsgDetachFrom) panic(err) } - if err := s.keeper.Detach(ctx, req.ContractId, sdk.AccAddress(req.From), req.TokenId); err != nil { + if err := s.keeper.Detach(ctx, req.ContractId, fromAddr, req.TokenId); err != nil { return nil, err } diff --git a/x/collection/keeper/msg_server_test.go b/x/collection/keeper/msg_server_test.go index 91aff35a02..f6abe504c4 100644 --- a/x/collection/keeper/msg_server_test.go +++ b/x/collection/keeper/msg_server_test.go @@ -559,6 +559,7 @@ func (s *KeeperTestSuite) TestMsgIssueFT() { req := &collection.MsgIssueFT{ ContractId: tc.contractID, Owner: tc.owner.String(), + To: s.customer.String(), Amount: tc.amount, } res, err := s.msgServer.IssueFT(sdk.WrapSDKContext(ctx), req) diff --git a/x/collection/keeper/nft.go b/x/collection/keeper/nft.go index c3e6d3d612..af1eadb784 100644 --- a/x/collection/keeper/nft.go +++ b/x/collection/keeper/nft.go @@ -74,7 +74,7 @@ func (k Keeper) Attach(ctx sdk.Context, contractID string, owner sdk.AccAddress, } root := k.GetRoot(ctx, contractID, target) - if owner != k.getOwner(ctx, contractID, root) { + if !owner.Equals(k.getOwner(ctx, contractID, root)) { return sdkerrors.ErrInvalidRequest.Wrapf("%s is not owner of %s", owner, target) } if root == subject { @@ -109,7 +109,7 @@ func (k Keeper) Detach(ctx sdk.Context, contractID string, owner sdk.AccAddress, return err } - if owner != k.GetRootOwner(ctx, contractID, subject) { + if !owner.Equals(k.GetRootOwner(ctx, contractID, subject)) { return sdkerrors.ErrInvalidRequest.Wrapf("%s is not owner of %s", owner, subject) } diff --git a/x/collection/keeper/send_test.go b/x/collection/keeper/send_test.go index 18b97255db..92a02805ed 100644 --- a/x/collection/keeper/send_test.go +++ b/x/collection/keeper/send_test.go @@ -58,10 +58,10 @@ func (s *KeeperTestSuite) TestAuthorizeOperator() { s.contractID: "valid", dummyContractID: "not-exists", } - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", } for id, idDesc := range contractDescriptions { for operator, operatorDesc := range userDescriptions { @@ -71,11 +71,17 @@ func (s *KeeperTestSuite) TestAuthorizeOperator() { ctx, _ := s.ctx.CacheContext() _, idErr := s.keeper.GetContract(ctx, id) - _, authErr := s.keeper.GetAuthorization(ctx, id, from, operator) - err := s.keeper.AuthorizeOperator(ctx, id, from, operator) + + fromAddr, err := sdk.AccAddressFromBech32(from) + s.Require().NoError(err) + operatorAddr, err := sdk.AccAddressFromBech32(operator) + s.Require().NoError(err) + + _, authErr := s.keeper.GetAuthorization(ctx, id, fromAddr, operatorAddr) + err = s.keeper.AuthorizeOperator(ctx, id, fromAddr, operatorAddr) if idErr == nil && authErr != nil { s.Require().NoError(err) - _, authErr = s.keeper.GetAuthorization(ctx, id, from, operator) + _, authErr = s.keeper.GetAuthorization(ctx, id, fromAddr, operatorAddr) s.Require().NoError(authErr) } else { s.Require().Error(err) @@ -96,10 +102,10 @@ func (s *KeeperTestSuite) TestRevokeOperator() { s.contractID: "valid", dummyContractID: "not-exists", } - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", } for id, idDesc := range contractDescriptions { for operator, operatorDesc := range userDescriptions { @@ -109,11 +115,17 @@ func (s *KeeperTestSuite) TestRevokeOperator() { ctx, _ := s.ctx.CacheContext() _, idErr := s.keeper.GetContract(ctx, id) - _, authErr := s.keeper.GetAuthorization(ctx, id, from, operator) - err := s.keeper.RevokeOperator(ctx, id, from, operator) + + fromAddr, err := sdk.AccAddressFromBech32(from) + s.Require().NoError(err) + operatorAddr, err := sdk.AccAddressFromBech32(operator) + s.Require().NoError(err) + + _, authErr := s.keeper.GetAuthorization(ctx, id, fromAddr, operatorAddr) + err = s.keeper.RevokeOperator(ctx, id, fromAddr, operatorAddr) if idErr == nil && authErr == nil { s.Require().NoError(err) - _, authErr = s.keeper.GetAuthorization(ctx, id, from, operator) + _, authErr = s.keeper.GetAuthorization(ctx, id, fromAddr, operatorAddr) s.Require().Error(authErr) } else { s.Require().Error(err) diff --git a/x/collection/keeper/supply.go b/x/collection/keeper/supply.go index 80880c91c3..366c9e6422 100644 --- a/x/collection/keeper/supply.go +++ b/x/collection/keeper/supply.go @@ -33,7 +33,7 @@ func (k Keeper) CreateContract(ctx sdk.Context, creator sdk.AccAddress, contract eventGrant.Permission = p ctx.EventManager().EmitEvent(collection.NewEventGrantPermTokenBody(eventGrant)) - k.Grant(ctx, contractID, "", creator, collection.Permission(permission)) + k.Grant(ctx, contractID, []byte{}, creator, collection.Permission(permission)) } return contractID diff --git a/x/collection/msgs.go b/x/collection/msgs.go index 920e60c0fa..535d1e0334 100644 --- a/x/collection/msgs.go +++ b/x/collection/msgs.go @@ -231,10 +231,10 @@ func (m MsgSend) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -247,7 +247,7 @@ func (m MsgSend) ValidateBasic() error { // GetSigners implements Msg func (m MsgSend) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -259,13 +259,13 @@ func (m MsgOperatorSend) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -278,7 +278,7 @@ func (m MsgOperatorSend) ValidateBasic() error { // GetSigners implements Msg func (m MsgOperatorSend) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -290,10 +290,10 @@ func (m MsgTransferFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -306,7 +306,7 @@ func (m MsgTransferFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgTransferFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -318,13 +318,13 @@ func (m MsgTransferFTFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -337,7 +337,7 @@ func (m MsgTransferFTFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgTransferFTFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } @@ -349,10 +349,10 @@ func (m MsgTransferNFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -370,7 +370,7 @@ func (m MsgTransferNFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgTransferNFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -382,13 +382,13 @@ func (m MsgTransferNFTFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -406,7 +406,7 @@ func (m MsgTransferNFTFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgTransferNFTFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } @@ -418,10 +418,10 @@ func (m MsgAuthorizeOperator) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Holder); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Holder); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", m.Holder) } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -430,7 +430,7 @@ func (m MsgAuthorizeOperator) ValidateBasic() error { // GetSigners implements Msg func (m MsgAuthorizeOperator) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Holder) + signer, _ := sdk.AccAddressFromBech32(m.Holder) return []sdk.AccAddress{signer} } @@ -442,10 +442,10 @@ func (m MsgRevokeOperator) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Holder); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Holder); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", m.Holder) } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -454,7 +454,7 @@ func (m MsgRevokeOperator) ValidateBasic() error { // GetSigners implements Msg func (m MsgRevokeOperator) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Holder) + signer, _ := sdk.AccAddressFromBech32(m.Holder) return []sdk.AccAddress{signer} } @@ -466,10 +466,10 @@ func (m MsgApprove) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Approver); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Approver); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid approver address: %s", m.Approver) } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } @@ -478,7 +478,7 @@ func (m MsgApprove) ValidateBasic() error { // GetSigners implements Msg func (m MsgApprove) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Approver) + signer, _ := sdk.AccAddressFromBech32(m.Approver) return []sdk.AccAddress{signer} } @@ -490,10 +490,10 @@ func (m MsgDisapprove) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Approver); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Approver); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid approver address: %s", m.Approver) } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } @@ -502,7 +502,7 @@ func (m MsgDisapprove) ValidateBasic() error { // GetSigners implements Msg func (m MsgDisapprove) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Approver) + signer, _ := sdk.AccAddressFromBech32(m.Approver) return []sdk.AccAddress{signer} } @@ -510,7 +510,7 @@ var _ sdk.Msg = (*MsgCreateContract)(nil) // ValidateBasic implements Msg. func (m MsgCreateContract) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", m.Owner) } @@ -531,7 +531,7 @@ func (m MsgCreateContract) ValidateBasic() error { // GetSigners implements Msg func (m MsgCreateContract) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Owner) + signer, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{signer} } @@ -543,7 +543,7 @@ func (m MsgCreateFTClass) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -563,7 +563,7 @@ func (m MsgCreateFTClass) ValidateBasic() error { return sdkerrors.ErrInvalidRequest.Wrap("supply cannot be negative") } if m.Supply.IsPositive() { - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } } @@ -573,7 +573,7 @@ func (m MsgCreateFTClass) ValidateBasic() error { // GetSigners implements Msg func (m MsgCreateFTClass) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -585,7 +585,7 @@ func (m MsgCreateNFTClass) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -602,7 +602,7 @@ func (m MsgCreateNFTClass) ValidateBasic() error { // GetSigners implements Msg func (m MsgCreateNFTClass) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -614,7 +614,7 @@ func (m MsgIssueFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", m.Owner) } @@ -633,7 +633,7 @@ func (m MsgIssueFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -647,7 +647,7 @@ func (m MsgIssueFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgIssueFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Owner) + signer, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{signer} } @@ -667,7 +667,7 @@ func (m MsgIssueNFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", m.Owner) } @@ -676,7 +676,7 @@ func (m MsgIssueNFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgIssueNFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Owner) + signer, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{signer} } @@ -688,10 +688,10 @@ func (m MsgMintFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -704,7 +704,7 @@ func (m MsgMintFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgMintFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -716,10 +716,10 @@ func (m MsgMintNFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -746,7 +746,7 @@ func (m MsgMintNFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgMintNFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -758,7 +758,7 @@ func (m MsgBurn) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -771,7 +771,7 @@ func (m MsgBurn) ValidateBasic() error { // GetSigners implements Msg func (m MsgBurn) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -783,10 +783,10 @@ func (m MsgOperatorBurn) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -799,7 +799,7 @@ func (m MsgOperatorBurn) ValidateBasic() error { // GetSigners implements Msg func (m MsgOperatorBurn) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -811,7 +811,7 @@ func (m MsgBurnFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -824,7 +824,7 @@ func (m MsgBurnFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgBurnFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -836,10 +836,10 @@ func (m MsgBurnFTFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -852,7 +852,7 @@ func (m MsgBurnFTFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgBurnFTFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } @@ -864,7 +864,7 @@ func (m MsgBurnNFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -882,7 +882,7 @@ func (m MsgBurnNFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgBurnNFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -894,10 +894,10 @@ func (m MsgBurnNFTFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -915,7 +915,7 @@ func (m MsgBurnNFTFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgBurnNFTFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } @@ -927,7 +927,7 @@ func (m MsgModifyContract) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -940,7 +940,7 @@ func (m MsgModifyContract) ValidateBasic() error { // GetSigners implements Msg func (m MsgModifyContract) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -952,7 +952,7 @@ func (m MsgModifyTokenClass) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -969,7 +969,7 @@ func (m MsgModifyTokenClass) ValidateBasic() error { // GetSigners implements Msg func (m MsgModifyTokenClass) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -981,7 +981,7 @@ func (m MsgModifyNFT) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -998,7 +998,7 @@ func (m MsgModifyNFT) ValidateBasic() error { // GetSigners implements Msg func (m MsgModifyNFT) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -1010,7 +1010,7 @@ func (m MsgModify) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", m.Owner) } @@ -1067,7 +1067,7 @@ func (m MsgModify) ValidateBasic() error { // GetSigners implements Msg func (m MsgModify) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Owner) + signer, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{signer} } @@ -1079,10 +1079,10 @@ func (m MsgGrant) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Granter); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Granter); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", m.Granter) } - if err := sdk.ValidateAccAddress(m.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Grantee); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.Grantee) } @@ -1095,7 +1095,7 @@ func (m MsgGrant) ValidateBasic() error { // GetSigners implements Msg func (m MsgGrant) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Granter) + signer, _ := sdk.AccAddressFromBech32(m.Granter) return []sdk.AccAddress{signer} } @@ -1107,7 +1107,7 @@ func (m MsgAbandon) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Grantee); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.Grantee) } @@ -1120,7 +1120,7 @@ func (m MsgAbandon) ValidateBasic() error { // GetSigners implements Msg func (m MsgAbandon) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Grantee) + signer, _ := sdk.AccAddressFromBech32(m.Grantee) return []sdk.AccAddress{signer} } @@ -1132,10 +1132,10 @@ func (m MsgGrantPermission) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -1148,7 +1148,7 @@ func (m MsgGrantPermission) ValidateBasic() error { // GetSigners implements Msg func (m MsgGrantPermission) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -1160,7 +1160,7 @@ func (m MsgRevokePermission) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -1173,7 +1173,7 @@ func (m MsgRevokePermission) ValidateBasic() error { // GetSigners implements Msg func (m MsgRevokePermission) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -1185,7 +1185,7 @@ func (m MsgAttach) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -1205,7 +1205,7 @@ func (m MsgAttach) ValidateBasic() error { // GetSigners implements Msg func (m MsgAttach) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -1217,7 +1217,7 @@ func (m MsgDetach) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -1230,7 +1230,7 @@ func (m MsgDetach) ValidateBasic() error { // GetSigners implements Msg func (m MsgDetach) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -1242,10 +1242,10 @@ func (m MsgOperatorAttach) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", m.Owner) } @@ -1265,7 +1265,7 @@ func (m MsgOperatorAttach) ValidateBasic() error { // GetSigners implements Msg func (m MsgOperatorAttach) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -1277,10 +1277,10 @@ func (m MsgOperatorDetach) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", m.Owner) } @@ -1293,7 +1293,7 @@ func (m MsgOperatorDetach) ValidateBasic() error { // GetSigners implements Msg func (m MsgOperatorDetach) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -1305,10 +1305,10 @@ func (m MsgAttachFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -1328,7 +1328,7 @@ func (m MsgAttachFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgAttachFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } @@ -1340,10 +1340,10 @@ func (m MsgDetachFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -1356,6 +1356,6 @@ func (m MsgDetachFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgDetachFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } diff --git a/x/collection/msgs_test.go b/x/collection/msgs_test.go index 1028c4a7e3..c0ef216b4f 100644 --- a/x/collection/msgs_test.go +++ b/x/collection/msgs_test.go @@ -13,7 +13,7 @@ import ( func TestMsgSend(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -87,21 +87,21 @@ func TestMsgSend(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgOperatorSend(t *testing.T) { addrs := make([]sdk.AccAddress, 3) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -166,21 +166,21 @@ func TestMsgOperatorSend(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgTransferFT(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } amount := collection.NewCoins( @@ -253,25 +253,25 @@ func TestMsgTransferFT(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - if tc.panic { require.Panics(t, func() { msg.ValidateBasic() }, name) continue } err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgTransferFTFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 3) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } amount := collection.NewCoins( @@ -338,21 +338,21 @@ func TestMsgTransferFTFrom(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) } } func TestMsgTransferNFT(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } ids := []string{collection.NewNFTID("deadbeef", 1)} @@ -407,21 +407,21 @@ func TestMsgTransferNFT(t *testing.T) { TokenIds: tc.ids, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgTransferNFTFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 3) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } ids := []string{collection.NewNFTID("deadbeef", 1)} @@ -490,21 +490,21 @@ func TestMsgTransferNFTFrom(t *testing.T) { TokenIds: tc.ids, } - require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) } } func TestMsgAuthorizeOperator(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -541,21 +541,21 @@ func TestMsgAuthorizeOperator(t *testing.T) { Operator: tc.operator.String(), } - require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) } } func TestMsgRevokeOperator(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -592,21 +592,21 @@ func TestMsgRevokeOperator(t *testing.T) { Operator: tc.operator.String(), } - require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) } } func TestMsgApprove(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -642,21 +642,21 @@ func TestMsgApprove(t *testing.T) { Proxy: tc.proxy.String(), } - require.Equal(t, []sdk.AccAddress{tc.approver}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.approver}, msg.GetSigners()) } } func TestMsgDisapprove(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -692,21 +692,21 @@ func TestMsgDisapprove(t *testing.T) { Proxy: tc.proxy.String(), } - require.Equal(t, []sdk.AccAddress{tc.approver}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.approver}, msg.GetSigners()) } } func TestMsgCreateContract(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } name := "tibetian fox" @@ -759,21 +759,21 @@ func TestMsgCreateContract(t *testing.T) { Meta: tc.meta, } - require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) } } func TestMsgIssueFT(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -882,21 +882,21 @@ func TestMsgIssueFT(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) } } func TestMsgIssueNFT(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -948,21 +948,21 @@ func TestMsgIssueNFT(t *testing.T) { Meta: tc.meta, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgCreateFTClass(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -1065,21 +1065,21 @@ func TestMsgCreateFTClass(t *testing.T) { Supply: tc.supply, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgCreateNFTClass(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -1131,21 +1131,21 @@ func TestMsgCreateNFTClass(t *testing.T) { Meta: tc.meta, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgMintFT(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } amount := collection.NewCoins( @@ -1200,21 +1200,21 @@ func TestMsgMintFT(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgMintNFT(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } params := []collection.MintNFTParam{{ @@ -1290,21 +1290,21 @@ func TestMsgMintNFT(t *testing.T) { Params: tc.params, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgBurn(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -1345,21 +1345,21 @@ func TestMsgBurn(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgOperatorBurn(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -1411,21 +1411,21 @@ func TestMsgOperatorBurn(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgBurnFT(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } amount := collection.NewCoins( @@ -1468,21 +1468,21 @@ func TestMsgBurnFT(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgBurnFTFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } amount := collection.NewCoins( @@ -1536,21 +1536,21 @@ func TestMsgBurnFTFrom(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) } } func TestMsgBurnNFT(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } ids := []string{collection.NewNFTID("deadbeef", 1)} @@ -1593,21 +1593,21 @@ func TestMsgBurnNFT(t *testing.T) { TokenIds: tc.ids, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgBurnNFTFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } ids := []string{collection.NewNFTID("deadbeef", 1)} @@ -1662,21 +1662,21 @@ func TestMsgBurnNFTFrom(t *testing.T) { TokenIds: tc.ids, } - require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) } } func TestMsgModifyContract(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -1737,21 +1737,21 @@ func TestMsgModifyContract(t *testing.T) { Changes: tc.changes, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgModifyTokenClass(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -1828,21 +1828,21 @@ func TestMsgModifyTokenClass(t *testing.T) { Changes: tc.changes, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgModifyNFT(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -1920,21 +1920,21 @@ func TestMsgModifyNFT(t *testing.T) { Changes: tc.changes, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgModify(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } changes := []collection.Change{{Field: "name", Value: "New test"}} @@ -2010,21 +2010,21 @@ func TestMsgModify(t *testing.T) { Changes: tc.changes, } - require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) } } func TestMsgGrant(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -2072,21 +2072,21 @@ func TestMsgGrant(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.granter}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.granter}, msg.GetSigners()) } } func TestMsgAbandon(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -2123,21 +2123,21 @@ func TestMsgAbandon(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) } } func TestMsgGrantPermission(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -2184,21 +2184,21 @@ func TestMsgGrantPermission(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgRevokePermission(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -2234,21 +2234,21 @@ func TestMsgRevokePermission(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgAttach(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -2307,21 +2307,21 @@ func TestMsgAttach(t *testing.T) { ToTokenId: tc.toTokenID, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgDetach(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -2360,21 +2360,21 @@ func TestMsgDetach(t *testing.T) { TokenId: tc.tokenID, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgOperatorAttach(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -2447,21 +2447,21 @@ func TestMsgOperatorAttach(t *testing.T) { Target: tc.target, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgOperatorDetach(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } contractID := "deadbeef" @@ -2511,21 +2511,21 @@ func TestMsgOperatorDetach(t *testing.T) { Subject: tc.subject, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgAttachFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } tokenIDs := []string{ @@ -2597,21 +2597,21 @@ func TestMsgAttachFrom(t *testing.T) { ToTokenId: tc.toTokenID, } - require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) } } func TestMsgDetachFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } tokenID := collection.NewNFTID("deadbeef", 1) @@ -2660,13 +2660,13 @@ func TestMsgDetachFrom(t *testing.T) { TokenId: tc.tokenID, } - require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) } } diff --git a/x/crisis/keeper/msg_server.go b/x/crisis/keeper/msg_server.go index a16a2817db..a1ee7b035d 100644 --- a/x/crisis/keeper/msg_server.go +++ b/x/crisis/keeper/msg_server.go @@ -13,7 +13,11 @@ func (k Keeper) VerifyInvariant(goCtx context.Context, msg *types.MsgVerifyInvar ctx := sdk.UnwrapSDKContext(goCtx) constantFee := sdk.NewCoins(k.GetConstantFee(ctx)) - if err := k.SendCoinsFromAccountToFeeCollector(ctx, sdk.AccAddress(msg.Sender), constantFee); err != nil { + sender, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + return nil, err + } + if err := k.SendCoinsFromAccountToFeeCollector(ctx, sender, constantFee); err != nil { return nil, err } diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index aeb1256029..c5780d3c9b 100644 --- a/x/crisis/types/msgs.go +++ b/x/crisis/types/msgs.go @@ -2,7 +2,6 @@ package types import ( sdk "github.com/line/lbm-sdk/types" - "github.com/line/lbm-sdk/types/errors" ) // ensure Msg interface compliance at compile time @@ -23,7 +22,8 @@ func (msg MsgVerifyInvariant) Type() string { return "verify_invariant" } // get the bytes for the message signer to sign on func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(msg.Sender)} + sender, _ := sdk.AccAddressFromBech32(msg.Sender) + return []sdk.AccAddress{sender} } // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant @@ -37,9 +37,6 @@ 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 111b8139f4..2ffa2af7b9 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.BytesToConsAddress(req.Header.ProposerAddress) + consAddr := sdk.ConsAddress(req.Header.ProposerAddress) k.SetPreviousProposerConsAddr(ctx, consAddr) } diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 6af6dd11e3..ed56fe16ba 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -87,14 +87,14 @@ $ %s query distribution validator-outstanding-rewards %s1lwjmdnks33xwnmfayc64ycp } queryClient := types.NewQueryClient(clientCtx) - err = sdk.ValidateValAddress(args[0]) + validatorAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } res, err := queryClient.ValidatorOutstandingRewards( cmd.Context(), - &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: args[0]}, + &types.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: validatorAddr.String()}, ) if err != nil { return err @@ -132,14 +132,14 @@ $ %s query distribution commission %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - err = sdk.ValidateValAddress(args[0]) + validatorAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } res, err := queryClient.ValidatorCommission( cmd.Context(), - &types.QueryValidatorCommissionRequest{ValidatorAddress: args[0]}, + &types.QueryValidatorCommissionRequest{ValidatorAddress: validatorAddr.String()}, ) if err != nil { return err @@ -177,7 +177,7 @@ $ %s query distribution slashes %svaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - err = sdk.ValidateValAddress(args[0]) + validatorAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } @@ -200,7 +200,7 @@ $ %s query distribution slashes %svaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj res, err := queryClient.ValidatorSlashes( cmd.Context(), &types.QueryValidatorSlashesRequest{ - ValidatorAddress: args[0], + ValidatorAddress: validatorAddr.String(), StartingHeight: startHeight, EndingHeight: endHeight, Pagination: pageReq, @@ -245,7 +245,7 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh } queryClient := types.NewQueryClient(clientCtx) - err = sdk.ValidateAccAddress(args[0]) + delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } @@ -253,14 +253,14 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh // query for rewards from a particular delegation ctx := cmd.Context() if len(args) == 2 { - err := sdk.ValidateValAddress(args[1]) + validatorAddr, err := sdk.ValAddressFromBech32(args[1]) if err != nil { return err } res, err := queryClient.DelegationRewards( ctx, - &types.QueryDelegationRewardsRequest{DelegatorAddress: args[0], ValidatorAddress: args[1]}, + &types.QueryDelegationRewardsRequest{DelegatorAddress: delegatorAddr.String(), ValidatorAddress: validatorAddr.String()}, ) if err != nil { return err @@ -271,7 +271,7 @@ $ %s query distribution rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1ggh res, err := queryClient.DelegationTotalRewards( ctx, - &types.QueryDelegationTotalRewardsRequest{DelegatorAddress: args[0]}, + &types.QueryDelegationTotalRewardsRequest{DelegatorAddress: delegatorAddr.String()}, ) if err != nil { return err diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index ce8bae5a64..c97669646a 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -98,15 +98,15 @@ $ %s tx distribution withdraw-rewards %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj return err } delAddr := clientCtx.GetFromAddress() - err = sdk.ValidateValAddress(args[0]) + valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } - msgs := []sdk.Msg{types.NewMsgWithdrawDelegatorReward(delAddr, sdk.ValAddress(args[0]))} + msgs := []sdk.Msg{types.NewMsgWithdrawDelegatorReward(delAddr, valAddr)} if commission, _ := cmd.Flags().GetBool(FlagCommission); commission { - msgs = append(msgs, types.NewMsgWithdrawValidatorCommission(sdk.ValAddress(args[0]))) + msgs = append(msgs, types.NewMsgWithdrawValidatorCommission(valAddr)) } for _, msg := range msgs { @@ -163,12 +163,12 @@ $ %[1]s tx distribution withdraw-all-rewards --from mykey // build multi-message transaction msgs := make([]sdk.Msg, 0, len(validators)) for _, valAddr := range validators { - err := sdk.ValidateValAddress(valAddr) + val, err := sdk.ValAddressFromBech32(valAddr) if err != nil { return err } - msg := types.NewMsgWithdrawDelegatorReward(delAddr, sdk.ValAddress(valAddr)) + msg := types.NewMsgWithdrawDelegatorReward(delAddr, val) if err := msg.ValidateBasic(); err != nil { return err } @@ -213,11 +213,10 @@ $ %s tx distribution set-withdraw-addr %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } delAddr := clientCtx.GetFromAddress() - err = sdk.ValidateAccAddress(args[0]) + withdrawAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } - withdrawAddr := sdk.AccAddress(args[0]) msg := types.NewMsgSetWithdrawAddress(delAddr, withdrawAddr) @@ -315,12 +314,11 @@ Where proposal.json contains: } from := clientCtx.GetFromAddress() - err = sdk.ValidateAccAddress(proposal.Recipient) + recpAddr, err := sdk.AccAddressFromBech32(proposal.Recipient) if err != nil { return err } - content := types.NewCommunityPoolSpendProposal(proposal.Title, proposal.Description, - sdk.AccAddress(proposal.Recipient), amount) + content := types.NewCommunityPoolSpendProposal(proposal.Title, proposal.Description, recpAddr, 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 0ebd639e5c..326132d57a 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -39,7 +39,7 @@ func Test_splitAndCall_NoMessages(t *testing.T) { func Test_splitAndCall_Splitting(t *testing.T) { clientCtx := client.Context{} - addr := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr := sdk.AccAddress(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 f771fba79a..51992c2e78 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) { - err := sdk.ValidateAccAddress(delAddr) + delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) if err != nil { return nil, 0, err } - err = sdk.ValidateValAddress(valAddr) + validatorAddr, err := sdk.ValAddressFromBech32(valAddr) if err != nil { return nil, 0, err } - params := types.NewQueryDelegationRewardsParams(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)) + params := types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr) 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 7011666857..76811a4ec0 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 } - err := sdk.ValidateAccAddress(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) if rest.CheckBadRequestError(w, err) { return } - msg := types.NewMsgFundCommunityPool(req.Amount, sdk.AccAddress(req.BaseReq.From)) + msg := types.NewMsgFundCommunityPool(req.Amount, fromAddr) if rest.CheckBadRequestError(w, msg.ValidateBasic()) { return } @@ -204,21 +204,19 @@ func newFundCommunityPoolHandlerFn(clientCtx client.Context) http.HandlerFunc { // Auxiliary func checkDelegatorAddressVar(w http.ResponseWriter, r *http.Request) (sdk.AccAddress, bool) { - addr := mux.Vars(r)["delegatorAddr"] - err := sdk.ValidateAccAddress(addr) + addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["delegatorAddr"]) if rest.CheckBadRequestError(w, err) { - return "", false + return nil, false } - return sdk.AccAddress(addr), true + return addr, true } func checkValidatorAddressVar(w http.ResponseWriter, r *http.Request) (sdk.ValAddress, bool) { - addr := mux.Vars(r)["validatorAddr"] - err := sdk.ValidateValAddress(addr) + addr, err := sdk.ValAddressFromBech32(mux.Vars(r)["validatorAddr"]) if rest.CheckBadRequestError(w, err) { - return "", false + return nil, false } - return sdk.ValAddress(addr), true + return addr, true } diff --git a/x/distribution/client/testutil/suite.go b/x/distribution/client/testutil/suite.go index 63b16eb441..2eea8163c3 100644 --- a/x/distribution/client/testutil/suite.go +++ b/x/distribution/client/testutil/suite.go @@ -125,7 +125,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorOutstandingRewards() { "json output", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), + sdk.ValAddress(val.Address).String(), fmt.Sprintf("--%s=json", ostcli.OutputFlag), }, false, @@ -136,7 +136,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorOutstandingRewards() { []string{ fmt.Sprintf("--%s=text", ostcli.OutputFlag), fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), + sdk.ValAddress(val.Address).String(), }, false, `rewards: @@ -188,7 +188,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorCommission() { "json output", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), + sdk.ValAddress(val.Address).String(), fmt.Sprintf("--%s=json", ostcli.OutputFlag), }, false, @@ -199,7 +199,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorCommission() { []string{ fmt.Sprintf("--%s=text", ostcli.OutputFlag), fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), + sdk.ValAddress(val.Address).String(), }, false, `commission: @@ -251,7 +251,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { "invalid start height", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), "-1", "3", + sdk.ValAddress(val.Address).String(), "-1", "3", }, true, "", @@ -260,7 +260,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { "invalid end height", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), "1", "-3", + sdk.ValAddress(val.Address).String(), "1", "-3", }, true, "", @@ -269,7 +269,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { "json output", []string{ fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), "1", "3", + sdk.ValAddress(val.Address).String(), "1", "3", fmt.Sprintf("--%s=json", ostcli.OutputFlag), }, false, @@ -280,7 +280,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { []string{ fmt.Sprintf("--%s=text", ostcli.OutputFlag), fmt.Sprintf("--%s=3", flags.FlagHeight), - val.Address.ToValAddress().String(), "1", "3", + sdk.ValAddress(val.Address).String(), "1", "3", }, false, "pagination:\n next_key: null\n total: \"0\"\nslashes: []", @@ -308,7 +308,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { func (s *IntegrationTestSuite) TestGetCmdQueryDelegatorRewards() { val := s.network.Validators[0] addr := val.Address - valAddr := addr.ToValAddress() + valAddr := sdk.ValAddress(addr) _, err := s.network.WaitForHeightWithTimeout(11, time.Minute) s.Require().NoError(err) @@ -469,7 +469,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { }, { "valid transaction", - val.Address.ToValAddress(), + sdk.ValAddress(val.Address), []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -480,7 +480,7 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { }, { "valid transaction (with commission)", - val.Address.ToValAddress(), + sdk.ValAddress(val.Address), []string{ fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go index 190e8cc269..4b1525cd7d 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -86,7 +86,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 bondedVotes { - validator := k.stakingKeeper.ValidatorByConsAddr(ctx, sdk.BytesToConsAddress(vote.Validator.Address)) + validator := k.stakingKeeper.ValidatorByConsAddr(ctx, 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 75593cdbf9..c2d3462fd2 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(addrs[0].ToValAddress(), valConsPk1, sdk.NewInt(100), true) + tstaking.CreateValidator(sdk.ValAddress(addrs[0]), valConsPk1, sdk.NewInt(100), true) val := app.StakingKeeper.Validator(ctx, valAddrs[0]) // allocate tokens @@ -186,7 +186,7 @@ func TestAllocateTokensTruncation(t *testing.T) { SignedLastBlock: true, }, } - app.DistrKeeper.AllocateTokens(ctx, 31, 31, sdk.BytesToConsAddress(valConsPk2.Address()), votes) + app.DistrKeeper.AllocateTokens(ctx, 31, 31, sdk.ConsAddress(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 49557c784a..45a1e3966b 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.BytesToConsAddress(valConsPk1.Address()) - valConsAddr2 = sdk.BytesToConsAddress(valConsPk2.Address()) + valConsAddr1 = sdk.ConsAddress(valConsPk1.Address()) + valConsAddr2 = sdk.ConsAddress(valConsPk2.Address()) distrAcc = authtypes.NewEmptyModuleAccount(types.ModuleName) ) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index b133e48e7e..7a5b6a8bac 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, valAddrs[0].ToAccAddress(), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), 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, valAddrs[0].ToAccAddress(), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), 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, valAddrs[0].ToAccAddress(), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), 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, valAddrs[0].ToAccAddress(), valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) // allocate some rewards initial := int64(20) @@ -234,8 +234,8 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // second delegation tstaking.Ctx = ctx - tstaking.Delegate(valAddrs[1].ToAccAddress(), valAddrs[0], sdk.NewInt(100)) - del2 := app.StakingKeeper.Delegation(ctx, valAddrs[1].ToAccAddress(), valAddrs[0]) + tstaking.Delegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewInt(100)) + del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), 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, valAddrs[0].ToAccAddress()), + app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), ) // 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, valAddrs[0].ToAccAddress(), valAddrs[0]) + _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), 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, valAddrs[0].ToAccAddress()), + app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), ) // 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, valAddrs[0].ToAccAddress()), + app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), ) } @@ -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, valAddrs[0].ToAccAddress(), valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), 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, valAddrs[0].ToAccAddress(), valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) // allocate some rewards initial := app.StakingKeeper.TokensFromConsensusPower(ctx, 30).ToDec() @@ -441,9 +441,9 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) // second delegation - tstaking.DelegateWithPower(valAddrs[1].ToAccAddress(), valAddrs[0], 100) + tstaking.DelegateWithPower(sdk.AccAddress(valAddrs[1]), valAddrs[0], 100) - del2 := app.StakingKeeper.Delegation(ctx, valAddrs[1].ToAccAddress(), valAddrs[0]) + del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) // end block staking.EndBlocker(ctx, app.StakingKeeper) @@ -509,7 +509,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { // fetch validator and delegation val := app.StakingKeeper.Validator(ctx, valAddrs[0]) - del1 := app.StakingKeeper.Delegation(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) // allocate some rewards app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) @@ -518,14 +518,14 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // second delegation - tstaking.Delegate(valAddrs[1].ToAccAddress(), valAddrs[0], sdk.NewInt(100)) + tstaking.Delegate(sdk.AccAddress(valAddrs[1]), 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, valAddrs[1].ToAccAddress(), valAddrs[0]) + del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) // end block staking.EndBlocker(ctx, app.StakingKeeper) @@ -537,11 +537,11 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // first delegator withdraws - _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) + _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) require.NoError(t, err) // second delegator withdraws - _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, valAddrs[1].ToAccAddress(), valAddrs[0]) + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) require.NoError(t, err) // historical count should be 3 (validator init + two delegations) @@ -576,7 +576,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // first delegator withdraws again - _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, valAddrs[0].ToAccAddress(), valAddrs[0]) + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) require.NoError(t, err) // end period diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go index 25f2fcf6ad..5f3cb16d09 100644 --- a/x/distribution/keeper/genesis.go +++ b/x/distribution/keeper/genesis.go @@ -15,43 +15,74 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data types.GenesisState) { k.SetParams(ctx, data.Params) for _, dwi := range data.DelegatorWithdrawInfos { - delegatorAddress := sdk.AccAddress(dwi.DelegatorAddress) - withdrawAddress := sdk.AccAddress(dwi.WithdrawAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(dwi.DelegatorAddress) + if err != nil { + panic(err) + } + withdrawAddress, err := sdk.AccAddressFromBech32(dwi.WithdrawAddress) + if err != nil { + panic(err) + } k.SetDelegatorWithdrawAddr(ctx, delegatorAddress, withdrawAddress) } var previousProposer sdk.ConsAddress if data.PreviousProposer != "" { - previousProposer = sdk.ConsAddress(data.PreviousProposer) + var err error + previousProposer, err = sdk.ConsAddressFromBech32(data.PreviousProposer) + if err != nil { + panic(err) + } } k.SetPreviousProposerConsAddr(ctx, previousProposer) for _, rew := range data.OutstandingRewards { - valAddr := sdk.ValAddress(rew.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(rew.ValidatorAddress) + if err != nil { + panic(err) + } k.SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: rew.OutstandingRewards}) moduleHoldings = moduleHoldings.Add(rew.OutstandingRewards...) } for _, acc := range data.ValidatorAccumulatedCommissions { - valAddr := sdk.ValAddress(acc.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(acc.ValidatorAddress) + if err != nil { + panic(err) + } k.SetValidatorAccumulatedCommission(ctx, valAddr, acc.Accumulated) } for _, his := range data.ValidatorHistoricalRewards { - valAddr := sdk.ValAddress(his.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(his.ValidatorAddress) + if err != nil { + panic(err) + } k.SetValidatorHistoricalRewards(ctx, valAddr, his.Period, his.Rewards) } for _, cur := range data.ValidatorCurrentRewards { - valAddr := sdk.ValAddress(cur.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(cur.ValidatorAddress) + if err != nil { + panic(err) + } k.SetValidatorCurrentRewards(ctx, valAddr, cur.Rewards) } for _, del := range data.DelegatorStartingInfos { - valAddr := sdk.ValAddress(del.ValidatorAddress) - delegatorAddress := sdk.AccAddress(del.DelegatorAddress) + valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) + if err != nil { + panic(err) + } + delegatorAddress, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + if err != nil { + panic(err) + } k.SetDelegatorStartingInfo(ctx, valAddr, delegatorAddress, del.StartingInfo) } for _, evt := range data.ValidatorSlashEvents { - valAddr := sdk.ValAddress(evt.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(evt.ValidatorAddress) + if err != nil { + panic(err) + } 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 626fa821b0..cc26dd554e 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) - err := sdk.ValidateValAddress(req.ValidatorAddress) + valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) if err != nil { return nil, err } - rewards := k.GetValidatorOutstandingRewards(ctx, sdk.ValAddress(req.ValidatorAddress)) + rewards := k.GetValidatorOutstandingRewards(ctx, valAdr) return &types.QueryValidatorOutstandingRewardsResponse{Rewards: rewards}, nil } @@ -58,11 +58,11 @@ func (k Keeper) ValidatorCommission(c context.Context, req *types.QueryValidator ctx := sdk.UnwrapSDKContext(c) - err := sdk.ValidateValAddress(req.ValidatorAddress) + valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) if err != nil { return nil, err } - commission := k.GetValidatorAccumulatedCommission(ctx, sdk.ValAddress(req.ValidatorAddress)) + commission := k.GetValidatorAccumulatedCommission(ctx, valAdr) 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) - err := sdk.ValidateValAddress(req.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid validator address") } - slashesStore := prefix.NewStore(store, types.GetValidatorSlashEventPrefix(sdk.ValAddress(req.ValidatorAddress))) + slashesStore := prefix.NewStore(store, types.GetValidatorSlashEventPrefix(valAddr)) 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) - err := sdk.ValidateValAddress(req.ValidatorAddress) + valAdr, err := sdk.ValAddressFromBech32(req.ValidatorAddress) if err != nil { return nil, err } - val := k.stakingKeeper.Validator(ctx, sdk.ValAddress(req.ValidatorAddress)) + val := k.stakingKeeper.Validator(ctx, valAdr) if val == nil { return nil, sdkerrors.Wrap(types.ErrNoValidatorExists, req.ValidatorAddress) } - err = sdk.ValidateAccAddress(req.DelegatorAddress) + delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) if err != nil { return nil, err } - del := k.stakingKeeper.Delegation(ctx, sdk.AccAddress(req.DelegatorAddress), sdk.ValAddress(req.ValidatorAddress)) + del := k.stakingKeeper.Delegation(ctx, delAdr, valAdr) 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 - err := sdk.ValidateAccAddress(req.DelegatorAddress) + delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) if err != nil { return nil, err } k.stakingKeeper.IterateDelegations( - ctx, sdk.AccAddress(req.DelegatorAddress), + ctx, delAdr, 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) - err := sdk.ValidateAccAddress(req.DelegatorAddress) + delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) if err != nil { return nil, err } var validators []string k.stakingKeeper.IterateDelegations( - ctx, sdk.AccAddress(req.DelegatorAddress), + ctx, delAdr, 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") } - err := sdk.ValidateAccAddress(req.DelegatorAddress) + delAdr, err := sdk.AccAddressFromBech32(req.DelegatorAddress) if err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) - withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, sdk.AccAddress(req.DelegatorAddress)) + withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, delAdr) return &types.QueryDelegatorWithdrawAddressResponse{WithdrawAddress: withdrawAddr.String()}, nil } diff --git a/x/distribution/keeper/hooks.go b/x/distribution/keeper/hooks.go index 5185323d23..dbd97d5130 100644 --- a/x/distribution/keeper/hooks.go +++ b/x/distribution/keeper/hooks.go @@ -43,7 +43,7 @@ func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, _ sdk.ConsAddress, valAddr // add to validator account if !coins.IsZero() { - accAddr := valAddr.ToAccAddress() + accAddr := sdk.AccAddress(valAddr) withdrawAddr := h.k.GetDelegatorWithdrawAddr(ctx, accAddr) if err := h.k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, coins); err != nil { diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 5ec509ccad..130dd54097 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.Empty() { + if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { 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 := valAddr.ToAccAddress() + accAddr := sdk.AccAddress(valAddr) 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 ca2f922bba..9634f4cdbe 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -54,7 +54,7 @@ func TestWithdrawValidatorCommission(t *testing.T) { app.AccountKeeper.SetModuleAccount(ctx, distrAcc) // check initial balance - balance := app.BankKeeper.GetAllBalances(ctx, valAddrs[0].ToAccAddress()) + balance := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) expTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 1000) expCoins := sdk.NewCoins(sdk.NewCoin("stake", expTokens)) require.Equal(t, expCoins, balance) @@ -70,7 +70,7 @@ func TestWithdrawValidatorCommission(t *testing.T) { require.NoError(t, err) // check balance increase - balance = app.BankKeeper.GetAllBalances(ctx, valAddrs[0].ToAccAddress()) + balance = app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) 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 560d9955e2..c49b293ccc 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) - err := sdk.ValidateAccAddress(msg.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) if err != nil { return nil, err } - err = sdk.ValidateAccAddress(msg.WithdrawAddress) + withdrawAddress, err := sdk.AccAddressFromBech32(msg.WithdrawAddress) if err != nil { return nil, err } - err = k.SetWithdrawAddr(ctx, sdk.AccAddress(msg.DelegatorAddress), sdk.AccAddress(msg.WithdrawAddress)) + err = k.SetWithdrawAddr(ctx, delegatorAddress, withdrawAddress) if err != nil { return nil, err } @@ -52,16 +52,15 @@ 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) - err := sdk.ValidateValAddress(msg.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { return nil, err } - err = sdk.ValidateAccAddress(msg.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) if err != nil { return nil, err } - amount, err := k.WithdrawDelegationRewards(ctx, sdk.AccAddress(msg.DelegatorAddress), - sdk.ValAddress(msg.ValidatorAddress)) + amount, err := k.WithdrawDelegationRewards(ctx, delegatorAddress, valAddr) if err != nil { return nil, err } @@ -91,11 +90,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) - err := sdk.ValidateValAddress(msg.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { return nil, err } - amount, err := k.Keeper.WithdrawValidatorCommission(ctx, sdk.ValAddress(msg.ValidatorAddress)) + amount, err := k.Keeper.WithdrawValidatorCommission(ctx, valAddr) if err != nil { return nil, err } @@ -126,11 +125,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) - err := sdk.ValidateAccAddress(msg.Depositor) + depositer, err := sdk.AccAddressFromBech32(msg.Depositor) if err != nil { return nil, err } - if err := k.Keeper.FundCommunityPool(ctx, msg.Amount, sdk.AccAddress(msg.Depositor)); err != nil { + if err := k.Keeper.FundCommunityPool(ctx, msg.Amount, depositer); err != nil { return nil, err } diff --git a/x/distribution/keeper/proposal_handler.go b/x/distribution/keeper/proposal_handler.go index 30e4da452e..b84a3a1f35 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) } - addrErr := sdk.ValidateAccAddress(p.Recipient) + recipient, addrErr := sdk.AccAddressFromBech32(p.Recipient) if addrErr != nil { return addrErr } - err := k.DistributeFromFeePool(ctx, p.Amount, sdk.AccAddress(p.Recipient)) + err := k.DistributeFromFeePool(ctx, p.Amount, recipient) if err != nil { return err } diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index 5283c7e4a9..72f2a5dbcc 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, valOpAddr1.ToAccAddress()) + delRewards := getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1)) 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, valOpAddr1.ToAccAddress(), valOpAddr1) + rewards := getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), 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, valOpAddr1.ToAccAddress(), valOpAddr1) + rewards = getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), 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, valOpAddr1.ToAccAddress()) + delRewards = getQueriedDelegatorTotalRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1)) 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 0c065985a0..4fac33a3c6 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.MustUnmarshal(bz, &addrValue) - return sdk.ConsAddress(addrValue.GetValue()) + return 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.MustMarshal(&gogotypes.BytesValue{Value: consAddr.Bytes()}) + bz := k.cdc.MustMarshal(&gogotypes.BytesValue{Value: consAddr}) store.Set(types.ProposerKey, bz) } diff --git a/x/distribution/legacy/v043/helpers.go b/x/distribution/legacy/v043/helpers.go index cd1b098b0b..17806ad72f 100644 --- a/x/distribution/legacy/v043/helpers.go +++ b/x/distribution/legacy/v043/helpers.go @@ -69,24 +69,3 @@ func MigratePrefixAddressAddress(store sdk.KVStore, prefixBz []byte) { oldStore.Delete(oldStoreIter.Key()) } } - -// MigratePrefixValAddressAddress is a helper function that migrates all keys of format: -// prefix_bytes | val_address_bytes | address_bytes -// into format: -// prefix_bytes | val_address_len (1 byte) | val_address_bytes | address_len (1 byte) | address_bytes -func MigratePrefixValAddressAddress(store sdk.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr1 := oldStoreIter.Key()[:v040auth.ValAddrLen] - addr2 := oldStoreIter.Key()[v040auth.ValAddrLen:] - newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} diff --git a/x/distribution/proposal_handler_test.go b/x/distribution/proposal_handler_test.go index e33578da37..1f0d486170 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.BytesToAccAddress(delPk1.Address()) + delAddr1 = sdk.AccAddress(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 6ba7ec0861..ea4e5bcbeb 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.BytesToAccAddress(delPk1.Address()) - valAddr1 = sdk.BytesToValAddress(delPk1.Address()) - consAddr1 = sdk.BytesToConsAddress(delPk1.Address()) + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) + consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) ) func TestDecodeDistributionStore(t *testing.T) { diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index f8f84f7c61..0d42f9bc65 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -172,7 +172,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, validator.GetOperator().ToAccAddress()) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) 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 e6f1dcae06..1f3571fa61 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -244,7 +244,7 @@ func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, comm require := suite.Require() account := accounts[n] valPubKey := account.PubKey - valAddr := sdk.BytesToValAddress(account.PubKey.Address()) + valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) 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 2bf4b5dbec..fe5db0a78c 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.BytesToAccAddress(delPk1.Address()) - delAddr2 = sdk.BytesToAccAddress(delPk2.Address()) - delAddr3 = sdk.BytesToAccAddress(delPk3.Address()) + delAddr1 = sdk.AccAddress(delPk1.Address()) + delAddr2 = sdk.AccAddress(delPk2.Address()) + delAddr3 = sdk.AccAddress(delPk3.Address()) emptyDelAddr sdk.AccAddress valPk1 = ed25519.GenPrivKey().PubKey() valPk2 = ed25519.GenPrivKey().PubKey() valPk3 = ed25519.GenPrivKey().PubKey() - valAddr1 = sdk.BytesToValAddress(valPk1.Address()) - valAddr2 = sdk.BytesToValAddress(valPk2.Address()) - valAddr3 = sdk.BytesToValAddress(valPk3.Address()) + valAddr1 = sdk.ValAddress(valPk1.Address()) + valAddr2 = sdk.ValAddress(valPk2.Address()) + valAddr3 = sdk.ValAddress(valPk3.Address()) emptyValAddr sdk.ValAddress emptyPubkey cryptotypes.PubKey diff --git a/x/distribution/types/keys.go b/x/distribution/types/keys.go index 9da16763bf..861ba6f6aa 100644 --- a/x/distribution/types/keys.go +++ b/x/distribution/types/keys.go @@ -52,8 +52,6 @@ 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 = "," ) // GetValidatorOutstandingRewardsAddress creates an address from a validator's outstanding rewards key. @@ -146,7 +144,7 @@ func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, he // key is in the format: // 0x08: ValidatorSlashEvent valAddrLen := int(key[1]) - valAddr = sdk.ValAddress(key[2 : 2+valAddrLen]) + valAddr = key[2 : 2+valAddrLen] startB := 2 + valAddrLen b := key[startB : startB+8] // the next 8 bytes represent the height height = binary.BigEndian.Uint64(b) diff --git a/x/distribution/types/msg.go b/x/distribution/types/msg.go index f63617c3ab..3b80735905 100644 --- a/x/distribution/types/msg.go +++ b/x/distribution/types/msg.go @@ -28,7 +28,11 @@ func (msg MsgSetWithdrawAddress) Type() string { return TypeMsgSetWithdrawAddre // Return address that must sign over msg.GetSignBytes() func (msg MsgSetWithdrawAddress) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{delAddr} } // get the bytes for the message signer to sign on @@ -45,12 +49,7 @@ 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,7 +65,10 @@ func (msg MsgWithdrawDelegatorReward) Type() string { return TypeMsgWithdrawDel // Return address that must sign over msg.GetSignBytes() func (msg MsgWithdrawDelegatorReward) GetSigners() []sdk.AccAddress { - delAddr := sdk.AccAddress(msg.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + if err != nil { + panic(err) + } return []sdk.AccAddress{delAddr} } @@ -84,12 +86,6 @@ 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 } @@ -104,11 +100,11 @@ func (msg MsgWithdrawValidatorCommission) Type() string { return TypeMsgWithdra // Return address that must sign over msg.GetSignBytes() func (msg MsgWithdrawValidatorCommission) GetSigners() []sdk.AccAddress { - valAddrBytes, err := sdk.ValAddressToBytes(msg.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{sdk.BytesToAccAddress(valAddrBytes)} + return []sdk.AccAddress{valAddr.Bytes()} } // get the bytes for the message signer to sign on @@ -122,9 +118,6 @@ 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 } @@ -146,7 +139,10 @@ 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 := sdk.AccAddress(msg.Depositor) + depoAddr, err := sdk.AccAddressFromBech32(msg.Depositor) + if err != nil { + panic(err) + } return []sdk.AccAddress{depoAddr} } @@ -165,9 +161,6 @@ 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 89500f5e91..9972cf67e9 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)), "", false}, + {sdk.NewCoins(sdk.NewInt64Coin("uatom", 10000)), sdk.AccAddress{}, 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 6c674307d6..7f8e804658 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() - consAddrBytes, _ := sdk.ConsAddressToBytes(consAddr.String()) - if _, err := k.slashingKeeper.GetPubkey(ctx, consAddrBytes); err != nil { + + if _, err := k.slashingKeeper.GetPubkey(ctx, consAddr.Bytes()); 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 4ae2c78c4f..67a13edb57 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, operatorAddr.ToAccAddress()).String(), + suite.app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(operatorAddr)).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.BytesToConsAddress(val.Address()).String(), + ConsensusAddress: sdk.ConsAddress(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.BytesToConsAddress(val.Address()))) + suite.True(suite.app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(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, operatorAddr.ToAccAddress(), operatorAddr) + del, _ := suite.app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(operatorAddr), operatorAddr) validator, _ := suite.app.StakingKeeper.GetValidator(ctx, operatorAddr) totalBond := validator.TokensFromShares(del.GetShares()).TruncateInt() tstaking.Ctx = ctx tstaking.Denom = stakingParams.BondDenom - tstaking.Undelegate(operatorAddr.ToAccAddress(), operatorAddr, totalBond, true) + tstaking.Undelegate(sdk.AccAddress(operatorAddr), operatorAddr, totalBond, true) // query evidence from store evidences := suite.app.EvidenceKeeper.GetAllEvidence(ctx) @@ -89,7 +89,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, operatorAddr.ToAccAddress()), + suite.app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(operatorAddr)), sdk.NewCoins(sdk.NewCoin(stakingParams.BondDenom, initAmt.Sub(amt))), ) suite.Equal(amt, suite.app.StakingKeeper.Validator(ctx, operatorAddr).GetBondedTokens()) @@ -98,7 +98,7 @@ func (suite *KeeperTestSuite) TestHandleDoubleSign_TooOld() { Height: 0, Time: ctx.BlockTime(), Power: power, - ConsensusAddress: sdk.BytesToConsAddress(val.Address()).String(), + ConsensusAddress: sdk.ConsAddress(val.Address()).String(), } cp := suite.app.BaseApp.GetConsensusParams(ctx) @@ -109,5 +109,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.BytesToConsAddress(val.Address()))) + suite.False(suite.app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(val.Address()))) } diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index b789cb1d4b..b88936dbc2 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -29,9 +29,9 @@ var ( } valAddresses = []sdk.ValAddress{ - sdk.BytesToValAddress(pubkeys[0].Address()), - sdk.BytesToValAddress(pubkeys[1].Address()), - sdk.BytesToValAddress(pubkeys[2].Address()), + sdk.ValAddress(pubkeys[0].Address()), + sdk.ValAddress(pubkeys[1].Address()), + sdk.ValAddress(pubkeys[2].Address()), } // The default power validators are initialized to have within tests @@ -98,7 +98,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.app = app for i, addr := range valAddresses { - addr := addr.ToAccAddress() + addr := sdk.AccAddress(addr) app.AccountKeeper.SetAccount(suite.ctx, authtypes.NewBaseAccount(addr, pubkeys[i], uint64(i), 0)) } @@ -118,7 +118,7 @@ func (suite *KeeperTestSuite) populateEvidence(ctx sdk.Context, numEvidence int) Height: 11, Power: 100, Time: time.Now().UTC(), - ConsensusAddress: sdk.BytesToConsAddress(pk.PubKey().Address()).String(), + ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).String(), } suite.Nil(suite.app.EvidenceKeeper.SubmitEvidence(ctx, evidence[i])) @@ -134,7 +134,7 @@ func (suite *KeeperTestSuite) populateValidators(ctx sdk.Context) { suite.NoError(suite.app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, totalSupply)) for _, addr := range valAddresses { - suite.NoError(suite.app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr.ToAccAddress(), initCoins)) + suite.NoError(suite.app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, (sdk.AccAddress)(addr), initCoins)) } } @@ -146,7 +146,7 @@ func (suite *KeeperTestSuite) TestSubmitValidEvidence() { Height: 1, Power: 100, Time: time.Now().UTC(), - ConsensusAddress: sdk.BytesToConsAddress(pk.PubKey().Address()).String(), + ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).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.BytesToConsAddress(pk.PubKey().Address()).String(), + ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).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.BytesToConsAddress(pk.PubKey().Address()).String(), + ConsensusAddress: sdk.ConsAddress(pk.PubKey().Address().Bytes()).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 b88ecd3c9b..694664061f 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.BytesToConsAddress(delPk1.Address()).String(), + ConsensusAddress: sdk.ConsAddress(delPk1.Address()).String(), } evBz, err := app.EvidenceKeeper.MarshalEvidence(ev) diff --git a/x/evidence/types/evidence.go b/x/evidence/types/evidence.go index 709826734e..40c1cf1357 100644 --- a/x/evidence/types/evidence.go +++ b/x/evidence/types/evidence.go @@ -62,7 +62,8 @@ func (e *Equivocation) ValidateBasic() error { // GetConsensusAddress returns the validator's consensus address at time of the // Equivocation infraction. func (e Equivocation) GetConsensusAddress() sdk.ConsAddress { - return sdk.ConsAddress(e.ConsensusAddress) + addr, _ := sdk.ConsAddressFromBech32(e.ConsensusAddress) + return addr } // 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 894953d05b..a1fc8977d7 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.BytesToConsAddress([]byte("foo_________________")) + addr := sdk.ConsAddress("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.BytesToConsAddress([]byte("foo_________________")) + addr := sdk.ConsAddress("foo_________________") n, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") testCases := []struct { @@ -74,7 +74,6 @@ func TestEvidenceAddressConversion(t *testing.T) { evidence := types.FromABCIEvidence(tmEvidence).(*types.Equivocation) consAddr := evidence.GetConsensusAddress() // Check the address is the same after conversion - consAddrBytes, _ := sdk.ConsAddressToBytes(consAddr.String()) - require.Equal(t, tmEvidence.Validator.Address, consAddrBytes) + require.Equal(t, tmEvidence.Validator.Address, consAddr.Bytes()) sdk.GetConfig().SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) } diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index e7f320a308..fee9a43197 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -47,9 +47,6 @@ 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 { @@ -70,7 +67,12 @@ func (m MsgSubmitEvidence) GetSignBytes() []byte { // GetSigners returns the single expected signer for a MsgSubmitEvidence. func (m MsgSubmitEvidence) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(m.Submitter)} + accAddr, err := sdk.AccAddressFromBech32(m.Submitter) + if err != nil { + return nil + } + + return []sdk.AccAddress{accAddr} } func (m MsgSubmitEvidence) GetEvidence() exported.Evidence { @@ -82,7 +84,11 @@ func (m MsgSubmitEvidence) GetEvidence() exported.Evidence { } func (m MsgSubmitEvidence) GetSubmitter() sdk.AccAddress { - return sdk.AccAddress(m.Submitter) + accAddr, err := sdk.AccAddressFromBech32(m.Submitter) + if err != nil { + return nil + } + return accAddr } 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 60b2da4c76..bc5d1f3a5f 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.BytesToAccAddress([]byte("test________________")) + submitter := sdk.AccAddress("test________________") testCases := []struct { msg sdk.Msg diff --git a/x/feegrant/client/cli/query.go b/x/feegrant/client/cli/query.go index 44eb1ab99b..81f4af5974 100644 --- a/x/feegrant/client/cli/query.go +++ b/x/feegrant/client/cli/query.go @@ -49,17 +49,15 @@ $ %s query feegrant grant [granter] [grantee] clientCtx := client.GetClientContextFromCmd(cmd) queryClient := feegrant.NewQueryClient(clientCtx) - err := sdk.ValidateAccAddress(args[0]) + granterAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } - granterAddr := sdk.AccAddress(args[0]) - err = sdk.ValidateAccAddress(args[1]) + granteeAddr, err := sdk.AccAddressFromBech32(args[1]) if err != nil { return err } - granteeAddr := sdk.AccAddress(args[1]) res, err := queryClient.Allowance( cmd.Context(), @@ -99,11 +97,10 @@ $ %s query feegrant grants [grantee] clientCtx := client.GetClientContextFromCmd(cmd) queryClient := feegrant.NewQueryClient(clientCtx) - err := sdk.ValidateAccAddress(args[0]) + granteeAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } - granteeAddr := sdk.AccAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { diff --git a/x/feegrant/client/cli/tx.go b/x/feegrant/client/cli/tx.go index 0858b171d0..2440cc0866 100644 --- a/x/feegrant/client/cli/tx.go +++ b/x/feegrant/client/cli/tx.go @@ -70,11 +70,10 @@ Examples: return err } - err = sdk.ValidateAccAddress(args[1]) + grantee, err := sdk.AccAddressFromBech32(args[1]) if err != nil { return err } - grantee := sdk.AccAddress(args[1]) granter := clientCtx.GetFromAddress() sl, err := cmd.Flags().GetString(FlagSpendLimit) @@ -202,11 +201,10 @@ Example: return err } - err = sdk.ValidateAccAddress(args[1]) + grantee, err := sdk.AccAddressFromBech32(args[1]) if err != nil { return err } - grantee := sdk.AccAddress(args[1]) msg := feegrant.NewMsgRevokeAllowance(clientCtx.GetFromAddress(), grantee) diff --git a/x/feegrant/client/testutil/suite.go b/x/feegrant/client/testutil/suite.go index 0ad6ea733f..92bd533b75 100644 --- a/x/feegrant/client/testutil/suite.go +++ b/x/feegrant/client/testutil/suite.go @@ -52,10 +52,9 @@ func (s *IntegrationTestSuite) SetupSuite() { s.T().Skip("skipping test in unit-tests mode.") } - var err error s.network = network.New(s.T(), s.cfg) - _, err = s.network.WaitForHeight(1) + _, err := s.network.WaitForHeight(1) s.Require().NoError(err) val := s.network.Validators[0] @@ -561,7 +560,8 @@ func (s *IntegrationTestSuite) TestNewCmdRevokeFeegrant() { } // Create new fee grant specifically to test amino. - aminoGrantee := sdk.AccAddress("link1zp4lzwuwzvhq7xhe8xj688vv00dxv2zyue4xuj") + aminoGrantee, err := sdk.AccAddressFromBech32("link1zp4lzwuwzvhq7xhe8xj688vv00dxv2zyue4xuj") + s.Require().NoError(err) s.createGrant(granter, aminoGrantee) testCases := []struct { @@ -660,10 +660,9 @@ func (s *IntegrationTestSuite) TestTxWithFeeGrant() { granter := val.Address // creating an account manually (This account won't be exist in state) - k, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) + info, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) - pub := k.GetPubKey() - grantee := sdk.BytesToAccAddress(pub.Address()) + grantee := sdk.AccAddress(info.GetPubKey().Address()) commonFlags := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), @@ -708,10 +707,9 @@ func (s *IntegrationTestSuite) TestFilteredFeeAllowance() { val := s.network.Validators[0] granter := val.Address - k, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee1", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) + info, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee1", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) - pub := k.GetPubKey() - grantee := sdk.BytesToAccAddress(pub.Address()) + grantee := sdk.AccAddress(info.GetPubKey().Address()) clientCtx := val.ClientCtx diff --git a/x/feegrant/filtered_fee_test.go b/x/feegrant/filtered_fee_test.go index dcf2b40127..6aee743a44 100644 --- a/x/feegrant/filtered_fee_test.go +++ b/x/feegrant/filtered_fee_test.go @@ -160,10 +160,12 @@ func TestFilteredFeeValidAllow(t *testing.T) { // however, the saved value was not. // so we need this to catch the bug. + newGranter, _ := sdk.AccAddressFromBech32(grant.Granter) + newGrantee, _ := sdk.AccAddressFromBech32(grant.Grantee) // create a new updated grant newGrant, err := feegrant.NewGrant( - sdk.AccAddress(grant.Granter), - sdk.AccAddress(grant.Grantee), + newGranter, + newGrantee, allowance) require.NoError(t, err) diff --git a/x/feegrant/grant_test.go b/x/feegrant/grant_test.go index d28130a4d4..dca4e1b0f6 100644 --- a/x/feegrant/grant_test.go +++ b/x/feegrant/grant_test.go @@ -15,8 +15,10 @@ import ( func TestGrant(t *testing.T) { app := simapp.Setup(false) - addr := sdk.AccAddress("link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5") - addr2 := sdk.AccAddress("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") + addr, err := sdk.AccAddressFromBech32("link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5") + require.NoError(t, err) + addr2, err := sdk.AccAddressFromBech32("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") + require.NoError(t, err) atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) ctx := app.BaseApp.NewContext(false, ocproto.Header{ Time: time.Now(), @@ -43,13 +45,13 @@ func TestGrant(t *testing.T) { }, "no grantee": { granter: addr2, - grantee: "", + grantee: nil, limit: atom, expires: oneYear, valid: false, }, "no granter": { - granter: "", + granter: nil, grantee: addr, limit: atom, expires: oneYear, diff --git a/x/feegrant/keeper/genesis_test.go b/x/feegrant/keeper/genesis_test.go index df17ca1c65..e0a595b8b6 100644 --- a/x/feegrant/keeper/genesis_test.go +++ b/x/feegrant/keeper/genesis_test.go @@ -32,8 +32,8 @@ func (suite *GenesisTestSuite) SetupTest() { var ( granteePub = secp256k1.GenPrivKey().PubKey() granterPub = secp256k1.GenPrivKey().PubKey() - granteeAddr = sdk.BytesToAccAddress(granteePub.Address()) - granterAddr = sdk.BytesToAccAddress(granterPub.Address()) + granteeAddr = sdk.AccAddress(granteePub.Address()) + granterAddr = sdk.AccAddress(granterPub.Address()) ) func (suite *GenesisTestSuite) TestImportExportGenesis() { diff --git a/x/feegrant/keeper/grpc_query.go b/x/feegrant/keeper/grpc_query.go index e484e40598..ca7b9a50e6 100644 --- a/x/feegrant/keeper/grpc_query.go +++ b/x/feegrant/keeper/grpc_query.go @@ -22,8 +22,15 @@ func (q Keeper) Allowance(c context.Context, req *feegrant.QueryAllowanceRequest return nil, status.Error(codes.InvalidArgument, "invalid request") } - granterAddr := sdk.AccAddress(req.Granter) - granteeAddr := sdk.AccAddress(req.Grantee) + granterAddr, err := sdk.AccAddressFromBech32(req.Granter) + if err != nil { + return nil, err + } + + granteeAddr, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, err + } ctx := sdk.UnwrapSDKContext(c) @@ -57,11 +64,10 @@ func (q Keeper) Allowances(c context.Context, req *feegrant.QueryAllowancesReque return nil, status.Error(codes.InvalidArgument, "invalid request") } - err := sdk.ValidateAccAddress(req.Grantee) + granteeAddr, err := sdk.AccAddressFromBech32(req.Grantee) if err != nil { return nil, err } - granteeAddr := sdk.AccAddress(req.Grantee) ctx := sdk.UnwrapSDKContext(c) diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index c553371604..593f767a7f 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -192,16 +192,14 @@ func emitUseGrantEvent(ctx sdk.Context, granter, grantee string) { // InitGenesis will initialize the keeper from a *previously validated* GenesisState func (k Keeper) InitGenesis(ctx sdk.Context, data *feegrant.GenesisState) error { for _, f := range data.Allowances { - err := sdk.ValidateAccAddress(f.Granter) + granter, err := sdk.AccAddressFromBech32(f.Granter) if err != nil { return err } - granter := sdk.AccAddress(f.Granter) - err = sdk.ValidateAccAddress(f.Grantee) + grantee, err := sdk.AccAddressFromBech32(f.Grantee) if err != nil { return err } - grantee := sdk.AccAddress(f.Grantee) grant, err := f.GetGrant() if err != nil { diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index 39da4f20ea..69e7f8d2d3 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -133,7 +133,7 @@ func (suite *KeeperTestSuite) TestKeeperCrud() { suite.Equal(tc.allowance, allow) }) } - accAddr := sdk.AccAddress("link1k907plrxssuh2dxsd8k2jtp3de2t4xyhq6rkxd") + accAddr, err := sdk.AccAddressFromBech32("link1k907plrxssuh2dxsd8k2jtp3de2t4xyhq6rkxd") suite.Require().NoError(err) // let's grant and revoke authorization to non existing account diff --git a/x/feegrant/keeper/msg_server.go b/x/feegrant/keeper/msg_server.go index c280cf7786..83c2d56c65 100644 --- a/x/feegrant/keeper/msg_server.go +++ b/x/feegrant/keeper/msg_server.go @@ -26,17 +26,15 @@ var _ feegrant.MsgServer = msgServer{} func (k msgServer) GrantAllowance(goCtx context.Context, msg *feegrant.MsgGrantAllowance) (*feegrant.MsgGrantAllowanceResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return nil, err } - grantee := sdk.AccAddress(msg.Grantee) - err = sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { return nil, err } - granter := sdk.AccAddress(msg.Granter) // Checking for duplicate entry if f, _ := k.Keeper.GetAllowance(ctx, granter, grantee); f != nil { @@ -60,17 +58,15 @@ func (k msgServer) GrantAllowance(goCtx context.Context, msg *feegrant.MsgGrantA func (k msgServer) RevokeAllowance(goCtx context.Context, msg *feegrant.MsgRevokeAllowance) (*feegrant.MsgRevokeAllowanceResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Grantee) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) if err != nil { return nil, err } - grantee := sdk.AccAddress(msg.Grantee) - err = sdk.ValidateAccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) if err != nil { return nil, err } - granter := sdk.AccAddress(msg.Granter) err = k.Keeper.revokeAllowance(ctx, granter, grantee) if err != nil { diff --git a/x/feegrant/msgs.go b/x/feegrant/msgs.go index 0ba7a09202..bbbcdcf678 100644 --- a/x/feegrant/msgs.go +++ b/x/feegrant/msgs.go @@ -38,15 +38,16 @@ func NewMsgGrantAllowance(feeAllowance FeeAllowanceI, granter, grantee sdk.AccAd // ValidateBasic implements the sdk.Msg interface. func (msg MsgGrantAllowance) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Granter); err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid granter address: %s", err) + if msg.Granter == "" { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing granter address") } - if err := sdk.ValidateAccAddress(msg.Grantee); err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid grantee address: %s", err) + if msg.Grantee == "" { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing grantee address") } if msg.Grantee == msg.Granter { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "cannot self-grant fee authorization") } + allowance, err := msg.GetFeeAllowanceI() if err != nil { return err @@ -57,7 +58,10 @@ func (msg MsgGrantAllowance) ValidateBasic() error { // GetSigners gets the granter account associated with an allowance func (msg MsgGrantAllowance) GetSigners() []sdk.AccAddress { - granter := sdk.AccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) + if err != nil { + panic(err) + } return []sdk.AccAddress{granter} } @@ -101,14 +105,11 @@ func NewMsgRevokeAllowance(granter sdk.AccAddress, grantee sdk.AccAddress) MsgRe // ValidateBasic implements the sdk.Msg interface. func (msg MsgRevokeAllowance) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Granter); err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid granter address: %s", err) - } - if err := sdk.ValidateAccAddress(msg.Grantee); err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid grantee address: %s", err) + if msg.Granter == "" { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing granter address") } - if msg.Grantee == msg.Granter { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "addresses must be different") + if msg.Grantee == "" { + return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing grantee address") } if msg.Grantee == msg.Granter { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "addresses must be different") @@ -120,7 +121,10 @@ func (msg MsgRevokeAllowance) ValidateBasic() error { // GetSigners gets the granter address associated with an Allowance // to revoke. func (msg MsgRevokeAllowance) GetSigners() []sdk.AccAddress { - granter := sdk.AccAddress(msg.Granter) + granter, err := sdk.AccAddressFromBech32(msg.Granter) + if err != nil { + panic(err) + } return []sdk.AccAddress{granter} } diff --git a/x/feegrant/msgs_test.go b/x/feegrant/msgs_test.go index 122956a3a0..1a2e3f2c46 100644 --- a/x/feegrant/msgs_test.go +++ b/x/feegrant/msgs_test.go @@ -14,8 +14,8 @@ import ( func TestMsgGrantAllowance(t *testing.T) { cdc := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) - addr := sdk.AccAddress("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") - addr2 := sdk.AccAddress("link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu") + addr, _ := sdk.AccAddressFromBech32("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") + addr2, _ := sdk.AccAddressFromBech32("link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu") atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) threeHours := time.Now().Add(3 * time.Hour) basic := &feegrant.BasicAllowance{ @@ -37,12 +37,12 @@ func TestMsgGrantAllowance(t *testing.T) { }, "no grantee": { granter: addr2, - grantee: sdk.AccAddress(""), + grantee: sdk.AccAddress{}, grant: basic, valid: false, }, "no granter": { - granter: sdk.AccAddress(""), + granter: sdk.AccAddress{}, grantee: addr, grant: basic, valid: false, @@ -64,7 +64,7 @@ func TestMsgGrantAllowance(t *testing.T) { require.NoError(t, err) addrSlice := msg.GetSigners() - require.True(t, tc.granter.Equals(addrSlice[0])) + require.Equal(t, tc.granter.String(), addrSlice[0].String()) allowance, err := msg.GetFeeAllowanceI() require.NoError(t, err) @@ -79,8 +79,8 @@ func TestMsgGrantAllowance(t *testing.T) { } func TestMsgRevokeAllowance(t *testing.T) { - addr := sdk.AccAddress("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") - addr2 := sdk.AccAddress("link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu") + addr, _ := sdk.AccAddressFromBech32("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") + addr2, _ := sdk.AccAddressFromBech32("link18vd8fpwxzck93qlwghaj6arh4p7c5n89fvcmzu") atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) threeHours := time.Now().Add(3 * time.Hour) @@ -102,12 +102,12 @@ func TestMsgRevokeAllowance(t *testing.T) { }, "no grantee": { granter: addr2, - grantee: sdk.AccAddress(""), + grantee: sdk.AccAddress{}, grant: basic, valid: false, }, "no granter": { - granter: sdk.AccAddress(""), + granter: sdk.AccAddress{}, grantee: addr, grant: basic, valid: false, @@ -126,7 +126,7 @@ func TestMsgRevokeAllowance(t *testing.T) { if tc.valid { require.NoError(t, err) addrSlice := msg.GetSigners() - require.True(t, tc.granter.Equals(addrSlice[0])) + require.Equal(t, tc.granter.String(), addrSlice[0].String()) } else { require.Error(t, err) } diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index ab58e5bcba..f8d911ea06 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -121,8 +121,14 @@ func SimulateMsgRevokeAllowance(ak feegrant.AccountKeeper, bk feegrant.BankKeepe var granteeAddr sdk.AccAddress k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool { - granter := sdk.AccAddress(grant.Granter) - grantee := sdk.AccAddress(grant.Grantee) + granter, err := sdk.AccAddressFromBech32(grant.Granter) + if err != nil { + panic(err) + } + grantee, err := sdk.AccAddressFromBech32(grant.Grantee) + if err != nil { + panic(err) + } granterAddr = granter granteeAddr = grantee hasGrant = true diff --git a/x/feegrant/types/grant_test.go b/x/feegrant/types/grant_test.go index 0681dbb464..bf8fe88f37 100644 --- a/x/feegrant/types/grant_test.go +++ b/x/feegrant/types/grant_test.go @@ -15,8 +15,8 @@ import ( func TestGrant(t *testing.T) { app := simapp.Setup(false) - addr := sdk.AccAddress("link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5") - addr2 := sdk.AccAddress("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") + addr, _ := sdk.AccAddressFromBech32("link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5") + addr2, _ := sdk.AccAddressFromBech32("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) ctx := app.BaseApp.NewContext(false, ocproto.Header{ Time: time.Now(), @@ -43,13 +43,13 @@ func TestGrant(t *testing.T) { }, "no grantee": { granter: addr2, - grantee: "", + grantee: nil, limit: atom, expires: oneYear, valid: false, }, "no granter": { - granter: "", + granter: nil, grantee: addr, limit: atom, expires: oneYear, diff --git a/x/foundation/client/cli/query.go b/x/foundation/client/cli/query.go index 4e7d84e230..d078f45b12 100644 --- a/x/foundation/client/cli/query.go +++ b/x/foundation/client/cli/query.go @@ -139,7 +139,7 @@ func NewQueryCmdMember() *cobra.Command { queryClient := foundation.NewQueryClient(clientCtx) address := args[0] - if err = sdk.ValidateAccAddress(address); err != nil { + if _, err := sdk.AccAddressFromBech32(address); err != nil { return err } @@ -270,7 +270,7 @@ func NewQueryCmdVote() *cobra.Command { } voter := args[1] - if err := sdk.ValidateAccAddress(voter); err != nil { + if _, err := sdk.AccAddressFromBech32(voter); err != nil { return err } diff --git a/x/foundation/foundation.go b/x/foundation/foundation.go index f96979da86..e489a620ac 100644 --- a/x/foundation/foundation.go +++ b/x/foundation/foundation.go @@ -33,7 +33,7 @@ func validateProposers(proposers []string) error { } addrs[proposer] = true - if err := sdk.ValidateAccAddress(proposer); err != nil { + if _, err := sdk.AccAddressFromBech32(proposer); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proposer address: %s", proposer) } } @@ -82,7 +82,7 @@ func validateMembers(members []Member) error { } func (m Member) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Address); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { return err } diff --git a/x/foundation/genesis.go b/x/foundation/genesis.go index 5ec0afebce..49337cc17d 100644 --- a/x/foundation/genesis.go +++ b/x/foundation/genesis.go @@ -48,7 +48,7 @@ func ValidateGenesis(data GenesisState) error { if info := data.Foundation; info != nil { if operator := info.Operator; len(operator) != 0 { - if err := sdk.ValidateAccAddress(info.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(info.Operator); err != nil { return err } } @@ -95,7 +95,7 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidRequest.Wrapf("vote for a proposal which does not exist: id %d", vote.ProposalId) } - if err := sdk.ValidateAccAddress(vote.Voter); err != nil { + if _, err := sdk.AccAddressFromBech32(vote.Voter); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", vote.Voter) } @@ -109,7 +109,7 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidType.Wrap("invalid authorization") } - if err := sdk.ValidateAccAddress(ga.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(ga.Grantee); err != nil { return err } } diff --git a/x/foundation/genesis_test.go b/x/foundation/genesis_test.go index db87c2ffc5..f0f8586f58 100644 --- a/x/foundation/genesis_test.go +++ b/x/foundation/genesis_test.go @@ -19,7 +19,7 @@ func TestDefaultGenesisState(t *testing.T) { func TestValidateGenesis(t *testing.T) { createAddress := func() sdk.AccAddress { - return sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + return sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { diff --git a/x/foundation/keeper/genesis.go b/x/foundation/keeper/genesis.go index 854556231c..7cea3b39d1 100644 --- a/x/foundation/keeper/genesis.go +++ b/x/foundation/keeper/genesis.go @@ -24,12 +24,12 @@ func (k Keeper) InitGenesis(ctx sdk.Context, sk foundation.StakingKeeper, data * // so it should be the very first block of the chain. // We gather the information from staking module. sk.IterateValidators(ctx, func(_ int64, addr stakingtypes.ValidatorI) (stop bool) { - grantee := addr.GetOperator().ToAccAddress() + grantee := sdk.AccAddress(addr.GetOperator()) createValidatorGrantees = append(createValidatorGrantees, grantee) // add to authorizations authorization := &stakingplus.CreateValidatorAuthorization{ - ValidatorAddress: grantee.ToValAddress().String(), + ValidatorAddress: sdk.ValAddress(grantee).String(), } ga := foundation.GrantAuthorization{ Granter: govtypes.ModuleName, @@ -115,7 +115,11 @@ func (k Keeper) InitGenesis(ctx sdk.Context, sk foundation.StakingKeeper, data * } for _, ga := range authorizations { - k.setAuthorization(ctx, ga.Granter, sdk.AccAddress(ga.Grantee), ga.GetAuthorization()) + grantee, err := sdk.AccAddressFromBech32(ga.Grantee) + if err != nil { + return err + } + k.setAuthorization(ctx, ga.Granter, grantee, ga.GetAuthorization()) } return nil @@ -150,7 +154,11 @@ func (k Keeper) ResetState(ctx sdk.Context) { // reset members for _, member := range k.GetMembers(ctx) { - store.Delete(memberKey(sdk.AccAddress(member.Address))) + addr, err := sdk.AccAddressFromBech32(member.Address) + if err != nil { + panic(err) + } + store.Delete(memberKey(addr)) } // id @@ -163,7 +171,11 @@ func (k Keeper) ResetState(ctx sdk.Context) { // reset authorizations for _, ga := range k.GetGrants(ctx) { - k.deleteAuthorization(ctx, ga.Granter, sdk.AccAddress(ga.Grantee), ga.GetAuthorization().MsgTypeURL()) + grantee, err := sdk.AccAddressFromBech32(ga.Grantee) + if err != nil { + panic(err) + } + k.deleteAuthorization(ctx, ga.Granter, grantee, ga.GetAuthorization().MsgTypeURL()) } } @@ -190,7 +202,11 @@ func getCreateValidatorGrantees(authorizations []foundation.GrantAuthorization) var grantees []sdk.AccAddress for _, ga := range authorizations { if ga.Granter == granter && ga.GetAuthorization().MsgTypeURL() == msgTypeURL { - grantees = append(grantees, sdk.AccAddress(ga.Grantee)) + grantee, err := sdk.AccAddressFromBech32(ga.Grantee) + if err != nil { + panic(err) + } + grantees = append(grantees, grantee) } } diff --git a/x/foundation/keeper/genesis_test.go b/x/foundation/keeper/genesis_test.go index 7afa21a31a..9ef09de147 100644 --- a/x/foundation/keeper/genesis_test.go +++ b/x/foundation/keeper/genesis_test.go @@ -158,7 +158,7 @@ func (s *KeeperTestSuite) TestImportExportGenesis() { Granter: govtypes.ModuleName, Grantee: s.stranger.String(), }.WithAuthorization(&stakingplus.CreateValidatorAuthorization{ - ValidatorAddress: s.stranger.ToValAddress().String(), + ValidatorAddress: sdk.ValAddress(s.stranger).String(), }), }, }, @@ -175,7 +175,7 @@ func (s *KeeperTestSuite) TestImportExportGenesis() { Granter: govtypes.ModuleName, Grantee: s.stranger.String(), }.WithAuthorization(&stakingplus.CreateValidatorAuthorization{ - ValidatorAddress: s.stranger.ToValAddress().String(), + ValidatorAddress: sdk.ValAddress(s.stranger).String(), }), }, Members: []foundation.Member{{ diff --git a/x/foundation/keeper/grpc_query.go b/x/foundation/keeper/grpc_query.go index 46b6955f5e..e5e55c5d53 100644 --- a/x/foundation/keeper/grpc_query.go +++ b/x/foundation/keeper/grpc_query.go @@ -65,7 +65,11 @@ func (s queryServer) Member(c context.Context, req *foundation.QueryMemberReques } ctx := sdk.UnwrapSDKContext(c) - member, err := s.keeper.GetMember(ctx, sdk.AccAddress(req.Address)) + addr, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { + return nil, err + } + member, err := s.keeper.GetMember(ctx, addr) if err != nil { return nil, err } @@ -137,7 +141,11 @@ func (s queryServer) Vote(c context.Context, req *foundation.QueryVoteRequest) ( } ctx := sdk.UnwrapSDKContext(c) - vote, err := s.keeper.GetVote(ctx, req.ProposalId, sdk.AccAddress(req.Voter)) + voter, err := sdk.AccAddressFromBech32(req.Voter) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid voter address") + } + vote, err := s.keeper.GetVote(ctx, req.ProposalId, voter) if err != nil { return nil, err } @@ -191,7 +199,8 @@ func (s queryServer) Grants(c context.Context, req *foundation.QueryGrantsReques return nil, status.Error(codes.InvalidArgument, "invalid request") } - if err := sdk.ValidateAccAddress(req.Grantee); err != nil { + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { return nil, err } @@ -199,11 +208,11 @@ func (s queryServer) Grants(c context.Context, req *foundation.QueryGrantsReques store := ctx.KVStore(s.keeper.storeKey) if req.MsgTypeUrl != "" { - keyPrefix := grantKeyPrefixByURL(sdk.AccAddress(req.Grantee), req.MsgTypeUrl) + keyPrefix := grantKeyPrefixByURL(grantee, req.MsgTypeUrl) grantStore := prefix.NewStore(store, keyPrefix) var authorizations []*codectypes.Any - _, err := query.Paginate(grantStore, req.Pagination, func(key []byte, value []byte) error { + _, err = query.Paginate(grantStore, req.Pagination, func(key []byte, value []byte) error { var authorization foundation.Authorization if err := s.keeper.cdc.UnmarshalInterface(value, &authorization); err != nil { panic(err) @@ -229,7 +238,7 @@ func (s queryServer) Grants(c context.Context, req *foundation.QueryGrantsReques } - keyPrefix := grantKeyPrefixByGrantee(sdk.AccAddress(req.Grantee)) + keyPrefix := grantKeyPrefixByGrantee(grantee) grantStore := prefix.NewStore(store, keyPrefix) var authorizations []*codectypes.Any diff --git a/x/foundation/keeper/keeper_test.go b/x/foundation/keeper/keeper_test.go index 70dac3ae6c..667ff09c4d 100644 --- a/x/foundation/keeper/keeper_test.go +++ b/x/foundation/keeper/keeper_test.go @@ -21,8 +21,8 @@ import ( var ( delPk = ed25519.GenPrivKey().PubKey() - delAddr = sdk.BytesToAccAddress(delPk.Address()) - valAddr = delAddr.ToValAddress() + delAddr = sdk.AccAddress(delPk.Address()) + valAddr = sdk.ValAddress(delAddr) ) func TestCleanup(t *testing.T) { @@ -70,7 +70,7 @@ func (s *KeeperTestSuite) SetupTest() { s.msgServer = keeper.NewMsgServer(s.keeper) createAddress := func() sdk.AccAddress { - return sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + return sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } s.operator = s.keeper.GetOperator(s.ctx) diff --git a/x/foundation/keeper/keys.go b/x/foundation/keeper/keys.go index a58d643d3b..845a09d414 100644 --- a/x/foundation/keeper/keys.go +++ b/x/foundation/keeper/keys.go @@ -148,7 +148,7 @@ func grantKeyPrefixByGrantee(grantee sdk.AccAddress) []byte { func splitGrantKey(key []byte) (grantee sdk.AccAddress, url, granter string) { begin := len(grantKeyPrefix) + 1 end := begin + int(key[begin-1]) - grantee = sdk.AccAddress(key[begin:end]) + grantee = key[begin:end] begin = end + 1 end = begin + int(key[begin-1]) diff --git a/x/foundation/keeper/member.go b/x/foundation/keeper/member.go index 7deea3a436..f846137045 100644 --- a/x/foundation/keeper/member.go +++ b/x/foundation/keeper/member.go @@ -56,7 +56,11 @@ func (k Keeper) UpdateMembers(ctx sdk.Context, members []foundation.Member) erro } new.AddedAt = ctx.BlockTime() - old, err := k.GetMember(ctx, sdk.AccAddress(new.Address)) + newAddr, err := sdk.AccAddressFromBech32(new.Address) + if err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid new address: %s", new.Address) + } + old, err := k.GetMember(ctx, newAddr) if err == nil { weightUpdate = weightUpdate.Sub(sdk.OneDec()) new.AddedAt = old.AddedAt @@ -68,7 +72,11 @@ func (k Keeper) UpdateMembers(ctx sdk.Context, members []foundation.Member) erro } if deleting { - k.deleteMember(ctx, sdk.AccAddress(old.Address)) + oldAddr, err := sdk.AccAddressFromBech32(old.Address) + if err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid old address: %s", old.Address) + } + k.deleteMember(ctx, oldAddr) } else { weightUpdate = weightUpdate.Add(sdk.OneDec()) k.setMember(ctx, new) @@ -102,7 +110,11 @@ func (k Keeper) GetMember(ctx sdk.Context, address sdk.AccAddress) (*foundation. func (k Keeper) setMember(ctx sdk.Context, member foundation.Member) { store := ctx.KVStore(k.storeKey) - key := memberKey(sdk.AccAddress(member.Address)) + addr, err := sdk.AccAddressFromBech32(member.Address) + if err != nil { + panic(err) + } + key := memberKey(addr) bz := k.cdc.MustMarshal(&member) store.Set(key, bz) @@ -141,7 +153,11 @@ func (k Keeper) GetMembers(ctx sdk.Context) []foundation.Member { func (k Keeper) GetOperator(ctx sdk.Context) sdk.AccAddress { info := k.GetFoundationInfo(ctx) - return sdk.AccAddress(info.Operator) + operator, err := sdk.AccAddressFromBech32(info.Operator) + if err != nil { + panic(err) + } + return operator } func (k Keeper) UpdateOperator(ctx sdk.Context, operator sdk.AccAddress) error { @@ -161,7 +177,13 @@ func (k Keeper) GetAdmin(ctx sdk.Context) sdk.AccAddress { } func (k Keeper) validateOperator(ctx sdk.Context, operator string) error { - if sdk.AccAddress(operator) != k.GetOperator(ctx) { + addr, err := sdk.AccAddressFromBech32(operator) + + if err != nil { + return err + } + + if !addr.Equals(k.GetOperator(ctx)) { return sdkerrors.ErrUnauthorized.Wrapf("%s is not the operator", operator) } @@ -170,7 +192,11 @@ func (k Keeper) validateOperator(ctx sdk.Context, operator string) error { func (k Keeper) validateMembers(ctx sdk.Context, members []string) error { for _, member := range members { - if _, err := k.GetMember(ctx, sdk.AccAddress(member)); err != nil { + addr, err := sdk.AccAddressFromBech32(member) + if err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", member) + } + if _, err := k.GetMember(ctx, addr); err != nil { return sdkerrors.ErrUnauthorized.Wrapf("%s is not a member", member) } } diff --git a/x/foundation/keeper/msg_server.go b/x/foundation/keeper/msg_server.go index 5157fc62cf..17f93f82ad 100644 --- a/x/foundation/keeper/msg_server.go +++ b/x/foundation/keeper/msg_server.go @@ -34,7 +34,11 @@ var _ foundation.MsgServer = msgServer{} // FundTreasury defines a method to fund the treasury. func (s msgServer) FundTreasury(c context.Context, req *foundation.MsgFundTreasury) (*foundation.MsgFundTreasuryResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.FundTreasury(ctx, sdk.AccAddress(req.From), req.Amount); err != nil { + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, err + } + if err := s.keeper.FundTreasury(ctx, from, req.Amount); err != nil { return nil, err } @@ -56,11 +60,15 @@ func (s msgServer) WithdrawFromTreasury(c context.Context, req *foundation.MsgWi return nil, err } - if err := s.keeper.Accept(ctx, foundation.ModuleName, sdk.AccAddress(req.To), req); err != nil { + to, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, err + } + if err := s.keeper.Accept(ctx, foundation.ModuleName, to, req); err != nil { return nil, err } - if err := s.keeper.WithdrawFromTreasury(ctx, sdk.AccAddress(req.To), req.Amount); err != nil { + if err := s.keeper.WithdrawFromTreasury(ctx, to, req.Amount); err != nil { return nil, err } @@ -273,7 +281,11 @@ func (s msgServer) Grant(c context.Context, req *foundation.MsgGrant) (*foundati } authorization := req.GetAuthorization() - if err := s.keeper.Grant(ctx, foundation.ModuleName, sdk.AccAddress(req.Grantee), authorization); err != nil { + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, err + } + if err := s.keeper.Grant(ctx, foundation.ModuleName, grantee, authorization); err != nil { return nil, err } @@ -291,7 +303,11 @@ func (s msgServer) Revoke(c context.Context, req *foundation.MsgRevoke) (*founda return nil, sdkerrors.ErrUnauthorized.Wrapf("foundation cannot revoke %s", req.MsgTypeUrl) } - if err := s.keeper.Revoke(ctx, foundation.ModuleName, sdk.AccAddress(req.Grantee), req.MsgTypeUrl); err != nil { + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, err + } + if err := s.keeper.Revoke(ctx, foundation.ModuleName, grantee, req.MsgTypeUrl); err != nil { return nil, err } diff --git a/x/foundation/keeper/proposal.go b/x/foundation/keeper/proposal.go index 931e86897a..648a9fbb50 100644 --- a/x/foundation/keeper/proposal.go +++ b/x/foundation/keeper/proposal.go @@ -32,7 +32,12 @@ func (k Keeper) handleUpdateFoundationParamsProposal(ctx sdk.Context, p *foundat // handleUpdateValidatorAuthsProposal is a handler for update validator auths proposal func (k Keeper) handleUpdateValidatorAuthsProposal(ctx sdk.Context, p *foundation.UpdateValidatorAuthsProposal) error { for _, auth := range p.Auths { - grantee := sdk.ValAddress(auth.OperatorAddress).ToAccAddress() + valAddr, err := sdk.ValAddressFromBech32(auth.OperatorAddress) + grantee := sdk.AccAddress(valAddr) + + if err != nil { + return err + } if auth.CreationAllowed { authorization := &stakingplus.CreateValidatorAuthorization{ ValidatorAddress: auth.OperatorAddress, @@ -78,7 +83,11 @@ func (k Keeper) SubmitProposal(ctx sdk.Context, proposers []string, metadata str } foundationInfo := k.GetFoundationInfo(ctx) - if err := ensureMsgAuthz(msgs, sdk.AccAddress(foundationInfo.Operator)); err != nil { + operator, err := sdk.AccAddressFromBech32(foundationInfo.Operator) + if err != nil { + return 0, err + } + if err := ensureMsgAuthz(msgs, operator); err != nil { return 0, err } diff --git a/x/foundation/keeper/proposal_test.go b/x/foundation/keeper/proposal_test.go index c322f0ee62..ae68b88229 100644 --- a/x/foundation/keeper/proposal_test.go +++ b/x/foundation/keeper/proposal_test.go @@ -59,8 +59,10 @@ func TestProposalHandler(t *testing.T) { require.NoError(t, ap.ValidateBasic()) require.NoError(t, handler(ctx, ap)) for i := range adding { - grantee := sdk.ValAddress(adding[i].OperatorAddress).ToAccAddress() - _, err := k.GetAuthorization(ctx, govtypes.ModuleName, grantee, msgTypeURL) + valAddr, err := sdk.ValAddressFromBech32(adding[i].OperatorAddress) + grantee := sdk.AccAddress(valAddr) + require.NoError(t, err) + _, err = k.GetAuthorization(ctx, govtypes.ModuleName, grantee, msgTypeURL) require.NoError(t, err) } @@ -70,8 +72,9 @@ func TestProposalHandler(t *testing.T) { require.NoError(t, dp.ValidateBasic()) require.NoError(t, handler(ctx, dp)) for i := range deleting { - grantee := sdk.ValAddress(adding[i].OperatorAddress).ToAccAddress() - _, err := k.GetAuthorization(ctx, govtypes.ModuleName, grantee, msgTypeURL) + valAddr, err := sdk.ValAddressFromBech32(adding[i].OperatorAddress) + grantee := sdk.AccAddress(valAddr) + _, err = k.GetAuthorization(ctx, govtypes.ModuleName, grantee, msgTypeURL) require.Error(t, err) } diff --git a/x/foundation/keeper/tally.go b/x/foundation/keeper/tally.go index f919822144..294eeaab10 100644 --- a/x/foundation/keeper/tally.go +++ b/x/foundation/keeper/tally.go @@ -58,7 +58,12 @@ func (k Keeper) tally(ctx sdk.Context, p foundation.Proposal) (foundation.TallyR tallyResult := foundation.DefaultTallyResult() var errors []error k.iterateVotes(ctx, p.Id, func(vote foundation.Vote) (stop bool) { - _, err := k.GetMember(ctx, sdk.AccAddress(vote.Voter)) + voter, err := sdk.AccAddressFromBech32(vote.Voter) + if err != nil { + errors = append(errors, err) + return true + } + _, err = k.GetMember(ctx, voter) switch { case sdkerrors.ErrNotFound.Is(err): // If the member left the group after voting, then we simply skip the diff --git a/x/foundation/keeper/vote.go b/x/foundation/keeper/vote.go index bade705088..0e1e652333 100644 --- a/x/foundation/keeper/vote.go +++ b/x/foundation/keeper/vote.go @@ -12,7 +12,11 @@ func (k Keeper) Vote(ctx sdk.Context, vote foundation.Vote) error { } // Make sure that a voter hasn't already voted. - if k.hasVote(ctx, vote.ProposalId, sdk.AccAddress(vote.Voter)) { + voter, err := sdk.AccAddressFromBech32(vote.Voter) + if err != nil { + return err + } + if k.hasVote(ctx, vote.ProposalId, voter) { return sdkerrors.ErrInvalidRequest.Wrapf("Already voted: %s", vote.Voter) } @@ -63,8 +67,11 @@ func (k Keeper) GetVote(ctx sdk.Context, proposalID uint64, voter sdk.AccAddress func (k Keeper) setVote(ctx sdk.Context, vote foundation.Vote) { store := ctx.KVStore(k.storeKey) - key := voteKey(vote.ProposalId, sdk.AccAddress(vote.Voter)) - + voter, err := sdk.AccAddressFromBech32(vote.Voter) + if err != nil { + panic(err) + } + key := voteKey(vote.ProposalId, voter) bz := k.cdc.MustMarshal(&vote) store.Set(key, bz) } @@ -98,7 +105,11 @@ func (k Keeper) GetVotes(ctx sdk.Context, proposalID uint64) []foundation.Vote { func (k Keeper) pruneVotes(ctx sdk.Context, proposalID uint64) { keys := [][]byte{} k.iterateVotes(ctx, proposalID, func(vote foundation.Vote) (stop bool) { - keys = append(keys, voteKey(proposalID, sdk.AccAddress(vote.Voter))) + voter, err := sdk.AccAddressFromBech32(vote.Voter) + if err != nil { + return true + } + keys = append(keys, voteKey(proposalID, voter)) return false }) diff --git a/x/foundation/msgs.go b/x/foundation/msgs.go index 2bc4d830cc..f4c1bc084b 100644 --- a/x/foundation/msgs.go +++ b/x/foundation/msgs.go @@ -12,7 +12,7 @@ var _ sdk.Msg = (*MsgFundTreasury)(nil) // ValidateBasic implements Msg. func (m MsgFundTreasury) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -25,7 +25,7 @@ func (m MsgFundTreasury) ValidateBasic() error { // GetSigners implements Msg. func (m MsgFundTreasury) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -33,11 +33,11 @@ var _ sdk.Msg = (*MsgWithdrawFromTreasury)(nil) // ValidateBasic implements Msg. func (m MsgWithdrawFromTreasury) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -50,7 +50,7 @@ func (m MsgWithdrawFromTreasury) ValidateBasic() error { // GetSigners implements Msg. func (m MsgWithdrawFromTreasury) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -58,7 +58,7 @@ var _ sdk.Msg = (*MsgUpdateMembers)(nil) // ValidateBasic implements Msg. func (m MsgUpdateMembers) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -74,7 +74,7 @@ func (m MsgUpdateMembers) ValidateBasic() error { // GetSigners implements Msg. func (m MsgUpdateMembers) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -82,7 +82,7 @@ var _ sdk.Msg = (*MsgUpdateDecisionPolicy)(nil) // ValidateBasic implements Msg. func (m MsgUpdateDecisionPolicy) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -99,7 +99,7 @@ func (m MsgUpdateDecisionPolicy) ValidateBasic() error { // GetSigners implements Msg. func (m MsgUpdateDecisionPolicy) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -178,8 +178,9 @@ func (m MsgSubmitProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) err // GetSigners implements Msg. func (m MsgSubmitProposal) GetSigners() []sdk.AccAddress { signers := make([]sdk.AccAddress, len(m.Proposers)) - for i, proposer := range m.Proposers { - signers[i] = sdk.AccAddress(proposer) + for i, p := range m.Proposers { + proposer, _ := sdk.AccAddressFromBech32(p) + signers[i] = proposer } return signers } @@ -192,7 +193,7 @@ func (m MsgWithdrawProposal) ValidateBasic() error { return sdkerrors.ErrInvalidRequest.Wrap("empty proposal id") } - if err := sdk.ValidateAccAddress(m.Address); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid withdrawer address: %s", m.Address) } @@ -201,7 +202,7 @@ func (m MsgWithdrawProposal) ValidateBasic() error { // GetSigners implements Msg. func (m MsgWithdrawProposal) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Address) + signer, _ := sdk.AccAddressFromBech32(m.Address) return []sdk.AccAddress{signer} } @@ -213,7 +214,7 @@ func (m MsgVote) ValidateBasic() error { return sdkerrors.ErrInvalidRequest.Wrap("empty proposal id") } - if err := sdk.ValidateAccAddress(m.Voter); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Voter); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid voter address: %s", m.Voter) } @@ -230,7 +231,7 @@ func (m MsgVote) ValidateBasic() error { // GetSigners implements Msg. func (m MsgVote) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Voter) + signer, _ := sdk.AccAddressFromBech32(m.Voter) return []sdk.AccAddress{signer} } @@ -242,7 +243,7 @@ func (m MsgExec) ValidateBasic() error { return sdkerrors.ErrInvalidRequest.Wrap("empty proposal id") } - if err := sdk.ValidateAccAddress(m.Signer); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Signer); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid approver address: %s", m.Signer) } @@ -251,7 +252,7 @@ func (m MsgExec) ValidateBasic() error { // GetSigners implements Msg. func (m MsgExec) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Signer) + signer, _ := sdk.AccAddressFromBech32(m.Signer) return []sdk.AccAddress{signer} } @@ -259,7 +260,7 @@ var _ sdk.Msg = (*MsgLeaveFoundation)(nil) // ValidateBasic implements Msg. func (m MsgLeaveFoundation) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Address); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid member address: %s", m.Address) } @@ -268,7 +269,7 @@ func (m MsgLeaveFoundation) ValidateBasic() error { // GetSigners implements Msg. func (m MsgLeaveFoundation) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Address) + signer, _ := sdk.AccAddressFromBech32(m.Address) return []sdk.AccAddress{signer} } @@ -276,11 +277,11 @@ var _ sdk.Msg = (*MsgGrant)(nil) // ValidateBasic implements Msg. func (m MsgGrant) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Grantee); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.Grantee) } @@ -324,7 +325,7 @@ func (m MsgGrant) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { // GetSigners implements Msg. func (m MsgGrant) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -332,11 +333,11 @@ var _ sdk.Msg = (*MsgRevoke)(nil) // ValidateBasic implements Msg. func (m MsgRevoke) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Grantee); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.Grantee) } @@ -349,6 +350,6 @@ func (m MsgRevoke) ValidateBasic() error { // GetSigners implements Msg. func (m MsgRevoke) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } diff --git a/x/foundation/msgs_test.go b/x/foundation/msgs_test.go index 7b9e1c21f7..7ffd77513f 100644 --- a/x/foundation/msgs_test.go +++ b/x/foundation/msgs_test.go @@ -14,7 +14,7 @@ import ( func TestMsgFundTreasury(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -42,21 +42,21 @@ func TestMsgFundTreasury(t *testing.T) { Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tc.amount)), } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners(), name) } } func TestMsgWithdrawFromTreasury(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -93,21 +93,21 @@ func TestMsgWithdrawFromTreasury(t *testing.T) { Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, tc.amount)), } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) } } func TestMsgUpdateMembers(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -131,7 +131,6 @@ func TestMsgUpdateMembers(t *testing.T) { }, "empty members": { operator: addrs[0], - members: []foundation.Member{}, }, "empty member address": { operator: addrs[0], @@ -159,21 +158,21 @@ func TestMsgUpdateMembers(t *testing.T) { MemberUpdates: tc.members, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) } } func TestMsgUpdateDecisionPolicy(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -248,21 +247,21 @@ func TestMsgUpdateDecisionPolicy(t *testing.T) { require.NoError(t, err, name) } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) } } func TestMsgSubmitProposal(t *testing.T) { addrs := make([]sdk.AccAddress, 3) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -281,7 +280,6 @@ func TestMsgSubmitProposal(t *testing.T) { valid: true, }, "empty proposers": { - proposers: []sdk.AccAddress{}, msgs: []sdk.Msg{&foundation.MsgWithdrawFromTreasury{ Operator: addrs[1].String(), To: addrs[2].String(), @@ -289,7 +287,7 @@ func TestMsgSubmitProposal(t *testing.T) { }}, }, "invalid proposer": { - proposers: []sdk.AccAddress{""}, + proposers: []sdk.AccAddress{nil}, msgs: []sdk.Msg{&foundation.MsgWithdrawFromTreasury{ Operator: addrs[1].String(), To: addrs[2].String(), @@ -335,21 +333,21 @@ func TestMsgSubmitProposal(t *testing.T) { err := msg.SetMsgs(tc.msgs) require.NoError(t, err, name) - require.Equal(t, tc.proposers, msg.GetSigners(), name) - err = msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, tc.proposers, msg.GetSigners(), name) } } func TestMsgWithdrawProposal(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -376,21 +374,21 @@ func TestMsgWithdrawProposal(t *testing.T) { Address: tc.address.String(), } - require.Equal(t, []sdk.AccAddress{tc.address}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.address}, msg.GetSigners(), name) } } func TestMsgVote(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -439,21 +437,21 @@ func TestMsgVote(t *testing.T) { Exec: tc.exec, } - require.Equal(t, []sdk.AccAddress{tc.voter}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.voter}, msg.GetSigners(), name) } } func TestMsgExec(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -480,21 +478,21 @@ func TestMsgExec(t *testing.T) { Signer: tc.signer.String(), } - require.Equal(t, []sdk.AccAddress{tc.signer}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.signer}, msg.GetSigners(), name) } } func TestMsgLeaveFoundation(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -513,21 +511,21 @@ func TestMsgLeaveFoundation(t *testing.T) { Address: tc.address.String(), } - require.Equal(t, []sdk.AccAddress{tc.address}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.address}, msg.GetSigners(), name) } } func TestMsgGrant(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -565,21 +563,21 @@ func TestMsgGrant(t *testing.T) { msg.SetAuthorization(tc.authorization) } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) } } func TestMsgRevoke(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -615,13 +613,13 @@ func TestMsgRevoke(t *testing.T) { MsgTypeUrl: tc.msgTypeURL, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners(), name) } } diff --git a/x/foundation/proposal.go b/x/foundation/proposal.go index 48ef76f01c..2c52f5b894 100644 --- a/x/foundation/proposal.go +++ b/x/foundation/proposal.go @@ -74,7 +74,7 @@ func (p *UpdateValidatorAuthsProposal) ValidateBasic() error { usedAddrs := map[string]bool{} for _, auth := range p.Auths { addr := auth.OperatorAddress - if err := sdk.ValidateValAddress(addr); err != nil { + if _, err := sdk.ValAddressFromBech32(addr); err != nil { return err } if usedAddrs[addr] { diff --git a/x/foundation/proposal_test.go b/x/foundation/proposal_test.go index c5c75e0d1d..61b0ef464b 100644 --- a/x/foundation/proposal_test.go +++ b/x/foundation/proposal_test.go @@ -52,7 +52,7 @@ func TestUpdateFoundationParamsProposal(t *testing.T) { func TestUpdateValidatorAuthsProposal(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -61,7 +61,7 @@ func TestUpdateValidatorAuthsProposal(t *testing.T) { }{ "valid proposal": { updates: []foundation.ValidatorAuth{{ - OperatorAddress: addrs[0].ToValAddress().String(), + OperatorAddress: sdk.ValAddress(addrs[0]).String(), CreationAllowed: true, }}, valid: true, @@ -75,11 +75,11 @@ func TestUpdateValidatorAuthsProposal(t *testing.T) { "duplicate addresses": { updates: []foundation.ValidatorAuth{ { - OperatorAddress: addrs[0].ToValAddress().String(), + OperatorAddress: sdk.ValAddress(addrs[0]).String(), CreationAllowed: true, }, { - OperatorAddress: addrs[0].ToValAddress().String(), + OperatorAddress: sdk.ValAddress(addrs[0]).String(), }, }, }, diff --git a/x/genutil/collect.go b/x/genutil/collect.go index 4f1c513833..f7fe798106 100644 --- a/x/genutil/collect.go +++ b/x/genutil/collect.go @@ -140,7 +140,7 @@ func CollectTxs(cdc codec.JSONCodec, txJSONDecoder sdk.TxDecoder, moniker, genTx // validate delegator and validator addresses and funds against the accounts in the state delAddr := msg.DelegatorAddress - valAddr, err := sdk.ValAddressToBytes(msg.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) if err != nil { return appGenTxs, persistentPeers, err } @@ -155,11 +155,11 @@ func CollectTxs(cdc codec.JSONCodec, txJSONDecoder sdk.TxDecoder, moniker, genTx return appGenTxs, persistentPeers, fmt.Errorf("account %s balance not in genesis state: %+v", delAddr, balancesMap) } - _, valOk := balancesMap[sdk.BytesToAccAddress(valAddr).String()] + _, valOk := balancesMap[sdk.AccAddress(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.BytesToAccAddress(valAddr).String()) + fmt.Printf("CollectTxs-2, called from %s#%d - %s\n", file, no, 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 5824dbed19..1f49ee2f94 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.BytesToAccAddress(pk1.Address()) - addr2 = sdk.BytesToAccAddress(pk2.Address()) + addr1 = sdk.AccAddress(pk1.Address()) + addr2 = sdk.AccAddress(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.BytesToValAddress(pk1.Address()), pk1, amount, desc, comm, one) + sdk.ValAddress(pk1.Address()), pk1, amount, desc, comm, one) suite.NoError(err) suite.msg2, err = stakingtypes.NewMsgCreateValidator( - sdk.BytesToValAddress(pk2.Address()), pk1, amount, desc, comm, one) + sdk.ValAddress(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 bb361b3940..60bf700653 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.BytesToValAddress(pk1.Address()), pk1, + msg1, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(pk1.Address()), pk1, sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, sdk.OneInt()) require.NoError(t, err) - msg2, err := stakingtypes.NewMsgCreateValidator(sdk.BytesToValAddress(pk2.Address()), pk2, + msg2, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(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.BytesToValAddress(pk1.Address()), desc, nil, nil) + msg1 := stakingtypes.NewMsgEditValidator(sdk.ValAddress(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 da203bbdc5..cdda519061 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -283,7 +283,7 @@ func TestProposalPassedEndblocker(t *testing.T) { header := ocproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - valAddr := addrs[0].ToValAddress() + valAddr := sdk.ValAddress(addrs[0]) createValidators(t, stakingHandler, ctx, []sdk.ValAddress{valAddr}, []int64{10}) staking.EndBlocker(ctx, app.StakingKeeper) @@ -332,7 +332,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { header := ocproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - valAddr := addrs[0].ToValAddress() + valAddr := sdk.ValAddress(addrs[0]) createValidators(t, stakingHandler, ctx, []sdk.ValAddress{valAddr}, []int64{10}) staking.EndBlocker(ctx, app.StakingKeeper) diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index e36621a482..d668314b38 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -114,6 +114,20 @@ $ %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 @@ -202,7 +216,10 @@ $ %s query gov vote 1 link1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } - voterAddr := sdk.AccAddress(args[1]) + voterAddr, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } res, err := queryClient.Vote( ctx, @@ -357,7 +374,10 @@ $ %s query gov deposit 1 link1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } - depositorAddr := sdk.AccAddress(args[1]) + depositorAddr, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } var deposit types.Deposit propStatus := proposalRes.Proposal.Status diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go index 39647ad6d9..5d9d84e97c 100644 --- a/x/gov/client/rest/query.go +++ b/x/gov/client/rest/query.go @@ -180,13 +180,11 @@ func queryDepositHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - if err := sdk.ValidateAccAddress(bechDepositorAddr); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) + if rest.CheckBadRequestError(w, err) { return } - depositorAddr := sdk.AccAddress(bechDepositorAddr) - clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return @@ -258,13 +256,12 @@ func queryVoteHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - if err := sdk.ValidateAccAddress(bechVoterAddr); err != nil { + voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) + if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - voterAddr := sdk.AccAddress(bechVoterAddr) - clientCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { return @@ -399,11 +396,17 @@ func queryProposalsWithParameterFn(clientCtx client.Context) http.HandlerFunc { ) if v := r.URL.Query().Get(RestVoter); len(v) != 0 { - voterAddr = sdk.AccAddress(v) + voterAddr, err = sdk.AccAddressFromBech32(v) + if rest.CheckBadRequestError(w, err) { + return + } } if v := r.URL.Query().Get(RestDepositor); len(v) != 0 { - depositorAddr = sdk.AccAddress(v) + depositorAddr, err = sdk.AccAddressFromBech32(v) + if rest.CheckBadRequestError(w, err) { + return + } } if v := r.URL.Query().Get(RestProposalStatus); len(v) != 0 { diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index 7513b57224..975d3d6c46 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -84,12 +84,10 @@ func TestGetPaginatedVotes(t *testing.T) { msgs [][]sdk.Msg votes []types.Vote } - acc1Bytes := make([]byte, 20) - acc1Bytes[0] = 1 - acc2Bytes := make([]byte, 20) - acc2Bytes[0] = 2 - acc1 := sdk.BytesToAccAddress(acc1Bytes) - acc2 := sdk.BytesToAccAddress(acc2Bytes) + acc1 := make(sdk.AccAddress, 20) + acc1[0] = 1 + acc2 := make(sdk.AccAddress, 20) + acc2[0] = 2 acc1Msgs := []sdk.Msg{ types.NewMsgVote(acc1, 0, types.OptionYes), types.NewMsgVote(acc1, 0, types.OptionYes), @@ -109,8 +107,7 @@ func TestGetPaginatedVotes(t *testing.T) { }, votes: []types.Vote{ types.NewVote(0, acc1, types.NewNonSplitVoteOption(types.OptionYes)), - types.NewVote(0, acc2, types.NewNonSplitVoteOption(types.OptionYes)), - }, + types.NewVote(0, acc2, types.NewNonSplitVoteOption(types.OptionYes))}, }, { description: "2MsgPerTx1Chunk", diff --git a/x/gov/common_test.go b/x/gov/common_test.go index d80a063199..c33903cfa5 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] = sdk.AccAddress(string(byteAddr)) + addrs[i] = byteAddr } } diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index a970b30ed0..184a663ee0 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -25,7 +25,10 @@ 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.MustMarshal(&deposit) - depositor := sdk.AccAddress(deposit.Depositor) + depositor, err := sdk.AccAddressFromBech32(deposit.Depositor) + if err != nil { + panic(err) + } store.Set(types.DepositKey(deposit.ProposalId, depositor), bz) } @@ -60,7 +63,10 @@ func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID uint64) { panic(err) } - depositor := sdk.AccAddress(deposit.Depositor) + depositor, err := sdk.AccAddressFromBech32(deposit.Depositor) + if err != nil { + panic(err) + } store.Delete(types.DepositKey(proposalID, depositor)) return false }) @@ -165,9 +171,12 @@ func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) keeper.IterateDeposits(ctx, proposalID, func(deposit types.Deposit) bool { - depositor := sdk.AccAddress(deposit.Depositor) + depositor, err := sdk.AccAddressFromBech32(deposit.Depositor) + if err != nil { + panic(err) + } - 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 a96f63b351..8f44fe4a17 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -57,14 +57,20 @@ func (q Keeper) Proposals(c context.Context, req *types.QueryProposalsRequest) ( // match voter address (if supplied) if len(req.Voter) > 0 { - voter := sdk.AccAddress(req.Voter) + voter, err := sdk.AccAddressFromBech32(req.Voter) + if err != nil { + return false, err + } _, matchVoter = q.GetVote(ctx, p.ProposalId, voter) } // match depositor (if supplied) if len(req.Depositor) > 0 { - depositor := sdk.AccAddress(req.Depositor) + depositor, err := sdk.AccAddressFromBech32(req.Depositor) + if err != nil { + return false, err + } _, matchDepositor = q.GetDeposit(ctx, p.ProposalId, depositor) } @@ -102,7 +108,10 @@ func (q Keeper) Vote(c context.Context, req *types.QueryVoteRequest) (*types.Que ctx := sdk.UnwrapSDKContext(c) - voter := sdk.AccAddress(req.Voter) + voter, err := sdk.AccAddressFromBech32(req.Voter) + if err != nil { + return nil, err + } vote, found := q.GetVote(ctx, req.ProposalId, voter) if !found { return nil, status.Errorf(codes.InvalidArgument, @@ -189,7 +198,10 @@ func (q Keeper) Deposit(c context.Context, req *types.QueryDepositRequest) (*typ ctx := sdk.UnwrapSDKContext(c) - depositor := sdk.AccAddress(req.Depositor) + depositor, err := sdk.AccAddressFromBech32(req.Depositor) + if err != nil { + return nil, err + } 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 2d99d7fc5f..07949fd3f3 100644 --- a/x/gov/keeper/grpc_query_test.go +++ b/x/gov/keeper/grpc_query_test.go @@ -398,8 +398,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryVotes() { {ProposalId: proposal.ProposalId, Voter: addrs[0].String(), Option: types.OptionAbstain, Options: types.NewNonSplitVoteOption(types.OptionAbstain)}, {ProposalId: proposal.ProposalId, Voter: addrs[1].String(), Option: types.OptionYes, Options: types.NewNonSplitVoteOption(types.OptionYes)}, } - accAddr1 := sdk.AccAddress(votes[0].Voter) - accAddr2 := sdk.AccAddress(votes[1].Voter) + accAddr1, err1 := sdk.AccAddressFromBech32(votes[0].Voter) + accAddr2, err2 := sdk.AccAddressFromBech32(votes[1].Voter) + suite.Require().NoError(err1) + suite.Require().NoError(err2) suite.Require().NoError(app.GovKeeper.AddVote(ctx, proposal.ProposalId, accAddr1, votes[0].Options)) suite.Require().NoError(app.GovKeeper.AddVote(ctx, proposal.ProposalId, accAddr2, votes[1].Options)) diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 787d7b0dfc..ab138b7248 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -61,7 +61,10 @@ 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 := sdk.AccAddress(msg.Voter) + accAddr, accErr := sdk.AccAddressFromBech32(msg.Voter) + if accErr != nil { + return nil, accErr + } err := k.Keeper.AddVote(ctx, msg.ProposalId, accAddr, types.NewNonSplitVoteOption(msg.Option)) if err != nil { return nil, err @@ -88,7 +91,10 @@ func (k msgServer) Vote(goCtx context.Context, msg *types.MsgVote) (*types.MsgVo func (k msgServer) VoteWeighted(goCtx context.Context, msg *types.MsgVoteWeighted) (*types.MsgVoteWeightedResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - accAddr := sdk.AccAddress(msg.Voter) + accAddr, accErr := sdk.AccAddressFromBech32(msg.Voter) + if accErr != nil { + return nil, accErr + } err := k.Keeper.AddVote(ctx, msg.ProposalId, accAddr, msg.Options) if err != nil { return nil, err @@ -115,7 +121,10 @@ func (k msgServer) VoteWeighted(goCtx context.Context, msg *types.MsgVoteWeighte func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - accAddr := sdk.AccAddress(msg.Depositor) + accAddr, err := sdk.AccAddressFromBech32(msg.Depositor) + if err != nil { + return nil, err + } 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 0301016fb5..d09fd86b20 100644 --- a/x/gov/keeper/proposal_test.go +++ b/x/gov/keeper/proposal_test.go @@ -73,7 +73,7 @@ func (suite *KeeperTestSuite) TestGetProposalsFiltered() { proposalID := uint64(1) status := []types.ProposalStatus{types.StatusDepositPeriod, types.StatusVotingPeriod} - addr1 := sdk.BytesToAccAddress([]byte("foo_________________")) + addr1 := sdk.AccAddress("foo_________________") for _, s := range status { for i := 0; i < 50; i++ { @@ -98,18 +98,18 @@ func (suite *KeeperTestSuite) TestGetProposalsFiltered() { params types.QueryProposalsParams expectedNumResults int }{ - {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, 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, addr1, addr1), 50}, {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, addr1, addr1), 25}, - {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, "", ""), 50}, - {types.NewQueryProposalsParams(1, 50, types.StatusVotingPeriod, "", ""), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusDepositPeriod, nil, nil), 50}, + {types.NewQueryProposalsParams(1, 50, types.StatusVotingPeriod, nil, nil), 50}, } for i, tc := range testCases { diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 7e8caf0a82..09e4162271 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) - err = sdk.ValidateAccAddress(deposit1.Depositor) + depositer1, err := sdk.AccAddressFromBech32(deposit1.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit1.ProposalId, sdk.AccAddress(deposit1.Depositor), deposit1.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit1.ProposalId, depositer1, 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) - err = sdk.ValidateAccAddress(deposit2.Depositor) + depositer2, err := sdk.AccAddressFromBech32(deposit2.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit2.ProposalId, sdk.AccAddress(deposit2.Depositor), deposit2.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit2.ProposalId, depositer2, 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) - err = sdk.ValidateAccAddress(deposit3.Depositor) + depositer3, err := sdk.AccAddressFromBech32(deposit3.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit3.ProposalId, sdk.AccAddress(deposit3.Depositor), deposit3.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit3.ProposalId, depositer3, 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) - err = sdk.ValidateAccAddress(deposit4.Depositor) + depositer4, err := sdk.AccAddressFromBech32(deposit4.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit4.ProposalId, sdk.AccAddress(deposit4.Depositor), deposit4.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit4.ProposalId, depositer4, 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) - err = sdk.ValidateAccAddress(deposit5.Depositor) + depositer5, err := sdk.AccAddressFromBech32(deposit5.Depositor) require.NoError(t, err) - _, err = app.GovKeeper.AddDeposit(ctx, deposit5.ProposalId, sdk.AccAddress(deposit5.Depositor), deposit5.Amount) + _, err = app.GovKeeper.AddDeposit(ctx, deposit5.ProposalId, depositer5, deposit5.Amount) require.NoError(t, err) proposal3.TotalDeposit = proposal3.TotalDeposit.Add(deposit5.Amount...) @@ -240,13 +240,12 @@ 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, "", "", types.StatusDepositPeriod, 1, 0) - + proposals := getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, 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, "", "", types.StatusVotingPeriod, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, types.StatusVotingPeriod, 1, 0) require.Len(t, proposals, 2) require.Equal(t, proposal2, proposals[0]) require.Equal(t, proposal3, proposals[1]) @@ -262,7 +261,7 @@ func TestQueries(t *testing.T) { app.GovKeeper.SetVote(ctx, vote3) // Test query voted by TestAddrs[0] - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, "", TestAddrs[0], types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, TestAddrs[0], types.StatusNil, 1, 0) require.Equal(t, proposal2, proposals[0]) require.Equal(t, proposal3, proposals[1]) @@ -281,21 +280,21 @@ func TestQueries(t *testing.T) { checkEqualVotes(t, vote3, votes[1]) // Test query all proposals - proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, "", "", types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, nil, 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, "", TestAddrs[1], types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, nil, 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], "", types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[0], nil, 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], "", types.StatusNil, 1, 0) + proposals = getQueriedProposals(t, ctx, legacyQuerierCdc, querier, TestAddrs[1], nil, types.StatusNil, 1, 0) require.Equal(t, proposal2.ProposalId, proposals[0].ProposalId) require.Equal(t, proposal3.ProposalId, proposals[1].ProposalId) @@ -320,10 +319,10 @@ func TestPaginatedVotesQuery(t *testing.T) { random := rand.New(rand.NewSource(time.Now().UnixNano())) addrMap := make(map[string]struct{}) genAddr := func() string { - addrBytes := make([]byte, 20) + addr := make(sdk.AccAddress, 20) for { - random.Read(addrBytes) - addrStr := sdk.BytesToAccAddress(addrBytes).String() + random.Read(addr) + addrStr := addr.String() if _, ok := addrMap[addrStr]; !ok { addrMap[addrStr] = struct{}{} return addrStr diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index fddf67515a..059e2a6020 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -35,21 +35,20 @@ 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 - voterBytes, err := sdk.AccAddressToBytes(vote.Voter) + voter, err := sdk.AccAddressFromBech32(vote.Voter) if err != nil { panic(err) } - valAddrStr := sdk.BytesToValAddress(voterBytes).String() + valAddrStr := sdk.ValAddress(voter.Bytes()).String() if val, ok := currValidators[valAddrStr]; ok { val.Vote = vote.Options currValidators[valAddrStr] = val } // iterate over all delegations from voter, deduct from any delegated-to validators - keeper.sk.IterateDelegations(ctx, sdk.AccAddress(vote.Voter), func(index int64, - delegation stakingtypes.DelegationI) (stop bool) { + keeper.sk.IterateDelegations(ctx, voter, func(index int64, delegation stakingtypes.DelegationI) (stop bool) { valAddrStr := delegation.GetValidatorAddr().String() if val, ok := currValidators[valAddrStr]; ok { @@ -71,7 +70,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes boo return false }) - keeper.deleteVote(ctx, vote.ProposalId, sdk.AccAddress(vote.Voter)) + keeper.deleteVote(ctx, vote.ProposalId, voter) return false }) diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index e230858801..ba21865d64 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, ocproto.Header{}) - createValidators(t, ctx, app, []int64{5, 2, 0}) // validators order was changed since using address string + createValidators(t, ctx, app, []int64{2, 5, 0}) 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, ocproto.Header{}) - valAccAddrs, _ := createValidators(t, ctx, app, []int64{6, 5, 0}) + valAccAddrs, _ := createValidators(t, ctx, app, []int64{5, 6, 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.NewNonSplitVoteOption(types.OptionNo))) - require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.NewNonSplitVoteOption(types.OptionYes))) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[0], types.NewNonSplitVoteOption(types.OptionYes))) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.NewNonSplitVoteOption(types.OptionNo))) 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, ocproto.Header{}) - valAccAddrs, _ := createValidators(t, ctx, app, []int64{6, 5, 0}) + valAccAddrs, _ := createValidators(t, ctx, app, []int64{5, 6, 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.NewNonSplitVoteOption(types.OptionYes))) - require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.NewNonSplitVoteOption(types.OptionNo))) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[0], types.NewNonSplitVoteOption(types.OptionNo))) + require.NoError(t, app.GovKeeper.AddVote(ctx, proposalID, valAccAddrs[1], types.NewNonSplitVoteOption(types.OptionYes))) 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, consAddr) + app.StakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr.Bytes())) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp) diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index ea6127b526..9770611d5a 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -84,7 +84,10 @@ func (keeper Keeper) SetVote(ctx sdk.Context, vote types.Vote) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshal(&vote) - addr := sdk.AccAddress(vote.Voter) + addr, err := sdk.AccAddressFromBech32(vote.Voter) + if err != nil { + panic(err) + } store.Set(types.VoteKey(vote.ProposalId, addr), bz) } diff --git a/x/gov/legacy/v043/json_test.go b/x/gov/legacy/v043/json_test.go index 84e50818b4..82a54a0d22 100644 --- a/x/gov/legacy/v043/json_test.go +++ b/x/gov/legacy/v043/json_test.go @@ -21,8 +21,7 @@ func TestMigrateJSON(t *testing.T) { WithTxConfig(encodingConfig.TxConfig). WithCodec(encodingConfig.Marshaler) - voter := sdk.AccAddress("link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3q4fdzl") - err := sdk.ValidateAccAddress(voter.String()) + voter, err := sdk.AccAddressFromBech32("link1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3q4fdzl") require.NoError(t, err) govGenState := &types.GenesisState{ Votes: types.Votes{ diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 7cb28ebf57..59f30a7aca 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.BytesToAccAddress(delPk1.Address()) + delAddr1 = sdk.AccAddress(delPk1.Address()) ) func TestDecodeStore(t *testing.T) { diff --git a/x/gov/types/keys_test.go b/x/gov/types/keys_test.go index 3fe829e492..30d42b5dba 100644 --- a/x/gov/types/keys_test.go +++ b/x/gov/types/keys_test.go @@ -10,7 +10,7 @@ import ( sdk "github.com/line/lbm-sdk/types" ) -var addr = sdk.BytesToAccAddress(ed25519.GenPrivKey().PubKey().Address()) +var addr = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) func TestProposalKeys(t *testing.T) { // key proposal diff --git a/x/gov/types/msgs.go b/x/gov/types/msgs.go index c7f0c1396c..b0c9a9f1be 100644 --- a/x/gov/types/msgs.go +++ b/x/gov/types/msgs.go @@ -42,7 +42,8 @@ func NewMsgSubmitProposal(content Content, initialDeposit sdk.Coins, proposer sd func (m *MsgSubmitProposal) GetInitialDeposit() sdk.Coins { return m.InitialDeposit } func (m *MsgSubmitProposal) GetProposer() sdk.AccAddress { - return sdk.AccAddress(m.Proposer) + proposer, _ := sdk.AccAddressFromBech32(m.Proposer) + return proposer } func (m *MsgSubmitProposal) GetContent() Content { @@ -91,9 +92,6 @@ 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 { @@ -117,7 +115,8 @@ func (m MsgSubmitProposal) GetSignBytes() []byte { // GetSigners implements Msg func (m MsgSubmitProposal) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(m.Proposer)} + proposer, _ := sdk.AccAddressFromBech32(m.Proposer) + return []sdk.AccAddress{proposer} } // String implements the Stringer interface @@ -149,9 +148,6 @@ 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()) } @@ -176,7 +172,8 @@ func (msg MsgDeposit) GetSignBytes() []byte { // GetSigners implements Msg func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(msg.Depositor)} + depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) + return []sdk.AccAddress{depositor} } // NewMsgVote creates a message to cast a vote on an active proposal @@ -196,6 +193,7 @@ func (msg MsgVote) ValidateBasic() error { if msg.Voter == "" { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Voter) } + if !ValidVoteOption(msg.Option) { return sdkerrors.Wrap(ErrInvalidVote, msg.Option.String()) } @@ -217,7 +215,8 @@ func (msg MsgVote) GetSignBytes() []byte { // GetSigners implements Msg func (msg MsgVote) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(msg.Voter)} + voter, _ := sdk.AccAddressFromBech32(msg.Voter) + return []sdk.AccAddress{voter} } // NewMsgVoteWeighted creates a message to cast a vote on an active proposal @@ -280,5 +279,6 @@ func (msg MsgVoteWeighted) GetSignBytes() []byte { // GetSigners implements Msg func (msg MsgVoteWeighted) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.AccAddress(msg.Voter)} + voter, _ := sdk.AccAddressFromBech32(msg.Voter) + return []sdk.AccAddress{voter} } diff --git a/x/gov/types/msgs_test.go b/x/gov/types/msgs_test.go index 54489c8cde..cf744c27b6 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.BytesToAccAddress([]byte(" test1")), - sdk.BytesToAccAddress([]byte(" test2")), + sdk.AccAddress([]byte(" test1")), + sdk.AccAddress([]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, "", 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, 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.BytesToAccAddress([]byte("addr1")) + addr := sdk.AccAddress("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, "", coinsPos, false}, + {1, sdk.AccAddress{}, 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, "", OptionYes, false}, + {0, sdk.AccAddress{}, OptionYes, false}, {0, addrs[0], OptionNo, true}, {0, addrs[0], OptionNoWithVeto, true}, {0, addrs[0], OptionAbstain, true}, @@ -127,7 +127,7 @@ func TestMsgVoteWeighted(t *testing.T) { expectPass bool }{ {0, addrs[0], NewNonSplitVoteOption(OptionYes), true}, - {0, "", NewNonSplitVoteOption(OptionYes), false}, + {0, sdk.AccAddress{}, NewNonSplitVoteOption(OptionYes), false}, {0, addrs[0], NewNonSplitVoteOption(OptionNo), true}, {0, addrs[0], NewNonSplitVoteOption(OptionNoWithVeto), true}, {0, addrs[0], NewNonSplitVoteOption(OptionAbstain), true}, @@ -164,7 +164,7 @@ func TestMsgVoteWeighted(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(), "") + msg, err := NewMsgSubmitProposal(NewTextProposal("test", "abcd"), sdk.NewCoins(), sdk.AccAddress{}) require.NoError(t, err) var bz []byte require.NotPanics(t, func() { diff --git a/x/ibc/applications/transfer/keeper/keeper_test.go b/x/ibc/applications/transfer/keeper/keeper_test.go index f8109eb3d8..f258690033 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.BytesToAccAddress(crypto.AddressHash([]byte(types.ModuleName))) + expectedMaccAddr := sdk.AccAddress(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 330d827592..9e53745479 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.BytesToAccAddress(crypto.AddressHash([]byte(address))).String() + return sdk.AccAddress(crypto.AddressHash([]byte(address))).String() } func AddressFromTla(addr []string) string { @@ -324,7 +324,8 @@ func (suite *KeeperTestSuite) TestModelBasedRelay() { } switch tc.handler { case "SendTransfer": - err = sdk.ValidateAccAddress(tc.packet.Data.Sender) + var sender sdk.AccAddress + sender, err = sdk.AccAddressFromBech32(tc.packet.Data.Sender) if err != nil { panic("MBT failed to convert sender address") } @@ -338,7 +339,7 @@ func (suite *KeeperTestSuite) TestModelBasedRelay() { tc.packet.SourcePort, tc.packet.SourceChannel, sdk.NewCoin(denom, sdk.NewIntFromUint64(tc.packet.Data.Amount)), - sdk.AccAddress(tc.packet.Data.Sender), + 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 5afc0f4720..ae033f689d 100644 --- a/x/ibc/applications/transfer/keeper/msg_server.go +++ b/x/ibc/applications/transfer/keeper/msg_server.go @@ -15,13 +15,12 @@ var _ types.MsgServer = Keeper{} func (k Keeper) Transfer(goCtx context.Context, msg *types.MsgTransfer) (*types.MsgTransferResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Sender) + sender, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, err } if err := k.SendTransfer( - ctx, msg.SourcePort, msg.SourceChannel, msg.Token, sdk.AccAddress(msg.Sender), - msg.Receiver, msg.TimeoutHeight, msg.TimeoutTimestamp, + ctx, msg.SourcePort, msg.SourceChannel, msg.Token, 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 cb014cb3f3..51e5f12f1e 100644 --- a/x/ibc/applications/transfer/keeper/relay.go +++ b/x/ibc/applications/transfer/keeper/relay.go @@ -195,7 +195,7 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t } // decode the receiver address - err := sdk.ValidateAccAddress(data.Receiver) + receiver, err := sdk.AccAddressFromBech32(data.Receiver) if err != nil { return err } @@ -233,7 +233,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, sdk.AccAddress(data.Receiver), sdk.NewCoins(token)); err != nil { + if err := k.bankKeeper.SendCoins(ctx, escrowAddress, 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 @@ -295,7 +295,7 @@ func (k Keeper) OnRecvPacket(ctx sdk.Context, packet channeltypes.Packet, data t // send to receiver if err := k.bankKeeper.SendCoinsFromModuleToAccount( - ctx, types.ModuleName, sdk.AccAddress(data.Receiver), sdk.NewCoins(voucher), + ctx, types.ModuleName, 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)) } @@ -353,7 +353,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 - err := sdk.ValidateAccAddress(data.Sender) + sender, err := sdk.AccAddressFromBech32(data.Sender) if err != nil { return err } @@ -361,7 +361,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, sdk.AccAddress(data.Sender), sdk.NewCoins(token)); err != nil { + if err := k.bankKeeper.SendCoins(ctx, escrowAddress, 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 @@ -379,7 +379,7 @@ func (k Keeper) refundPacketToken(ctx sdk.Context, packet channeltypes.Packet, d return err } - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, sdk.AccAddress(data.Sender), sdk.NewCoins(token)); err != nil { + if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, 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 420d261762..633f87a86d 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 sdk.BytesToAccAddress(hash[:20]) + return hash[:20] } diff --git a/x/ibc/applications/transfer/types/msgs.go b/x/ibc/applications/transfer/types/msgs.go index e94a154a30..f4ef7144b4 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.ValidateAccAddress(msg.Sender) + _, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -77,6 +77,9 @@ func (msg MsgTransfer) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgTransfer) GetSigners() []sdk.AccAddress { - valAddr := sdk.AccAddress(msg.Sender) + valAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + panic(err) + } 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 ba1c6a3079..171e4c814d 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.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr1 = sdk.AccAddress(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 55e8d2a9c5..adaee9151a 100644 --- a/x/ibc/core/02-client/keeper/keeper_test.go +++ b/x/ibc/core/02-client/keeper/keeper_test.go @@ -105,7 +105,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.Require().NoError(err) pk, err := cryptocodec.FromOcPubKeyInterface(tmPk) suite.Require().NoError(err) - val, err := stakingtypes.NewValidator(sdk.BytesToValAddress(pk.Address()), pk, stakingtypes.Description{}) + val, err := stakingtypes.NewValidator(sdk.ValAddress(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 8db4ea8307..1436ded1a3 100644 --- a/x/ibc/core/02-client/types/msgs.go +++ b/x/ibc/core/02-client/types/msgs.go @@ -63,6 +63,10 @@ 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 @@ -83,9 +87,6 @@ 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() } @@ -97,7 +98,10 @@ func (msg MsgCreateClient) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgCreateClient) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{accAddr} } @@ -140,6 +144,10 @@ 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 @@ -150,9 +158,6 @@ 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) } @@ -164,7 +169,10 @@ func (msg MsgUpdateClient) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgUpdateClient) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{accAddr} } @@ -232,7 +240,8 @@ func (msg MsgUpgradeClient) ValidateBasic() error { if len(msg.ProofUpgradeConsensusState) == 0 { return sdkerrors.Wrap(ErrInvalidUpgradeClient, "proof of upgrade consensus state cannot be empty") } - if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + _, err = sdk.AccAddressFromBech32(msg.Signer) + if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return host.ClientIdentifierValidator(msg.ClientId) @@ -246,7 +255,10 @@ func (msg MsgUpgradeClient) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgUpgradeClient) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{accAddr} } @@ -287,6 +299,10 @@ 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 @@ -301,9 +317,6 @@ 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) } @@ -316,7 +329,10 @@ func (msg MsgSubmitMisbehaviour) GetSignBytes() []byte { // GetSigners returns the single expected signer for a MsgSubmitMisbehaviour. func (msg MsgSubmitMisbehaviour) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } 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 868dda1880..1f59d199df 100644 --- a/x/ibc/core/03-connection/types/msgs.go +++ b/x/ibc/core/03-connection/types/msgs.go @@ -64,7 +64,8 @@ func (msg MsgConnectionOpenInit) ValidateBasic() error { return sdkerrors.Wrap(err, "basic validation of the provided version failed") } } - if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + _, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return msg.Counterparty.ValidateBasic() @@ -78,7 +79,10 @@ func (msg MsgConnectionOpenInit) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenInit) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{accAddr} } @@ -168,7 +172,8 @@ func (msg MsgConnectionOpenTry) ValidateBasic() error { if msg.ConsensusHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "consensus height must be non-zero") } - if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + _, err = sdk.AccAddressFromBech32(msg.Signer) + if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return msg.Counterparty.ValidateBasic() @@ -187,7 +192,10 @@ func (msg MsgConnectionOpenTry) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenTry) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{accAddr} } @@ -266,7 +274,8 @@ func (msg MsgConnectionOpenAck) ValidateBasic() error { if msg.ConsensusHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "consensus height must be non-zero") } - if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + _, err = sdk.AccAddressFromBech32(msg.Signer) + if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return nil @@ -280,7 +289,10 @@ func (msg MsgConnectionOpenAck) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenAck) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{accAddr} } @@ -319,7 +331,8 @@ func (msg MsgConnectionOpenConfirm) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - if err := sdk.ValidateAccAddress(msg.Signer); err != nil { + _, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } return nil @@ -333,6 +346,9 @@ func (msg MsgConnectionOpenConfirm) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgConnectionOpenConfirm) GetSigners() []sdk.AccAddress { - accAddr := sdk.AccAddress(msg.Signer) + accAddr, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } 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 82dd77c349..923348b35b 100644 --- a/x/ibc/core/03-connection/types/msgs_test.go +++ b/x/ibc/core/03-connection/types/msgs_test.go @@ -78,7 +78,7 @@ func TestMsgTestSuite(t *testing.T) { func (suite *MsgTestSuite) TestNewMsgConnectionOpenInit() { prefix := commitmenttypes.NewMerklePrefix([]byte("storePrefixKey")) - signer := sdk.AccAddress("link1kerpa33qxdwvrgms5qr7xegfxnewzm6s46ce7t") + signer, _ := sdk.AccAddressFromBech32("link1kerpa33qxdwvrgms5qr7xegfxnewzm6s46ce7t") // empty versions are considered valid, the default compatible versions // will be used in protocol. var version *types.Version @@ -93,7 +93,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, ""), false}, + {"empty singer", types.NewMsgConnectionOpenInit("clienttotest", "clienttotest", prefix, version, 500, nil), false}, {"success", types.NewMsgConnectionOpenInit("clienttotest", "clienttotest", prefix, version, 500, signer), true}, } @@ -109,7 +109,7 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenInit() { func (suite *MsgTestSuite) TestNewMsgConnectionOpenTry() { prefix := commitmenttypes.NewMerklePrefix([]byte("storePrefixKey")) - signer := sdk.AccAddress("link10czqumeld9k6dm32ud0xpqs0kn4m6xtrxy024r") + signer, _ := sdk.AccAddressFromBech32("link10czqumeld9k6dm32ud0xpqs0kn4m6xtrxy024r") clientState := ibctmtypes.NewClientState( chainID, ibctmtypes.DefaultTrustLevel, ibctesting.TrustingPeriod, ibctesting.UnbondingPeriod, ibctesting.MaxClockDrift, clientHeight, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath, false, false, @@ -147,7 +147,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, ""), 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}, {"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}, } @@ -163,7 +163,7 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenTry() { } func (suite *MsgTestSuite) TestNewMsgConnectionOpenAck() { - signer := sdk.AccAddress("link1amsfdt72u7ysc8542p0mmafq9ys8c7qxh74wf5") + signer, _ := sdk.AccAddressFromBech32("link1amsfdt72u7ysc8542p0mmafq9ys8c7qxh74wf5") clientState := ibctmtypes.NewClientState( chainID, ibctmtypes.DefaultTrustLevel, ibctesting.TrustingPeriod, ibctesting.UnbondingPeriod, ibctesting.MaxClockDrift, clientHeight, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath, false, false, ) @@ -196,7 +196,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, ""), false}, + {"empty signer", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, ibctesting.ConnectionVersion, nil), false}, {"success", types.NewMsgConnectionOpenAck(connectionID, connectionID, clientState, suite.proof, suite.proof, suite.proof, clientHeight, clientHeight, ibctesting.ConnectionVersion, signer), true}, } @@ -211,13 +211,13 @@ func (suite *MsgTestSuite) TestNewMsgConnectionOpenAck() { } func (suite *MsgTestSuite) TestNewMsgConnectionOpenConfirm() { - signer := sdk.AccAddress("link1ptg03mk43x5qcp9xnankk7cwt4vzrkpxqpcff3") + signer, _ := sdk.AccAddressFromBech32("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, ""), + types.NewMsgConnectionOpenConfirm(connectionID, suite.proof, clientHeight, nil), 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 e80c8016d3..efa3f6d1cc 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.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -67,7 +67,10 @@ func (msg MsgChannelOpenInit) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenInit) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -130,7 +133,7 @@ func (msg MsgChannelOpenTry) ValidateBasic() error { return sdkerrors.Wrap(err, "invalid counterparty channel ID") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -145,7 +148,10 @@ func (msg MsgChannelOpenTry) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenTry) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -195,7 +201,7 @@ func (msg MsgChannelOpenAck) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -210,7 +216,10 @@ func (msg MsgChannelOpenAck) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenAck) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -255,7 +264,7 @@ func (msg MsgChannelOpenConfirm) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -270,7 +279,10 @@ func (msg MsgChannelOpenConfirm) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelOpenConfirm) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -306,7 +318,7 @@ func (msg MsgChannelCloseInit) ValidateBasic() error { if !IsValidChannelID(msg.ChannelId) { return ErrInvalidChannelIdentifier } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -321,7 +333,10 @@ func (msg MsgChannelCloseInit) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelCloseInit) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -366,7 +381,7 @@ func (msg MsgChannelCloseConfirm) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -381,7 +396,10 @@ func (msg MsgChannelCloseConfirm) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgChannelCloseConfirm) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -414,7 +432,7 @@ func (msg MsgRecvPacket) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -436,7 +454,10 @@ func (msg MsgRecvPacket) GetDataSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgRecvPacket) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -478,7 +499,7 @@ func (msg MsgTimeout) ValidateBasic() error { if msg.NextSequenceRecv == 0 { return sdkerrors.Wrap(sdkerrors.ErrInvalidSequence, "next sequence receive cannot be 0") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -493,7 +514,10 @@ func (msg MsgTimeout) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgTimeout) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -538,7 +562,7 @@ func (msg MsgTimeoutOnClose) ValidateBasic() error { if msg.ProofHeight.IsZero() { return sdkerrors.Wrap(sdkerrors.ErrInvalidHeight, "proof height must be non-zero") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -553,7 +577,10 @@ func (msg MsgTimeoutOnClose) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgTimeoutOnClose) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } return []sdk.AccAddress{signer} } @@ -597,7 +624,7 @@ func (msg MsgAcknowledgement) ValidateBasic() error { if len(msg.Acknowledgement) == 0 { return sdkerrors.Wrap(ErrInvalidAcknowledgement, "ack bytes cannot be empty") } - err := sdk.ValidateAccAddress(msg.Signer) + _, err := sdk.AccAddressFromBech32(msg.Signer) if err != nil { return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "string could not be parsed as address: %v", err) } @@ -612,7 +639,10 @@ func (msg MsgAcknowledgement) GetSignBytes() []byte { // GetSigners implements sdk.Msg func (msg MsgAcknowledgement) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(msg.Signer) + signer, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + panic(err) + } 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 db2388d958..2290bbdced 100644 --- a/x/ibc/core/04-channel/types/msgs_test.go +++ b/x/ibc/core/04-channel/types/msgs_test.go @@ -60,7 +60,7 @@ var ( invalidProofs1 = exported.Proof(nil) invalidProofs2 = emptyProof - addr = sdk.BytesToAccAddress([]byte("testaddr111111111111")) + addr = sdk.AccAddress("testaddr111111111111") emptyAddr sdk.AccAddress connHops = []string{"testconnection"} @@ -354,7 +354,7 @@ func (suite *TypesTestSuite) TestMsgRecvPacketGetSigners() { msg := types.NewMsgRecvPacket(packet, suite.proof, height, addr) res := msg.GetSigners() - expected := "[6C696E6B3177336A687861727076336A38797666337879636E7A7666337879636E7A7666336339777A7374]" + expected := "[7465737461646472313131313131313131313131]" suite.Equal(expected, fmt.Sprintf("%v", res)) } diff --git a/x/ibc/testing/chain.go b/x/ibc/testing/chain.go index f74ea600fb..3e126e28a8 100644 --- a/x/ibc/testing/chain.go +++ b/x/ibc/testing/chain.go @@ -133,7 +133,7 @@ func NewTestChain(t *testing.T, chainID string) *TestChain { // generate genesis account senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(sdk.BytesToAccAddress(senderPrivKey.PubKey().Address()), senderPrivKey.PubKey(), 0, 0) + acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) balance := banktypes.Balance{ Address: acc.GetAddress().String(), Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), diff --git a/x/slashing/abci_test.go b/x/slashing/abci_test.go index a43f778a67..e264e8e9b9 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, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - addr, pk := sdk.BytesToValAddress(pks[0].Address()), pks[0] + addr, pk := sdk.ValAddress(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, addr.ToAccAddress()), + t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))), ) require.Equal(t, amt, app.StakingKeeper.Validator(ctx, addr).GetBondedTokens()) @@ -53,7 +53,7 @@ func TestBeginBlocker(t *testing.T) { slashing.BeginBlocker(ctx, req, app.SlashingKeeper) - info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(pk.Address())) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(pk.Address())) require.True(t, found) require.Equal(t, int64(1), info.VoterSetCounter) require.Equal(t, time.Unix(0, 0).UTC(), info.JailedUntil) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 51234f3097..5304b2b1de 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -20,15 +20,15 @@ import ( var ( priv1 = secp256k1.GenPrivKey() - addr1 = sdk.BytesToAccAddress(priv1.PubKey().Address()) + addr1 = sdk.AccAddress(priv1.PubKey().Address()) valKey = ed25519.GenPrivKey() - valAddr = sdk.BytesToAccAddress(valKey.PubKey().Address()) + valAddr = sdk.AccAddress(valKey.PubKey().Address()) ) func checkValidator(t *testing.T, app *simapp.SimApp, _ sdk.AccAddress, expFound bool) stakingtypes.Validator { ctxCheck := app.BaseApp.NewContext(true, ocproto.Header{}) - validator, found := app.StakingKeeper.GetValidator(ctxCheck, addr1.ToValAddress()) + validator, found := app.StakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1)) 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( - addr1.ToValAddress(), valKey.PubKey(), bondCoin, description, commission, sdk.OneInt(), + sdk.ValAddress(addr1), 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, addr1.ToValAddress().String(), validator.OperatorAddress) + require.Equal(t, sdk.ValAddress(addr1).String(), validator.OperatorAddress) require.Equal(t, stakingtypes.Bonded, validator.Status) require.True(sdk.IntEq(t, bondTokens, validator.BondedTokens())) - unjailMsg := &types.MsgUnjail{ValidatorAddr: addr1.ToValAddress().String()} + unjailMsg := &types.MsgUnjail{ValidatorAddr: sdk.ValAddress(addr1).String()} - checkValidatorSigningInfo(t, app, valAddr.ToConsAddress(), true) + checkValidatorSigningInfo(t, app, sdk.ConsAddress(valAddr), true) // unjail should fail with unknown validator header = ocproto.Header{Height: app.LastBlockHeight() + 1} diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index 4de6cd43d5..42adfa2b87 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -55,7 +55,7 @@ $ query slashing signing-info '{"@type":"/cosmos.crypto.ed25519.PubKey"," } queryClient := types.NewQueryClient(clientCtx) - consAddr := sdk.BytesToConsAddress(pk.Address()) + consAddr := sdk.ConsAddress(pk.Address()) params := &types.QuerySigningInfoRequest{ConsAddress: consAddr.String()} res, err := queryClient.SigningInfo(cmd.Context(), params) if err != nil { diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index c692bc019c..2d2df130ac 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -6,6 +6,7 @@ import ( "github.com/line/lbm-sdk/client" "github.com/line/lbm-sdk/client/flags" "github.com/line/lbm-sdk/client/tx" + sdk "github.com/line/lbm-sdk/types" "github.com/line/lbm-sdk/x/slashing/types" ) @@ -39,7 +40,7 @@ $ tx slashing unjail --from mykey } valAddr := clientCtx.GetFromAddress() - msg := types.NewMsgUnjail(valAddr.ToValAddress()) + msg := types.NewMsgUnjail(sdk.ValAddress(valAddr)) return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, diff --git a/x/slashing/client/rest/grpc_query_test.go b/x/slashing/client/rest/grpc_query_test.go index 80b1cb2c02..68acd5b721 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.BytesToConsAddress(val.PubKey.Address()).String() + consAddr := sdk.ConsAddress(val.PubKey.Address()).String() testCases := []struct { name string @@ -66,7 +66,7 @@ func (s *IntegrationTestSuite) TestGRPCQueries() { &types.QuerySigningInfosResponse{ Info: []types.ValidatorSigningInfo{ { - Address: sdk.BytesToConsAddress(val.PubKey.Address()).String(), + Address: sdk.ConsAddress(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.BytesToConsAddress(val.PubKey.Address()).String(), + Address: sdk.ConsAddress(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 424d9562da..73a18605e6 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.AccAddressToBytes(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) if rest.CheckBadRequestError(w, err) { return } - valAddr, err := sdk.ValAddressToBytes(bech32Validator) + valAddr, err := sdk.ValAddressFromBech32(bech32Validator) if rest.CheckInternalServerError(w, err) { return } @@ -54,7 +54,7 @@ func NewUnjailRequestHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - msg := types.NewMsgUnjail(sdk.ValAddress(bech32Validator)) + msg := types.NewMsgUnjail(valAddr) if rest.CheckBadRequestError(w, msg.ValidateBasic()) { return } diff --git a/x/slashing/client/testutil/suite.go b/x/slashing/client/testutil/suite.go index a17be423f8..8b3d6a4373 100644 --- a/x/slashing/client/testutil/suite.go +++ b/x/slashing/client/testutil/suite.go @@ -65,7 +65,7 @@ func (s *IntegrationTestSuite) TestGetCmdQuerySigningInfo() { fmt.Sprintf("--%s=1", flags.FlagHeight), }, false, - fmt.Sprintf("{\"address\":\"%s\",\"jailed_until\":\"1970-01-01T00:00:00Z\",\"tombstoned\":false,\"missed_blocks_counter\":\"0\",\"voter_set_counter\":\"0\"}", sdk.BytesToConsAddress(val.PubKey.Address())), + fmt.Sprintf("{\"address\":\"%s\",\"jailed_until\":\"1970-01-01T00:00:00Z\",\"tombstoned\":false,\"missed_blocks_counter\":\"0\",\"voter_set_counter\":\"0\"}", sdk.ConsAddress(val.PubKey.Address())), }, { "valid address (text output)", @@ -79,7 +79,7 @@ func (s *IntegrationTestSuite) TestGetCmdQuerySigningInfo() { jailed_until: "1970-01-01T00:00:00Z" missed_blocks_counter: "0" tombstoned: false -voter_set_counter: "0"`, sdk.BytesToConsAddress(val.PubKey.Address())), +voter_set_counter: "0"`, sdk.ConsAddress(val.PubKey.Address())), }, } diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index e3aba1a609..7e8704d011 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -22,12 +22,18 @@ func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, stakingKeeper types.Stak ) for _, info := range data.SigningInfos { - address := sdk.ConsAddress(info.Address) + address, err := sdk.ConsAddressFromBech32(info.Address) + if err != nil { + panic(err) + } keeper.SetValidatorSigningInfo(ctx, address, info.ValidatorSigningInfo) } for _, array := range data.MissedBlocks { - address := sdk.ConsAddress(array.Address) + address, err := sdk.ConsAddressFromBech32(array.Address) + if err != nil { + panic(err) + } 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 f8ee6ae373..789464be72 100644 --- a/x/slashing/genesis_test.go +++ b/x/slashing/genesis_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/line/lbm-sdk/simapp" + sdk "github.com/line/lbm-sdk/types" "github.com/line/lbm-sdk/x/slashing" "github.com/line/lbm-sdk/x/slashing/testslashing" "github.com/line/lbm-sdk/x/slashing/types" @@ -20,13 +21,13 @@ func TestExportAndInitGenesis(t *testing.T) { app.SlashingKeeper.SetParams(ctx, testslashing.TestParams()) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - info1 := types.NewValidatorSigningInfo(addrDels[0].ToConsAddress(), + info1 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), time.Now().UTC().Add(100000000000), false, int64(10), int64(3)) - info2 := types.NewValidatorSigningInfo(addrDels[1].ToConsAddress(), + info2 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), time.Now().UTC().Add(10000000000), false, int64(10), int64(4)) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), info1) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[1].ToConsAddress(), info2) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), info1) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1]), info2) genesisState := slashing.ExportGenesis(ctx, app.SlashingKeeper) require.Equal(t, genesisState.Params, testslashing.TestParams()) @@ -34,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, addrDels[0].ToConsAddress()) - app.SlashingKeeper.Tombstone(ctx, addrDels[1].ToConsAddress()) + app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[0])) + app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[1])) - ok := app.SlashingKeeper.IsTombstoned(ctx, addrDels[0].ToConsAddress()) + ok := app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0])) require.True(t, ok) - newInfo1, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) + newInfo1, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) 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, addrDels[0].ToConsAddress()) + ok = app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0])) require.False(t, ok) - newInfo1, ok = app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) - newInfo2, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[1].ToConsAddress()) + newInfo1, ok = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + newInfo2, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1])) 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 3dd4d348d8..b22af60e0e 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.BytesToValAddress(pks[0].Address()), pks[0] + addr, val := sdk.ValAddress(pks[0].Address()), pks[0] amt := tstaking.CreateValidatorWithValPower(addr, val, 100, true) staking.EndBlocker(ctx, app.StakingKeeper) require.Equal( - t, app.BankKeeper.GetAllBalances(ctx, addr.ToAccAddress()), + t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), 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.BytesToValAddress(pks[0].Address()), pks[0] + addr, val := sdk.ValAddress(pks[0].Address()), pks[0] amt := app.StakingKeeper.TokensFromConsensusPower(ctx, 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, addr.ToAccAddress()), + t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), sdk.Coins{sdk.NewCoin(app.StakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))}, ) - tstaking.Undelegate(addr.ToAccAddress(), addr, sdk.OneInt(), true) + tstaking.Undelegate(sdk.AccAddress(addr), 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.BytesToValAddress(pks[1].Address()), sdk.BytesToConsAddress(pks[0].Address()) + valAddr, consAddr := sdk.ValAddress(pks[1].Address()), sdk.ConsAddress(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.BytesToAccAddress(pks[2].Address()) + delAddr := sdk.AccAddress(pks[2].Address()) tstaking.Delegate(delAddr, valAddr, amt) // unbond validator total self-delegations (which should jail the validator) - valAcc := valAddr.ToAccAddress() + valAcc := sdk.AccAddress(valAddr) tstaking.Undelegate(valAcc, valAddr, amt, true) - _, err := app.StakingKeeper.CompleteUnbonding(ctx, valAcc, valAddr) + _, err := app.StakingKeeper.CompleteUnbonding(ctx, sdk.AccAddress(valAddr), 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.BytesToValAddress(pks[0].Address()), pks[0] + addr, val := sdk.ValAddress(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, addr.ToAccAddress()), + t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), 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.BytesToConsAddress(val.Address())) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.VoterSetCounter) require.Equal(t, int64(0), info.MissedBlocksCounter) @@ -175,7 +175,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.BytesToConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(1000), info.VoterSetCounter) require.Equal(t, int64(0), info.MissedBlocksCounter) @@ -185,7 +185,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.BytesToConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(1500), info.VoterSetCounter) require.Equal(t, app.SlashingKeeper.SignedBlocksWindow(ctx)-app.SlashingKeeper.MinSignedPerWindow(ctx), info.MissedBlocksCounter) @@ -200,7 +200,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.BytesToConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(1501), info.VoterSetCounter) // counter now reset to zero @@ -222,7 +222,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.BytesToConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(1502), info.VoterSetCounter) require.Equal(t, int64(1), info.MissedBlocksCounter) @@ -256,7 +256,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 voter set counter should not have been changed - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.BytesToConsAddress(val.Address())) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(1502), info.VoterSetCounter) // 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 acae75d114..c21136d79d 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -34,7 +34,10 @@ func (k Keeper) SigningInfo(c context.Context, req *types.QuerySigningInfoReques return nil, status.Errorf(codes.InvalidArgument, "invalid request") } - consAddr := sdk.ConsAddress(req.ConsAddress) + consAddr, err := sdk.ConsAddressFromBech32(req.ConsAddress) + if err != nil { + return nil, err + } 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 7067b18300..fc508510ef 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, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - info1 := types.NewValidatorSigningInfo(addrDels[0].ToConsAddress(), + info1 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), time.Unix(2, 0), false, int64(10), int64(3)) - info2 := types.NewValidatorSigningInfo(addrDels[1].ToConsAddress(), + info2 := types.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), time.Unix(2, 0), false, int64(10), int64(4)) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), info1) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[1].ToConsAddress(), info2) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), info1) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1]), info2) suite.app = app suite.ctx = ctx @@ -70,7 +70,7 @@ func (suite *SlashingTestSuite) TestGRPCSigningInfo() { suite.Error(err) suite.Nil(infoResp) - consAddr := suite.addrDels[0].ToConsAddress() + consAddr := sdk.ConsAddress(suite.addrDels[0]) info, found := suite.app.SlashingKeeper.GetValidatorSigningInfo(suite.ctx, consAddr) suite.True(found) diff --git a/x/slashing/keeper/hooks.go b/x/slashing/keeper/hooks.go index 368ae24702..b35d262ecf 100644 --- a/x/slashing/keeper/hooks.go +++ b/x/slashing/keeper/hooks.go @@ -3,6 +3,8 @@ package keeper import ( "time" + "github.com/line/ostracon/crypto" + sdk "github.com/line/lbm-sdk/types" "github.com/line/lbm-sdk/x/slashing/types" ) @@ -36,8 +38,7 @@ func (k Keeper) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) e // AfterValidatorRemoved deletes the address-pubkey relation when a validator is removed, func (k Keeper) AfterValidatorRemoved(ctx sdk.Context, address sdk.ConsAddress) { - addrBytes, _ := sdk.ConsAddressToBytes(address.String()) - k.deleteAddrPubkeyRelation(ctx, addrBytes) + k.deleteAddrPubkeyRelation(ctx, crypto.Address(address)) } // Hooks wrapper struct for slashing keeper diff --git a/x/slashing/keeper/infractions.go b/x/slashing/keeper/infractions.go index 683cacdf32..b84382c2c8 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.BytesToConsAddress(addr) + consAddr := sdk.ConsAddress(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 f44f4390e8..5ea3f49e54 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.BytesToConsAddress(a)) + return nil, fmt.Errorf("address %s not found", sdk.ConsAddress(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 a1c4209622..84ee18158d 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(addr.ToAccAddress(), addr, app.StakingKeeper.TokensFromConsensusPower(ctx, 1), true) + tstaking.Undelegate(sdk.AccAddress(addr), addr, app.StakingKeeper.TokensFromConsensusPower(ctx, 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(addr.ToAccAddress(), addr, 1) + tstaking.DelegateWithPower(sdk.AccAddress(addr), 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, addr.ToAccAddress()), + t, app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)), 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.BytesToConsAddress(val.Address())) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(2), info.VoterSetCounter) require.Equal(t, int64(1), info.MissedBlocksCounter) @@ -190,9 +190,9 @@ func TestValidatorDippingInAndOut(t *testing.T) { simapp.AddTestAddrsFromPubKeys(app, ctx, pks, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) addr, val := pks[0].Address(), pks[0] - consAddr := sdk.BytesToConsAddress(addr) + consAddr := sdk.ConsAddress(addr) tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) - valAddr := sdk.BytesToValAddress(addr) + valAddr := sdk.ValAddress(addr) tstaking.CreateValidatorWithValPower(valAddr, val, power, true) staking.EndBlocker(ctx, app.StakingKeeper) @@ -205,7 +205,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { } // kick first validator out of validator set - tstaking.CreateValidatorWithValPower(sdk.BytesToValAddress(pks[1].Address()), pks[1], 101, true) + tstaking.CreateValidatorWithValPower(sdk.ValAddress(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) @@ -215,7 +215,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { ctx = ctx.WithBlockHeight(height) // validator added back in - tstaking.DelegateWithPower(sdk.BytesToAccAddress(pks[2].Address()), sdk.BytesToValAddress(pks[0].Address()), 50) + tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), sdk.ValAddress(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 4e7185cf88..88549bc5e9 100644 --- a/x/slashing/keeper/msg_server.go +++ b/x/slashing/keeper/msg_server.go @@ -25,7 +25,10 @@ var _ types.MsgServer = msgServer{} func (k msgServer) Unjail(goCtx context.Context, msg *types.MsgUnjail) (*types.MsgUnjailResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr := sdk.ValAddress(msg.ValidatorAddr) + valAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddr) + if valErr != nil { + return nil, valErr + } err := k.Keeper.Unjail(ctx, valAddr) if err != nil { return nil, err diff --git a/x/slashing/keeper/querier.go b/x/slashing/keeper/querier.go index 721bff16cf..53f231f62a 100644 --- a/x/slashing/keeper/querier.go +++ b/x/slashing/keeper/querier.go @@ -48,7 +48,13 @@ func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQu return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - signingInfo, found := k.GetValidatorSigningInfo(ctx, sdk.ConsAddress(params.ConsAddress)) + // https://github.com/cosmos/cosmos-sdk/issues/12573 + // Will be removed, but fix this + addr, err := sdk.ConsAddressFromBech32(params.ConsAddress) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + } + signingInfo, found := k.GetValidatorSigningInfo(ctx, addr) if !found { return nil, sdkerrors.Wrap(types.ErrNoSigningInfoFound, params.ConsAddress) } diff --git a/x/slashing/keeper/signing_info_test.go b/x/slashing/keeper/signing_info_test.go index 28f70a300a..5b540d903a 100644 --- a/x/slashing/keeper/signing_info_test.go +++ b/x/slashing/keeper/signing_info_test.go @@ -4,11 +4,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - ocproto "github.com/line/ostracon/proto/ostracon/types" + "github.com/stretchr/testify/require" "github.com/line/lbm-sdk/simapp" + sdk "github.com/line/lbm-sdk/types" "github.com/line/lbm-sdk/x/slashing/types" ) @@ -17,17 +17,17 @@ func TestGetSetValidatorSigningInfo(t *testing.T) { ctx := app.BaseApp.NewContext(false, ocproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) require.False(t, found) newInfo := types.NewValidatorSigningInfo( - addrDels[0].ToConsAddress(), + sdk.ConsAddress(addrDels[0]), time.Unix(2, 0), false, int64(10), int64(3), ) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), newInfo) - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), newInfo) + info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) require.True(t, found) require.Equal(t, info.VoterSetCounter, int64(3)) require.Equal(t, info.JailedUntil, time.Unix(2, 0).UTC()) @@ -39,10 +39,10 @@ func TestGetSetValidatorMissedBlockBitArray(t *testing.T) { ctx := app.BaseApp.NewContext(false, ocproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - missed := app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, addrDels[0].ToConsAddress(), 0) + missed := app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, sdk.ConsAddress(addrDels[0]), 0) require.False(t, missed) // treat empty key as not missed - app.SlashingKeeper.SetValidatorMissedBlockBitArray(ctx, addrDels[0].ToConsAddress(), 0, true) - missed = app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, addrDels[0].ToConsAddress(), 0) + app.SlashingKeeper.SetValidatorMissedBlockBitArray(ctx, sdk.ConsAddress(addrDels[0]), 0, true) + missed = app.SlashingKeeper.GetValidatorMissedBlockBitArray(ctx, sdk.ConsAddress(addrDels[0]), 0) require.True(t, missed) // now should be missed } @@ -51,22 +51,22 @@ func TestTombstoned(t *testing.T) { ctx := app.BaseApp.NewContext(false, ocproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - require.Panics(t, func() { app.SlashingKeeper.Tombstone(ctx, addrDels[0].ToConsAddress()) }) - require.False(t, app.SlashingKeeper.IsTombstoned(ctx, addrDels[0].ToConsAddress())) + require.Panics(t, func() { app.SlashingKeeper.Tombstone(ctx, sdk.ConsAddress(addrDels[0])) }) + require.False(t, app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0]))) newInfo := types.NewValidatorSigningInfo( - addrDels[0].ToConsAddress(), + sdk.ConsAddress(addrDels[0]), time.Unix(2, 0), false, int64(10), int64(3), ) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), newInfo) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), newInfo) - 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()) }) + 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])) }) } func TestJailUntil(t *testing.T) { @@ -74,19 +74,19 @@ func TestJailUntil(t *testing.T) { ctx := app.BaseApp.NewContext(false, ocproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - require.Panics(t, func() { app.SlashingKeeper.JailUntil(ctx, addrDels[0].ToConsAddress(), time.Now()) }) + require.Panics(t, func() { app.SlashingKeeper.JailUntil(ctx, sdk.ConsAddress(addrDels[0]), time.Now()) }) newInfo := types.NewValidatorSigningInfo( - addrDels[0].ToConsAddress(), + sdk.ConsAddress(addrDels[0]), time.Unix(2, 0), false, int64(10), int64(3), ) - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress(), newInfo) - app.SlashingKeeper.JailUntil(ctx, addrDels[0].ToConsAddress(), time.Unix(253402300799, 0).UTC()) + app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), newInfo) + app.SlashingKeeper.JailUntil(ctx, sdk.ConsAddress(addrDels[0]), time.Unix(253402300799, 0).UTC()) - info, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, addrDels[0].ToConsAddress()) + info, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) 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 d442bec439..8ff11c7b84 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, validatorAddr.ToAccAddress(), validatorAddr) + selfDel := k.sk.Delegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) if selfDel == nil { return types.ErrMissingSelfDelegation } diff --git a/x/slashing/legacy/v043/store_test.go b/x/slashing/legacy/v043/store_test.go index ce65d0cd7a..21492735d8 100644 --- a/x/slashing/legacy/v043/store_test.go +++ b/x/slashing/legacy/v043/store_test.go @@ -41,8 +41,8 @@ func TestStoreMigration(t *testing.T) { }, { "AddrPubkeyRelationKey", - v040slashing.AddrPubkeyRelationKey(consAddr.Bytes()), - types.AddrPubkeyRelationKey(consAddr.Bytes()), + v040slashing.AddrPubkeyRelationKey(consAddr), + types.AddrPubkeyRelationKey(consAddr), }, } diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index c4a3033840..61438732e0 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.BytesToAccAddress(delPk1.Address()) - valAddr1 = sdk.BytesToValAddress(delPk1.Address()) - consAddr1 = sdk.BytesToConsAddress(delPk1.Address()) + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) + consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) ) func TestDecodeStore(t *testing.T) { @@ -37,7 +37,7 @@ func TestDecodeStore(t *testing.T) { Pairs: []kv.Pair{ {Key: types.ValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshal(&info)}, {Key: types.ValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshal(&missed)}, - {Key: types.AddrPubkeyRelationKey(delAddr1.Bytes()), Value: bz}, + {Key: types.AddrPubkeyRelationKey(delAddr1), Value: bz}, {Key: []byte{0x99}, Value: []byte{0x99}}, // This test should panic }, } diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 0419f821bf..fe48a637ab 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, validator.GetOperator().ToAccAddress()) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) 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, validator.GetOperator().ToAccAddress()) + account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) spendable := bk.SpendableCoins(ctx, account.GetAddress()) fees, err := simtypes.RandomFees(r, ctx, spendable) diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index 47811b122a..808a15bfdc 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 := app.StakingKeeper.TokensFromConsensusPower(ctx, 2) validator0, issuedShares := validator0.AddTokensFromDel(delTokens) - val0AccAddress := sdk.ValAddress(validator0.OperatorAddress).ToAccAddress() + val0AccAddress, err := sdk.ValAddressFromBech32(validator0.OperatorAddress) require.NoError(t, err) - selfDelegation := stakingtypes.NewDelegation(val0AccAddress, validator0.GetOperator(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(val0AccAddress.Bytes(), validator0.GetOperator(), issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) - app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), val0AccAddress, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) + app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), val0AccAddress.Bytes(), distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) // begin a new block app.BeginBlock(abci.RequestBeginBlock{Header: ocproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}}) @@ -137,7 +137,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.BytesToValAddress(account.PubKey.Address()) + valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) validator, err := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes.Description{}) require.NoError(t, err) validator, err = validator.SetInitialCommission(commission) diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index 1b8a2cfda5..e715e1a952 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -2,7 +2,6 @@ package types import ( sdk "github.com/line/lbm-sdk/types" - "github.com/line/lbm-sdk/types/errors" ) // slashing message types @@ -24,7 +23,11 @@ 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 { - return []sdk.AccAddress{sdk.ValAddress(msg.ValidatorAddr).ToAccAddress()} + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) + if err != nil { + panic(err) + } + return []sdk.AccAddress{valAddr.Bytes()} } // GetSignBytes gets the bytes for the message signer to sign on @@ -38,9 +41,6 @@ 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 cf4169b8c6..aa42076322 100644 --- a/x/slashing/types/msg_test.go +++ b/x/slashing/types/msg_test.go @@ -9,7 +9,7 @@ import ( ) func TestMsgUnjailGetSignBytes(t *testing.T) { - addr := sdk.BytesToValAddress([]byte("abcd")) + addr := sdk.ValAddress("abcd") msg := NewMsgUnjail(addr) bytes := msg.GetSignBytes() require.Equal( diff --git a/x/staking/app_test.go b/x/staking/app_test.go index fdbf2abbe7..6b085f8c34 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( - addr1.ToValAddress(), valKey.PubKey(), bondCoin, description, commissionRates, sdk.OneInt(), + sdk.ValAddress(addr1), valKey.PubKey(), bondCoin, description, commissionRates, sdk.OneInt(), ) require.NoError(t, err) @@ -79,8 +79,8 @@ func TestStakingMsgs(t *testing.T) { header = ocproto.Header{Height: app.LastBlockHeight() + 1} app.BeginBlock(abci.RequestBeginBlock{Header: header}) - validator := checkValidator(t, app, addr1.ToValAddress(), true) - require.Equal(t, addr1.ToValAddress().String(), validator.OperatorAddress) + validator := checkValidator(t, app, sdk.ValAddress(addr1), true) + require.Equal(t, sdk.ValAddress(addr1).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(addr1.ToValAddress(), description, nil, nil) + editValidatorMsg := types.NewMsgEditValidator(sdk.ValAddress(addr1), description, nil, nil) header = ocproto.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, addr1.ToValAddress(), true) + validator = checkValidator(t, app, sdk.ValAddress(addr1), true) require.Equal(t, description, validator.Description) // delegate simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin}) - delegateMsg := types.NewMsgDelegate(addr2, addr1.ToValAddress(), bondCoin) + delegateMsg := types.NewMsgDelegate(addr2, sdk.ValAddress(addr1), bondCoin) header = ocproto.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, addr1.ToValAddress(), true, bondTokens.ToDec()) + checkDelegation(t, app, addr2, sdk.ValAddress(addr1), true, bondTokens.ToDec()) // begin unbonding - beginUnbondingMsg := types.NewMsgUndelegate(addr2, addr1.ToValAddress(), bondCoin) + beginUnbondingMsg := types.NewMsgUndelegate(addr2, sdk.ValAddress(addr1), bondCoin) header = ocproto.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, addr1.ToValAddress(), false, sdk.Dec{}) + checkDelegation(t, app, addr2, sdk.ValAddress(addr1), 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/query.go b/x/staking/client/cli/query.go index aa6e839de3..059386a487 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -68,10 +68,10 @@ $ %s query staking validator %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateValAddress(args[0]); err != nil { + addr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { return err } - addr := sdk.ValAddress(args[0]) params := &types.QueryValidatorRequest{ValidatorAddr: addr.String()} res, err := queryClient.Validator(cmd.Context(), params) @@ -156,10 +156,10 @@ $ %s query staking unbonding-delegations-from %s1gghjut3ccd8ay0zduzj64hwre2fxs9l } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateValAddress(args[0]); err != nil { + valAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { return err } - valAddr := sdk.ValAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -211,10 +211,10 @@ $ %s query staking redelegations-from %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateValAddress(args[0]); err != nil { + valSrcAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { return err } - valSrcAddr := sdk.ValAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -266,15 +266,15 @@ $ %s query staking delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1gghju } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateAccAddress(args[0]); err != nil { + delAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { return err } - delAddr := sdk.AccAddress(args[0]) - if err := sdk.ValidateValAddress(args[1]); err != nil { + valAddr, err := sdk.ValAddressFromBech32(args[1]) + if err != nil { return err } - valAddr := sdk.ValAddress(args[1]) params := &types.QueryDelegationRequest{ DelegatorAddr: delAddr.String(), @@ -320,10 +320,10 @@ $ %s query staking delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateAccAddress(args[0]); err != nil { + delAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { return err } - delAddr := sdk.AccAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -375,10 +375,10 @@ $ %s query staking delegations-to %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateValAddress(args[0]); err != nil { + valAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { return err } - valAddr := sdk.ValAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -431,15 +431,15 @@ $ %s query staking unbonding-delegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9 } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateAccAddress(args[0]); err != nil { + valAddr, err := sdk.ValAddressFromBech32(args[1]) + if err != nil { return err } - delAddr := sdk.AccAddress(args[0]) - if err := sdk.ValidateValAddress(args[1]); err != nil { + delAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { return err } - valAddr := sdk.ValAddress(args[1]) params := &types.QueryUnbondingDelegationRequest{ DelegatorAddr: delAddr.String(), @@ -485,10 +485,10 @@ $ %s query staking unbonding-delegations %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateAccAddress(args[0]); err != nil { + delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { return err } - delegatorAddr := sdk.AccAddress(args[0]) pageReq, err := client.ReadPageRequest(cmd.Flags()) if err != nil { @@ -541,20 +541,20 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p %s1l2r } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateAccAddress(args[0]); err != nil { + delAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { return err } - delAddr := sdk.AccAddress(args[0]) - if err := sdk.ValidateValAddress(args[1]); err != nil { + valSrcAddr, err := sdk.ValAddressFromBech32(args[1]) + if err != nil { return err } - valSrcAddr := sdk.ValAddress(args[1]) - if err := sdk.ValidateValAddress(args[2]); err != nil { + valDstAddr, err := sdk.ValAddressFromBech32(args[2]) + if err != nil { return err } - valDstAddr := sdk.ValAddress(args[2]) params := &types.QueryRedelegationsRequest{ DelegatorAddr: delAddr.String(), @@ -601,10 +601,10 @@ $ %s query staking redelegation %s1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p } queryClient := types.NewQueryClient(clientCtx) - if err := sdk.ValidateAccAddress(args[0]); err != nil { + delAddr, err := sdk.AccAddressFromBech32(args[0]) + if 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 ddf1885439..fc97323e4b 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -129,7 +129,7 @@ func NewEditValidatorCmd() *cobra.Command { newMinSelfDelegation = &msb } - msg := types.NewMsgEditValidator(valAddr.ToValAddress(), description, newRate, newMinSelfDelegation) + msg := types.NewMsgEditValidator(sdk.ValAddress(valAddr), description, newRate, newMinSelfDelegation) return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, @@ -170,7 +170,10 @@ $ %s tx staking delegate %s1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --f } delAddr := clientCtx.GetFromAddress() - valAddr := sdk.ValAddress(args[0]) + valAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { + return err + } msg := types.NewMsgDelegate(delAddr, valAddr, amount) @@ -205,9 +208,15 @@ $ %s tx staking redelegate %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj %s1l2rsakp3 return err } delAddr := clientCtx.GetFromAddress() - valSrcAddr := sdk.ValAddress(args[0]) + valSrcAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { + return err + } - valDstAddr := sdk.ValAddress(args[1]) + valDstAddr, err := sdk.ValAddressFromBech32(args[1]) + if err != nil { + return err + } amount, err := sdk.ParseCoinNormalized(args[2]) if err != nil { @@ -247,7 +256,10 @@ $ %s tx staking unbond %s1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from return err } delAddr := clientCtx.GetFromAddress() - valAddr := sdk.ValAddress(args[0]) + valAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { + return err + } amount, err := sdk.ParseCoinNormalized(args[1]) if err != nil { @@ -315,7 +327,7 @@ func newBuildCreateValidatorMsg(clientCtx client.Context, txf tx.Factory, fs *fl } msg, err := types.NewMsgCreateValidator( - valAddr.ToValAddress(), pk, amount, description, commissionRates, minSelfDelegation, + sdk.ValAddress(valAddr), pk, amount, description, commissionRates, minSelfDelegation, ) if err != nil { return txf, nil, err @@ -518,7 +530,7 @@ func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorC } msg, err := types.NewMsgCreateValidator( - valAddr.ToValAddress(), config.PubKey, amount, description, commissionRates, minSelfDelegation, + sdk.ValAddress(valAddr), config.PubKey, amount, description, commissionRates, minSelfDelegation, ) if err != nil { return txBldr, msg, err diff --git a/x/staking/client/rest/grpc_query_test.go b/x/staking/client/rest/grpc_query_test.go index 25845894f0..9557d563ee 100644 --- a/x/staking/client/rest/grpc_query_test.go +++ b/x/staking/client/rest/grpc_query_test.go @@ -420,7 +420,7 @@ func (s *IntegrationTestSuite) TestQueryDelegatorDelegationsGRPC() { // Create new account in the keyring for address without delegations. info, _, err := val.ClientCtx.Keyring.NewMnemonic("test", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) - newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) testCases := []struct { name string diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 30700bb089..a543348125 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"] - err := sdk.ValidateAccAddress(delegatorAddr) - if rest.CheckBadRequestError(w, err) { + + if _, err := sdk.AccAddressFromBech32(delegatorAddr); rest.CheckBadRequestError(w, err) { return } @@ -153,7 +153,7 @@ func delegatorTxsHandlerFn(clientCtx client.Context) http.HandlerFunc { // For each case, we search txs for both: // - legacy messages: their Type() is a custom string, e.g. "delegate" - // - service Msgs: their Type() is their FQ method name, e.g. "/cosmos.staking.v1beta1.Msg/Deledate" + // - service Msgs: their Type() is their FQ method name, e.g. "/cosmos.staking.v1beta1.MsgDelegate" // and we combine the results. switch { case isBondTx: @@ -213,35 +213,29 @@ func redelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { bechDstValidatorAddr := r.URL.Query().Get("validator_to") if len(bechDelegatorAddr) != 0 { - err := sdk.ValidateAccAddress(bechDelegatorAddr) + delegatorAddr, err := sdk.AccAddressFromBech32(bechDelegatorAddr) if rest.CheckBadRequestError(w, err) { return } - delegatorAddr := sdk.AccAddress(bechDelegatorAddr) - params.DelegatorAddr = delegatorAddr } if len(bechSrcValidatorAddr) != 0 { - err := sdk.ValidateValAddress(bechSrcValidatorAddr) + srcValidatorAddr, err := sdk.ValAddressFromBech32(bechSrcValidatorAddr) if rest.CheckBadRequestError(w, err) { return } - srcValidatorAddr := sdk.ValAddress(bechSrcValidatorAddr) - params.SrcValidatorAddr = srcValidatorAddr } if len(bechDstValidatorAddr) != 0 { - err := sdk.ValidateValAddress(bechDstValidatorAddr) + dstValidatorAddr, err := sdk.ValAddressFromBech32(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 ddb7e3b714..7936da6dad 100644 --- a/x/staking/client/rest/tx.go +++ b/x/staking/client/rest/tx.go @@ -1,6 +1,7 @@ package rest import ( + "bytes" "net/http" "github.com/gorilla/mux" @@ -71,9 +72,12 @@ func newPostDelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr := sdk.AccAddress(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + if rest.CheckBadRequestError(w, err) { + return + } - if !fromAddr.Equals(req.DelegatorAddress) { + if !bytes.Equal(fromAddr, req.DelegatorAddress) { rest.WriteErrorResponse(w, http.StatusUnauthorized, "must use own delegator address") return } @@ -99,9 +103,12 @@ func newPostRedelegationsHandlerFn(clientCtx client.Context) http.HandlerFunc { return } - fromAddr := sdk.AccAddress(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + if rest.CheckBadRequestError(w, err) { + return + } - if !fromAddr.Equals(req.DelegatorAddress) { + if !bytes.Equal(fromAddr, req.DelegatorAddress) { rest.WriteErrorResponse(w, http.StatusUnauthorized, "must use own delegator address") return } @@ -127,9 +134,12 @@ func newPostUnbondingDelegationsHandlerFn(clientCtx client.Context) http.Handler return } - fromAddr := sdk.AccAddress(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + if rest.CheckBadRequestError(w, err) { + return + } - if !fromAddr.Equals(req.DelegatorAddress) { + if !bytes.Equal(fromAddr, 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 775aa4ed36..b9d6ccf951 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -42,17 +42,15 @@ func queryBonds(clientCtx client.Context, endpoint string) http.HandlerFunc { bech32delegator := vars["delegatorAddr"] bech32validator := vars["validatorAddr"] - err := sdk.ValidateAccAddress(bech32delegator) + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) if rest.CheckBadRequestError(w, err) { return } - delegatorAddr := sdk.AccAddress(bech32delegator) - err = sdk.ValidateValAddress(bech32validator) + validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) if rest.CheckBadRequestError(w, err) { return } - validatorAddr := sdk.ValAddress(bech32validator) clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { @@ -81,11 +79,10 @@ func queryDelegator(clientCtx client.Context, endpoint string) http.HandlerFunc vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] - err := sdk.ValidateAccAddress(bech32delegator) + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) if rest.CheckBadRequestError(w, err) { return } - delegatorAddr := sdk.AccAddress(bech32delegator) clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r) if !ok { @@ -119,11 +116,10 @@ func queryValidator(clientCtx client.Context, endpoint string) http.HandlerFunc return } - err = sdk.ValidateValAddress(bech32validatorAddr) + validatorAddr, err := sdk.ValAddressFromBech32(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/client/testutil/suite.go b/x/staking/client/testutil/suite.go index 354ae2cfc1..00fd5965f7 100644 --- a/x/staking/client/testutil/suite.go +++ b/x/staking/client/testutil/suite.go @@ -91,7 +91,7 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewValidator", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) require.NoError(err) - newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) _, err = banktestutil.MsgSendExec( val.ClientCtx, val.Address, @@ -1056,7 +1056,7 @@ func (s *IntegrationTestSuite) TestNewDelegateCmd() { info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewAccount", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) - newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) _, err = banktestutil.MsgSendExec( val.ClientCtx, @@ -1295,7 +1295,7 @@ func (s *IntegrationTestSuite) TestBlockResults() { // Create new account in the keyring. info, _, err := val.ClientCtx.Keyring.NewMnemonic("NewDelegator", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) require.NoError(err) - newAddr := sdk.BytesToAccAddress(info.GetPubKey().Address()) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) // Send some funds to the new account. _, err = banktestutil.MsgSendExec( diff --git a/x/staking/common_test.go b/x/staking/common_test.go index 0fc5aa6edd..623e428bad 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.BytesToAccAddress(priv1.PubKey().Address()) + addr1 = sdk.AccAddress(priv1.PubKey().Address()) priv2 = secp256k1.GenPrivKey() - addr2 = sdk.BytesToAccAddress(priv2.PubKey().Address()) + addr2 = sdk.AccAddress(priv2.PubKey().Address()) valKey = ed25519.GenPrivKey() - valAddr = sdk.BytesToAccAddress(valKey.PubKey().Address()) + valAddr = sdk.AccAddress(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 904d4e7642..2f46df1b20 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -63,7 +63,10 @@ func InitGenesis( } for _, delegation := range data.Delegations { - delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } // Call the before-creation hook if not exported if !data.Exported { @@ -127,7 +130,10 @@ func InitGenesis( // don't need to run Tendermint updates if we exported if data.Exported { for _, lv := range data.LastValidatorPowers { - valAddr := sdk.ValAddress(lv.Address) + valAddr, err := sdk.ValAddressFromBech32(lv.Address) + if err != nil { + panic(err) + } keeper.SetLastValidatorPower(ctx, valAddr, lv.Power) validator, found := keeper.GetValidator(ctx, valAddr) @@ -200,7 +206,7 @@ func WriteValidators(ctx sdk.Context, keeper keeper.Keeper) (vals []octypes.Gene } vals = append(vals, octypes.GenesisValidator{ - Address: tmPk.Address(), + Address: sdk.ConsAddress(tmPk.Address()).Bytes(), PubKey: tmPk, Power: validator.GetConsensusPower(keeper.PowerReduction(ctx)), Name: validator.GetMoniker(), diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index 9555eb5201..ed967ef61b 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -43,7 +43,7 @@ func TestInitGenesis(t *testing.T) { // initialize the validators bondedVal1 := types.Validator{ - OperatorAddress: addrs[0].ToValAddress().String(), + OperatorAddress: sdk.ValAddress(addrs[0]).String(), ConsensusPubkey: pk0, Status: types.Bonded, Tokens: valTokens, @@ -51,7 +51,7 @@ func TestInitGenesis(t *testing.T) { Description: types.NewDescription("hoop", "", "", "", ""), } bondedVal2 := types.Validator{ - OperatorAddress: addrs[1].ToValAddress().String(), + OperatorAddress: sdk.ValAddress(addrs[1]).String(), ConsensusPubkey: pk1, Status: types.Bonded, Tokens: valTokens, @@ -89,11 +89,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, addrs[0].ToValAddress()) + resVal, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[0])) require.True(t, found) require.Equal(t, types.Bonded, resVal.Status) - resVal, found = app.StakingKeeper.GetValidator(ctx, addrs[1].ToValAddress()) + resVal, found = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[1])) require.True(t, found) require.Equal(t, types.Bonded, resVal.Status) @@ -163,7 +163,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { bondedPoolAmt := sdk.ZeroInt() for i := range validators { - validators[i], err = types.NewValidator(addrs[i].ToValAddress(), + validators[i], err = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.NewDescription(fmt.Sprintf("#%d", i), "", "", "", "")) require.NoError(t, err) validators[i].Status = types.Bonded @@ -203,7 +203,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.BytesToValAddress(pk.Address()), pk) + genValidators1[0] = teststaking.NewValidator(t, sdk.ValAddress(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 52f5615de9..d7706daac3 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -56,7 +56,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.Equal(t, 1, len(updates)) // verify the self-delegation exists - bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found) gotBond := bond.Shares.RoundInt() require.Equal(t, initBond, gotBond) @@ -76,7 +76,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.Equal(t, 1, len(updates)) // slash and jail the first validator - consAddr0 := sdk.BytesToConsAddress(PKs[0].Address()) + consAddr0 := sdk.ConsAddress(PKs[0].Address()) app.StakingKeeper.Slash(ctx, consAddr0, 0, initPower, sdk.NewDecWithPrec(5, 1)) app.StakingKeeper.Jail(ctx, consAddr0) app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -102,7 +102,7 @@ func TestValidatorByPowerIndex(t *testing.T) { // unbond self-delegation totalBond := validator.TokensFromShares(bond.GetShares()).TruncateInt() - res := tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, totalBond, true) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, totalBond, true) var resData types.MsgUndelegateResponse err = proto.Unmarshal(res.Data, &resData) @@ -218,7 +218,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) valAddr := valAddrs[0] - valConsPubKey, valConsAddr := PKs[0], sdk.BytesToConsAddress(PKs[0].Address()) + valConsPubKey, valConsAddr := PKs[0], sdk.ConsAddress(PKs[0].Address()) delAddr := delAddrs[1] // create validator @@ -243,7 +243,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(valAddr.ToAccAddress(), valAddr, bondAmount, true) + res := tstaking.Undelegate(sdk.AccAddress(valAddr), valAddr, bondAmount, true) var resData types.MsgUndelegateResponse err = proto.Unmarshal(res.Data, &resData) @@ -264,7 +264,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt()) // verify the validator can still self-delegate - tstaking.Delegate(valAddr.ToAccAddress(), valAddr, bondAmount) + tstaking.Delegate(sdk.AccAddress(valAddr), valAddr, bondAmount) // verify validator bonded shares validator, found = app.StakingKeeper.GetValidator(ctx, valAddr) @@ -312,7 +312,7 @@ func TestIncrementsMsgDelegate(t *testing.T) { tstaking.CheckDelegator(delegatorAddr, validatorAddr, false) - bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found) require.Equal(t, bondAmount, bond.Shares.RoundInt()) @@ -369,7 +369,7 @@ func TestEditValidatorDecreaseMinSelfDelegation(t *testing.T) { require.Equal(t, 1, len(updates)) // verify the self-delegation exists - bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found) gotBond := bond.Shares.RoundInt() require.Equal(t, initBond, gotBond, @@ -400,7 +400,7 @@ func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) { require.Equal(t, 1, len(updates)) // verify the self-delegation exists - bond, found := app.StakingKeeper.GetDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) + bond, found := app.StakingKeeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found) gotBond := bond.Shares.RoundInt() require.Equal(t, initBond, gotBond, @@ -618,7 +618,7 @@ func TestJailValidator(t *testing.T) { // unbond the validators bond portion unamt := sdk.NewInt(amt) - res := tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, unamt, true) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, unamt, true) var resData types.MsgUndelegateResponse err := proto.Unmarshal(res.Data, &resData) @@ -661,7 +661,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(validatorAddr.ToAccAddress(), validatorAddr, amt, true) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, amt, true) var resData types.MsgUndelegateResponse err := proto.Unmarshal(res.Data, &resData) @@ -707,26 +707,26 @@ func TestUnbondingPeriod(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin unbonding - tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, amt, true) + tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, amt, true) origHeader := ctx.BlockHeader() - _, found := app.StakingKeeper.GetUnbondingDelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr) + _, found := app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), 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, validatorAddr.ToAccAddress(), validatorAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), 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, validatorAddr.ToAccAddress(), validatorAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), 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, validatorAddr.ToAccAddress(), validatorAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.False(t, found, "should have unbonded") } @@ -742,7 +742,7 @@ func TestUnbondingFromUnbondingValidator(t *testing.T) { // unbond the validators bond portion unbondAmt := sdk.NewInt(10) - res := tstaking.Undelegate(validatorAddr.ToAccAddress(), validatorAddr, unbondAmt, true) + res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, unbondAmt, true) // change the ctx to Block Time one second before the validator would have unbonded var resData types.MsgUndelegateResponse @@ -775,42 +775,42 @@ func TestRedelegationPeriod(t *testing.T) { params.UnbondingTime = 7 * time.Second app.StakingKeeper.SetParams(ctx, params) // initial balance - amt1 := app.BankKeeper.GetBalance(ctx, validatorAddr.ToAccAddress(), denom).Amount + amt1 := app.BankKeeper.GetBalance(ctx, sdk.AccAddress(validatorAddr), 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, validatorAddr.ToAccAddress(), denom).Amount + amt2 := app.BankKeeper.GetBalance(ctx, sdk.AccAddress(validatorAddr), 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, validatorAddr.ToAccAddress()) + bal1 := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(validatorAddr)) // begin redelegate redAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgBeginRedelegate := types.NewMsgBeginRedelegate(validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2, redAmt) + msgBeginRedelegate := types.NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2, redAmt) tstaking.Handle(msgBeginRedelegate, true) // origin account should not lose tokens as with a regular delegation - bal2 := app.BankKeeper.GetAllBalances(ctx, validatorAddr.ToAccAddress()) + bal2 := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(validatorAddr)) require.Equal(t, bal1, bal2) origHeader := ctx.BlockHeader() // cannot complete redelegation at same time staking.EndBlocker(ctx, app.StakingKeeper) - _, found := app.StakingKeeper.GetRedelegation(ctx, validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2) + _, found := app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), 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, validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2) + _, found = app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), 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, validatorAddr.ToAccAddress(), validatorAddr, validatorAddr2) + _, found = app.StakingKeeper.GetRedelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) require.False(t, found, "should have unbonded") } @@ -830,11 +830,11 @@ func TestTransitiveRedelegation(t *testing.T) { // begin redelegate redAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10)) - msgBeginRedelegate := types.NewMsgBeginRedelegate(val1.ToAccAddress(), val1, val2, redAmt) + msgBeginRedelegate := types.NewMsgBeginRedelegate(sdk.AccAddress(val1), val1, val2, redAmt) tstaking.Handle(msgBeginRedelegate, true) // cannot redelegation to next validator while first delegation exists - msgBeginRedelegate = types.NewMsgBeginRedelegate(val1.ToAccAddress(), val2, val3, redAmt) + msgBeginRedelegate = types.NewMsgBeginRedelegate(sdk.AccAddress(val1), val2, val3, redAmt) tstaking.Handle(msgBeginRedelegate, false) params := app.StakingKeeper.GetParams(ctx) @@ -868,7 +868,7 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin a redelegate - selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) + selfDelAddr := sdk.AccAddress(valAddr) // (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) @@ -912,7 +912,7 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin a redelegate - selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) + selfDelAddr := sdk.AccAddress(valAddr) // (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) @@ -957,7 +957,7 @@ func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin an unbonding delegation - selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) + selfDelAddr := sdk.AccAddress(valAddr) // (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 @@ -997,7 +997,7 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { staking.EndBlocker(ctx, app.StakingKeeper) // begin an unbonding delegation - selfDelAddr := valAddr.ToAccAddress() // (the validator is it's own delegator) + selfDelAddr := sdk.AccAddress(valAddr) // (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 @@ -1055,7 +1055,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { require.Equal(t, 2, len(app.StakingKeeper.GetLastValidators(ctx))) // unbond the validator-2 - tstaking.Undelegate(val2.ToAccAddress(), val2, valTokens2, true) + tstaking.Undelegate(sdk.AccAddress(val2), val2, valTokens2, true) // apply TM updates app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -1071,7 +1071,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { initPower := int64(1000) app, ctx, delAddrs, valAddrs := bootstrapHandlerGenesisTest(t, initPower, 3, sdk.TokensFromConsensusPower(initPower, sdk.DefaultPowerReduction)) valA, valB, del := valAddrs[0], valAddrs[1], delAddrs[2] - consAddr0 := sdk.BytesToConsAddress(PKs[0].Address()) + consAddr0 := sdk.ConsAddress(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 c101890b1f..b8c9e2d12c 100644 --- a/x/staking/keeper/alias_functions.go +++ b/x/staking/keeper/alias_functions.go @@ -39,7 +39,8 @@ func (k Keeper) IterateBondedValidatorsByPower(ctx sdk.Context, fn func(index in i := int64(0) for ; iterator.Valid() && i < int64(maxValidators); iterator.Next() { - validator := k.mustGetValidator(ctx, sdk.ValAddress(string(iterator.Value()))) + address := iterator.Value() + validator := k.mustGetValidator(ctx, address) if validator.IsBonded() { stop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to? @@ -61,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, sdk.ValAddress(string(address))) + validator, found := k.GetValidator(ctx, 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 5acaee0e53..64a8cfd631 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -1,6 +1,7 @@ package keeper import ( + "bytes" "fmt" "time" @@ -89,7 +90,10 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres // set a delegation func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { - delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) b := types.MustMarshalDelegation(k.cdc, delegation) @@ -98,7 +102,10 @@ func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { // remove a delegation func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) { - delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } // TODO: Consider calling hooks outside of the store wrapper functions, it's unobvious. k.BeforeDelegationRemoved(ctx, delegatorAddress, delegation.GetValidatorAddr()) store := ctx.KVStore(k.storeKey) @@ -189,10 +196,16 @@ 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 := sdk.AccAddress(ubd.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) bz := types.MustMarshalUBD(k.cdc, ubd) - addr := sdk.ValAddress(ubd.ValidatorAddress) + addr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) + if err != nil { + panic(err) + } key := types.GetUBDKey(delegatorAddress, addr) store.Set(key, bz) store.Set(types.GetUBDByValIndexKey(delegatorAddress, addr), []byte{}) // index, store empty bytes @@ -200,10 +213,16 @@ 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 := sdk.AccAddress(ubd.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) - addr := sdk.ValAddress(ubd.ValidatorAddress) + addr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) + if err != nil { + panic(err) + } key := types.GetUBDKey(delegatorAddress, addr) store.Delete(key) store.Delete(types.GetUBDByValIndexKey(delegatorAddress, addr)) @@ -375,12 +394,21 @@ func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context, // set a redelegation and associated index func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { - delegatorAddress := sdk.AccAddress(red.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(red.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) bz := types.MustMarshalRED(k.cdc, red) - valSrcAddr := sdk.ValAddress(red.ValidatorSrcAddress) - valDestAddr := sdk.ValAddress(red.ValidatorDstAddress) + valSrcAddr, err := sdk.ValAddressFromBech32(red.ValidatorSrcAddress) + if err != nil { + panic(err) + } + valDestAddr, err := sdk.ValAddressFromBech32(red.ValidatorDstAddress) + if err != nil { + panic(err) + } key := types.GetREDKey(delegatorAddress, valSrcAddr, valDestAddr) store.Set(key, bz) store.Set(types.GetREDByValSrcIndexKey(delegatorAddress, valSrcAddr, valDestAddr), []byte{}) @@ -425,10 +453,19 @@ 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 := sdk.AccAddress(red.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(red.DelegatorAddress) + if err != nil { + panic(err) + } store := ctx.KVStore(k.storeKey) - valSrcAddr := sdk.ValAddress(red.ValidatorSrcAddress) - valDestAddr := sdk.ValAddress(red.ValidatorDstAddress) + valSrcAddr, err := sdk.ValAddressFromBech32(red.ValidatorSrcAddress) + if err != nil { + panic(err) + } + valDestAddr, err := sdk.ValAddressFromBech32(red.ValidatorDstAddress) + if err != nil { + panic(err) + } redKey := types.GetREDKey(delegatorAddress, valSrcAddr, valDestAddr) store.Delete(redKey) store.Delete(types.GetREDByValSrcIndexKey(delegatorAddress, valSrcAddr, valDestAddr)) @@ -531,7 +568,10 @@ func (k Keeper) Delegate( k.BeforeDelegationCreated(ctx, delAddr, validator.GetOperator()) } - delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } // if subtractAccount is true then we are // performing a delegation and not a redelegation, thus the source tokens are @@ -613,9 +653,12 @@ func (k Keeper) Unbond( // subtract shares from delegation delegation.Shares = delegation.Shares.Sub(shares) - delegatorAddress := sdk.AccAddress(delegation.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + return amount, err + } - isValidatorOperator := delegatorAddress.Equals(validator.GetOperator().ToAccAddress()) + isValidatorOperator := delegatorAddress.Equals(validator.GetOperator()) // 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. @@ -721,7 +764,10 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd balances := sdk.NewCoins() ctxTime := ctx.BlockHeader().Time - delegatorAddress := sdk.AccAddress(ubd.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) + if err != nil { + return nil, err + } // loop through all the entries and complete unbonding mature entries for i := 0; i < len(ubd.Entries); i++ { @@ -758,7 +804,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 valSrcAddr.Equals(valDstAddr) { + if bytes.Equal(valSrcAddr, valDstAddr) { return time.Time{}, types.ErrSelfRedelegation } diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index ed6078fce0..15ff1ad6ce 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -322,7 +322,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) require.True(t, validator.IsBonded()) - selfDelegation := types.NewDelegation(addrVals[0].ToAccAddress(), addrVals[0], issuedShares) + selfDelegation := types.NewDelegation(sdk.AccAddress(addrVals[0].Bytes()), addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) // add bonded tokens to pool for delegations @@ -344,7 +344,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) - val0AccAddr := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], app.StakingKeeper.TokensFromConsensusPower(ctx, 6).ToDec()) require.NoError(t, err) @@ -381,7 +381,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - selfDelegation := types.NewDelegation(addrVals[0].ToAccAddress(), addrVals[0], issuedShares) + selfDelegation := types.NewDelegation(addrVals[0].Bytes(), addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) // add bonded tokens to pool for delegations @@ -413,7 +413,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { ctx = ctx.WithBlockHeader(header) // unbond the all self-delegation to put validator in unbonding state - val0AccAddr := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0]) _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) require.NoError(t, err) @@ -467,7 +467,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - val0AccAddr := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0]) selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -548,7 +548,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - val0AccAddr := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -652,7 +652,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], "", "") + redelegations = app.StakingKeeper.GetAllRedelegations(ctx, addrDels[0], nil, nil) require.Equal(t, 1, len(redelegations)) require.Equal(t, redelegations[0], resRed) @@ -684,7 +684,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], "", "") + redelegations = app.StakingKeeper.GetAllRedelegations(ctx, addrDels[0], nil, nil) require.Equal(t, 0, len(redelegations)) } @@ -709,7 +709,7 @@ func TestRedelegateToSameValidator(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.True(t, validator.IsBonded()) - val0AccAddr := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -737,7 +737,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 := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -797,7 +797,7 @@ func TestRedelegateSelfDelegation(t *testing.T) { validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) - val0AccAddr := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0]) selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -851,7 +851,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 := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -933,7 +933,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 := addrVals[0].ToAccAddress() + val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) 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 c05c909515..1e62c5b226 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -70,11 +70,11 @@ func (k Querier) Validator(c context.Context, req *types.QueryValidatorRequest) 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()) - } - valAddr := sdk.ValAddress(req.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) + if err != nil { + return nil, err + } ctx := sdk.UnwrapSDKContext(c) validator, found := k.GetValidator(ctx, valAddr) @@ -94,10 +94,6 @@ 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) @@ -109,7 +105,10 @@ func (k Querier) ValidatorDelegations(c context.Context, req *types.QueryValidat return false, err } - valAddr := sdk.ValAddress(req.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) + if err != nil { + return false, err + } if !delegation.GetValidatorAddr().Equals(valAddr) { return false, nil @@ -142,15 +141,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 := sdk.ValAddress(req.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) + if err != nil { + return nil, err + } srcValPrefix := types.GetUBDsByValIndexKey(valAddr) ubdStore := prefix.NewStore(store, srcValPrefix) @@ -184,21 +183,20 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, err + } - valAddr := sdk.ValAddress(req.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) + if err != nil { + return nil, err + } delegation, found := k.GetDelegation(ctx, delAddr, valAddr) if !found { @@ -225,22 +223,21 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, err + } - valAddr := sdk.ValAddress(req.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) + if err != nil { + return nil, err + } unbond, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr) if !found { @@ -262,14 +259,13 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, err + } store := ctx.KVStore(k.storeKey) delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) @@ -303,21 +299,20 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, err + } - valAddr := sdk.ValAddress(req.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr) + if err != nil { + return nil, err + } validator, err := k.GetDelegatorValidator(ctx, delAddr, valAddr) if err != nil { @@ -336,15 +331,14 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, err + } unbStore := prefix.NewStore(store, types.GetUBDsKey(delAddr)) pageRes, err := query.Paginate(unbStore, req.Pagination, func(key []byte, value []byte) error { @@ -395,25 +389,10 @@ 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 { @@ -436,15 +415,14 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, err + } delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) pageRes, err := query.Paginate(delStore, req.Pagination, func(key []byte, value []byte) error { @@ -494,11 +472,20 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, err + } - srcValAddr := sdk.ValAddress(req.SrcValidatorAddr) + srcValAddr, err := sdk.ValAddressFromBech32(req.SrcValidatorAddr) + if err != nil { + return nil, err + } - dstValAddr := sdk.ValAddress(req.DstValidatorAddr) + dstValAddr, err := sdk.ValAddressFromBech32(req.DstValidatorAddr) + if err != nil { + return nil, err + } redel, found := k.GetRedelegation(ctx, delAddr, srcValAddr, dstValAddr) if !found { @@ -513,7 +500,10 @@ 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 := sdk.ValAddress(req.SrcValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.SrcValidatorAddr) + if err != nil { + return nil, nil, err + } srcValPrefix := types.GetREDsFromValSrcIndexKey(valAddr) redStore := prefix.NewStore(store, srcValPrefix) @@ -532,7 +522,10 @@ 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 := sdk.AccAddress(req.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) + if err != nil { + return nil, nil, err + } 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 41cd1191a6..636f07c66b 100644 --- a/x/staking/keeper/grpc_query_test.go +++ b/x/staking/keeper/grpc_query_test.go @@ -229,8 +229,10 @@ 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 := sdk.ValAddress(vals[0].OperatorAddress) - delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, addrVal) + addrVal := vals[0].OperatorAddress + valAddr, err := sdk.ValAddressFromBech32(addrVal) + suite.NoError(err) + delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr) suite.True(found) var req *types.QueryDelegationRequest @@ -251,7 +253,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegation() { func() { req = &types.QueryDelegationRequest{ DelegatorAddr: addrAcc1.String(), - ValidatorAddr: addrVal.String(), + ValidatorAddr: addrVal, } }, false, @@ -259,7 +261,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegation() { { "valid request", func() { - req = &types.QueryDelegationRequest{DelegatorAddr: addrAcc.String(), ValidatorAddr: addrVal.String()} + req = &types.QueryDelegationRequest{DelegatorAddr: addrAcc.String(), ValidatorAddr: addrVal} }, true, }, @@ -285,7 +287,8 @@ 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 := sdk.ValAddress(addrVal1) + valAddr, err := sdk.ValAddressFromBech32(addrVal1) + suite.NoError(err) delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr) suite.True(found) var req *types.QueryDelegatorDelegationsRequest @@ -350,7 +353,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorDelegations() { addrVal1 := vals[1].OperatorAddress valAddrs := simapp.ConvertAddrsToValAddrs(addrs) addrVal2 := valAddrs[4] - valAddr := sdk.ValAddress(addrVal1) + valAddr, err := sdk.ValAddressFromBech32(addrVal1) + suite.NoError(err) delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr) suite.True(found) @@ -416,7 +420,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryUnbondingDelegation() { addrVal2 := vals[1].OperatorAddress unbondingTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2) - valAddr := sdk.ValAddress(addrVal2) + valAddr, err1 := sdk.ValAddressFromBech32(addrVal2) + suite.NoError(err1) _, err := app.StakingKeeper.Undelegate(ctx, addrAcc2, valAddr, unbondingTokens.ToDec()) suite.NoError(err) @@ -473,10 +478,12 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegatorUnbondingDelegations() { addrVal, addrVal2 := vals[0].OperatorAddress, vals[1].OperatorAddress unbondingTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2) - valAddr1 := sdk.ValAddress(addrVal) + valAddr1, err1 := sdk.ValAddressFromBech32(addrVal) + suite.NoError(err1) _, err := app.StakingKeeper.Undelegate(ctx, addrAcc, valAddr1, unbondingTokens.ToDec()) suite.NoError(err) - valAddr2 := sdk.ValAddress(addrVal2) + valAddr2, err1 := sdk.ValAddressFromBech32(addrVal2) + suite.NoError(err1) _, 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 12123979a5..ede1935672 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, sdk.ValAddress(string(iterator.Value()))) + validator, found := k.GetValidator(ctx, iterator.Value()) if !found { panic(fmt.Sprintf("validator record not found for address: %X\n", iterator.Value())) } diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index 283562f095..110fecc31d 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -30,7 +30,10 @@ var _ types.MsgServer = msgServer{} func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateValidator) (*types.MsgCreateValidatorResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr := sdk.ValAddress(msg.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + if err != nil { + return nil, err + } // check to see if the pubkey or sender has been registered before if _, found := k.GetValidator(ctx, valAddr); found { @@ -81,7 +84,10 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa return nil, err } - delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + if err != nil { + return nil, err + } validator.MinSelfDelegation = msg.MinSelfDelegation @@ -119,7 +125,10 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa // EditValidator defines a method for editing an existing validator func (k msgServer) EditValidator(goCtx context.Context, msg *types.MsgEditValidator) (*types.MsgEditValidatorResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr := sdk.ValAddress(msg.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + if err != nil { + return nil, err + } // validator must already be registered validator, found := k.GetValidator(ctx, valAddr) if !found { @@ -179,14 +188,20 @@ func (k msgServer) EditValidator(goCtx context.Context, msg *types.MsgEditValida // Delegate defines a method for performing a delegation of coins from a delegator to a validator func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valAddr := sdk.ValAddress(msg.ValidatorAddress) + valAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress) + if valErr != nil { + return nil, valErr + } validator, found := k.GetValidator(ctx, valAddr) if !found { return nil, types.ErrNoValidatorFound } - delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + if err != nil { + return nil, err + } bondDenom := k.BondDenom(ctx) if msg.Amount.Denom != bondDenom { @@ -232,8 +247,14 @@ func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*typ // BeginRedelegate defines a method for performing a redelegation of coins from a delegator and source validator to a destination validator func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRedelegate) (*types.MsgBeginRedelegateResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - valSrcAddr := sdk.ValAddress(msg.ValidatorSrcAddress) - delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) + valSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress) + if err != nil { + return nil, err + } + delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + if err != nil { + return nil, err + } shares, err := k.ValidateUnbondAmount( ctx, delegatorAddress, valSrcAddr, msg.Amount.Amount, ) @@ -248,7 +269,10 @@ func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRed ) } - valDstAddr := sdk.ValAddress(msg.ValidatorDstAddress) + valDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress) + if err != nil { + return nil, err + } completionTime, err := k.BeginRedelegation( ctx, delegatorAddress, valSrcAddr, valDstAddr, shares, @@ -292,8 +316,14 @@ 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 := sdk.ValAddress(msg.ValidatorAddress) - delegatorAddress := sdk.AccAddress(msg.DelegatorAddress) + addr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + if err != nil { + return nil, err + } + delegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + if err != nil { + return nil, err + } 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 aaa5597c45..7319536575 100644 --- a/x/staking/keeper/querier.go +++ b/x/staking/keeper/querier.go @@ -251,8 +251,7 @@ 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) @@ -260,18 +259,17 @@ func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - err = sdk.ValidateAccAddress(params.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) if err != nil { return nil, err } - err = sdk.ValidateValAddress(params.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) if err != nil { return nil, err } - validator, err := k.GetDelegatorValidator(ctx, sdk.AccAddress(params.DelegatorAddr), - sdk.ValAddress(params.ValidatorAddr)) + validator, err := k.GetDelegatorValidator(ctx, delAddr, valAddr) if err != nil { return nil, err } @@ -284,8 +282,7 @@ func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper, 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) @@ -293,18 +290,17 @@ func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - err = sdk.ValidateAccAddress(params.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) if err != nil { return nil, err } - err = sdk.ValidateValAddress(params.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) if err != nil { return nil, err } - delegation, found := k.GetDelegation(ctx, sdk.AccAddress(params.DelegatorAddr), - sdk.ValAddress(params.ValidatorAddr)) + delegation, found := k.GetDelegation(ctx, delAddr, valAddr) if !found { return nil, types.ErrNoDelegation } @@ -322,8 +318,7 @@ func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, 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) @@ -331,18 +326,17 @@ func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper, return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - err = sdk.ValidateAccAddress(params.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(params.DelegatorAddr) if err != nil { return nil, err } - err = sdk.ValidateValAddress(params.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(params.ValidatorAddr) if err != nil { return nil, err } - unbond, found := k.GetUnbondingDelegation(ctx, sdk.AccAddress(params.DelegatorAddr), - sdk.ValAddress(params.ValidatorAddr)) + unbond, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr) if !found { return nil, types.ErrNoUnbondingDelegation } @@ -458,7 +452,10 @@ func DelegationToDelegationResponse(ctx sdk.Context, k Keeper, del types.Delegat return types.DelegationResponse{}, types.ErrNoValidatorFound } - delegatorAddress := sdk.AccAddress(del.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + if err != nil { + return types.DelegationResponse{}, err + } return types.NewDelegationResp( delegatorAddress, @@ -491,10 +488,19 @@ func RedelegationsToRedelegationResponses( resp := make(types.RedelegationResponses, len(redels)) for i, redel := range redels { - valSrcAddr := sdk.ValAddress(redel.ValidatorSrcAddress) - valDstAddr := sdk.ValAddress(redel.ValidatorDstAddress) + valSrcAddr, err := sdk.ValAddressFromBech32(redel.ValidatorSrcAddress) + if err != nil { + panic(err) + } + valDstAddr, err := sdk.ValAddressFromBech32(redel.ValidatorDstAddress) + if err != nil { + panic(err) + } - delegatorAddress := sdk.AccAddress(redel.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(redel.DelegatorAddress) + if err != nil { + panic(err) + } 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 a742933364..1fa36ecfc2 100644 --- a/x/staking/keeper/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -20,14 +20,14 @@ func TestNewQuerier(t *testing.T) { cdc, app, ctx := createTestInput() addrs := simapp.AddTestAddrs(app, ctx, 500, sdk.NewInt(10000)) - addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1 := addrAcc1.ToValAddress() + _, addrAcc2 := addrs[0], addrs[1] + addrVal1, _ := sdk.ValAddress(addrs[0]), sdk.ValAddress(addrs[1]) // Create Validators amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8)} var validators [2]types.Validator for i, amt := range amts { - validators[i] = teststaking.NewValidator(t, sdk.AccAddress(addrs[i]).ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) validators[i], _ = validators[i].AddTokensFromDel(amt) app.StakingKeeper.SetValidator(ctx, validators[i]) app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[i]) @@ -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("", "", "")) + bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(nil, nil, nil)) require.NoError(t, errRes) query.Data = bz @@ -210,7 +210,7 @@ func TestQueryDelegation(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 2, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := addrAcc1.ToValAddress(), addrAcc2.ToValAddress() + addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) 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, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) pubKeys := simapp.CreateTestPubKeys(1) - valAddress := addrs[0].ToValAddress() + valAddress := sdk.ValAddress(addrs[0]) 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, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := addrAcc1.ToValAddress(), addrAcc2.ToValAddress() + addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) // 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, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1 := addrAcc1.ToValAddress() + addrVal1 := sdk.ValAddress(addrAcc1) // 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, app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)) addrAcc1, addrAcc2 := addrs[0], addrs[1] - addrVal1, addrVal2 := addrAcc1.ToValAddress(), addrAcc2.ToValAddress() + addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2) // 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 9d04cfaf1a..3244c7a84e 100644 --- a/x/staking/keeper/query_utils.go +++ b/x/staking/keeper/query_utils.go @@ -107,9 +107,14 @@ func (k Keeper) GetAllRedelegations( for ; iterator.Valid(); iterator.Next() { redelegation := types.MustUnmarshalRED(k.cdc, iterator.Value()) - valSrcAddr := sdk.ValAddress(redelegation.ValidatorSrcAddress) - valDstAddr := sdk.ValAddress(redelegation.ValidatorDstAddress) - + valSrcAddr, err := sdk.ValAddressFromBech32(redelegation.ValidatorSrcAddress) + if err != nil { + panic(err) + } + valDstAddr, err := sdk.ValAddressFromBech32(redelegation.ValidatorDstAddress) + if err != nil { + panic(err) + } if srcValFilter && !(srcValAddress.Equals(valSrcAddr)) { continue } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index fe4f9bf238..abbe51682a 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -245,9 +245,15 @@ func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, continue } - valDstAddr := sdk.ValAddress(redelegation.ValidatorDstAddress) + valDstAddr, err := sdk.ValAddressFromBech32(redelegation.ValidatorDstAddress) + if err != nil { + panic(err) + } - delegatorAddress := sdk.AccAddress(redelegation.DelegatorAddress) + delegatorAddress, err := sdk.AccAddressFromBech32(redelegation.DelegatorAddress) + if err != nil { + panic(err) + } 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 ba098d91cf..fb3fbd3722 100644 --- a/x/staking/keeper/slash_test.go +++ b/x/staking/keeper/slash_test.go @@ -51,7 +51,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.BytesToConsAddress(PKs[0].Address()) + consAddr := sdk.ConsAddress(PKs[0].Address()) // initial state val, found := app.StakingKeeper.GetValidator(ctx, addrVals[0]) @@ -186,7 +186,7 @@ func TestSlashRedelegation(t *testing.T) { func TestSlashAtFutureHeight(t *testing.T) { app, ctx, _, _ := bootstrapSlashTest(t, 10) - consAddr := sdk.BytesToConsAddress(PKs[0].Address()) + consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) require.Panics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 1, 10, fraction) }) } @@ -195,7 +195,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.BytesToConsAddress(PKs[0].Address()) + consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) bondedPool := app.StakingKeeper.GetBondedPool(ctx) @@ -226,7 +226,7 @@ func TestSlashAtNegativeHeight(t *testing.T) { // tests Slash at the current height func TestSlashValidatorAtCurrentHeight(t *testing.T) { app, ctx, _, _ := bootstrapSlashTest(t, 10) - consAddr := sdk.BytesToConsAddress(PKs[0].Address()) + consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) bondedPool := app.StakingKeeper.GetBondedPool(ctx) @@ -258,7 +258,7 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { func TestSlashWithUnbondingDelegation(t *testing.T) { app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10) - consAddr := sdk.BytesToConsAddress(PKs[0].Address()) + consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) // set an unbonding delegation with expiration timestamp beyond which the @@ -383,7 +383,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.BytesToConsAddress(PKs[0].Address()) + consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := sdk.NewDecWithPrec(5, 1) bondDenom := app.StakingKeeper.BondDenom(ctx) @@ -577,7 +577,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.BytesToConsAddress(PKs[0].Address()) + consAddr0 := sdk.ConsAddress(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 0473ce6410..df2b95ce23 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -1,6 +1,7 @@ package keeper // noalias import ( + "bytes" "math/rand" sdk "github.com/line/lbm-sdk/types" @@ -25,8 +26,8 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - valAddr := sdk.ValAddress(string(types.ParseValidatorPowerRankKey(iterator.Key()))) - if valAddr.Equals(validator.GetOperator()) { + valAddr := types.ParseValidatorPowerRankKey(iterator.Key()) + if bytes.Equal(valAddr, 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 f577ac1160..c37f5e75fc 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -4,13 +4,11 @@ import ( "bytes" "fmt" "sort" - "strings" gogotypes "github.com/gogo/protobuf/types" - abci "github.com/line/ostracon/abci/types" - sdk "github.com/line/lbm-sdk/types" "github.com/line/lbm-sdk/x/staking/types" + abci "github.com/line/ostracon/abci/types" ) // BlockValidatorUpdates calculates the ValidatorUpdates for the current block @@ -36,8 +34,15 @@ 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 { - balances, err := k.CompleteUnbonding(ctx, sdk.AccAddress(dvPair.DelegatorAddress), - sdk.ValAddress(dvPair.ValidatorAddress)) + 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) if err != nil { continue } @@ -55,11 +60,23 @@ 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, - sdk.AccAddress(dvvTriplet.DelegatorAddress), - sdk.ValAddress(dvvTriplet.ValidatorSrcAddress), - sdk.ValAddress(dvvTriplet.ValidatorDstAddress), + delegatorAddress, + valSrcAddr, + valDstAddr, ) if err != nil { continue @@ -101,7 +118,10 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab // Retrieve the last validator set. // The persistent set is updated later in this function. // (see LastValidatorPowerKey). - last := k.getLastValidatorsByAddr(ctx) + last, err := k.getLastValidatorsByAddr(ctx) + if err != nil { + return nil, err + } // Iterate over validators, highest power to lowest. iterator := k.ValidatorsPowerStoreIterator(ctx) @@ -144,7 +164,11 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab } // fetch the old power bytes - oldPowerBytes, found := last[valAddr.String()] + valAddrStr, err := sdk.Bech32ifyAddressBytes(sdk.GetConfig().GetBech32ValidatorAddrPrefix(), valAddr) + if err != nil { + return nil, err + } + oldPowerBytes, found := last[valAddrStr] newPower := validator.ConsensusPower(powerReduction) newPowerBytes := k.cdc.MustMarshal(&gogotypes.Int64Value{Value: newPower}) @@ -155,13 +179,17 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab k.SetLastValidatorPower(ctx, valAddr, newPower) } - delete(last, valAddr.String()) + delete(last, valAddrStr) count++ totalPower = totalPower.Add(sdk.NewInt(newPower)) } - noLongerBonded := sortNoLongerBonded(last) + noLongerBonded, err := sortNoLongerBonded(last) + if err != nil { + return nil, err + } + for _, valAddrBytes := range noLongerBonded { validator := k.mustGetValidator(ctx, sdk.ValAddress(valAddrBytes)) validator, err = k.bondedToUnbonding(ctx, validator) @@ -325,7 +353,7 @@ func (k Keeper) completeUnbondingValidator(ctx sdk.Context, validator types.Vali type validatorsByAddr map[string][]byte // get the last validator set -func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr { +func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) (validatorsByAddr, error) { last := make(validatorsByAddr) iterator := k.LastValidatorsIterator(ctx) @@ -333,31 +361,40 @@ func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr { for ; iterator.Valid(); iterator.Next() { // extract the validator address from the key (prefix is 1-byte, addrLen is 1-byte) - valAddr := string(iterator.Key()[2:]) + valAddr := types.AddressFromLastValidatorPowerKey(iterator.Key()) + valAddrStr, err := sdk.Bech32ifyAddressBytes(sdk.GetConfig().GetBech32ValidatorAddrPrefix(), valAddr) + if err != nil { + return nil, err + } + powerBytes := iterator.Value() - last[valAddr] = make([]byte, len(powerBytes)) - copy(last[valAddr], powerBytes) + last[valAddrStr] = make([]byte, len(powerBytes)) + copy(last[valAddrStr], powerBytes) } - return last + return last, nil } // 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) []string { +func sortNoLongerBonded(last validatorsByAddr) ([][]byte, error) { // sort the map keys for determinism - noLongerBonded := make([]string, len(last)) + noLongerBonded := make([][]byte, len(last)) index := 0 for valAddrStr := range last { - noLongerBonded[index] = valAddrStr + valAddrBytes, err := sdk.ValAddressFromBech32(valAddrStr) + if err != nil { + return nil, err + } + 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 strings.Compare(noLongerBonded[i], noLongerBonded[j]) == -1 + return bytes.Compare(noLongerBonded[i], noLongerBonded[j]) == -1 }) - return noLongerBonded + return noLongerBonded, nil } diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index d40eef4397..cdb27b344b 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, sdk.ValAddress(string(opAddr))) + return k.GetValidator(ctx, 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().Bytes()) + store.Set(types.GetValidatorByConsAddrKey(consPk), validator.GetOperator()) 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, k.PowerReduction(ctx)), validator.GetOperator().Bytes()) + store.Set(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx)), validator.GetOperator()) } // 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, k.PowerReduction(ctx)), validator.GetOperator().Bytes()) + store.Set(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx)), validator.GetOperator()) } // 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 := sdk.ValAddress(string(iterator.Value())) + address := iterator.Value() validator := k.mustGetValidator(ctx, address) if validator.IsBonded() { @@ -317,7 +317,7 @@ func (k Keeper) GetLastValidators(ctx sdk.Context) (validators []types.Validator } address := types.AddressFromLastValidatorPowerKey(iterator.Key()) - validator := k.mustGetValidator(ctx, sdk.ValAddress(string(address))) + validator := k.mustGetValidator(ctx, address) validators[i] = validator i++ @@ -422,7 +422,10 @@ func (k Keeper) UnbondAllMatureValidators(ctx sdk.Context) { k.cdc.MustUnmarshal(unbondingValIterator.Value(), &addrs) for _, valAddr := range addrs.Addresses { - addr := sdk.ValAddress(valAddr) + addr, err := sdk.ValAddressFromBech32(valAddr) + if err != nil { + panic(err) + } 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 c36e7e1bdd..6ddf7c3587 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -47,7 +47,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, addrs[i].ToValAddress(), pks[i]) + vs[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), pks[i]) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) vs[i], _ = vs[i].AddTokensFromDel(tokens) } @@ -58,7 +58,7 @@ func TestSetValidator(t *testing.T) { app, ctx, _, _ := bootstrapValidatorTest(t, 10, 100) valPubKey := PKs[0] - valAddr := sdk.BytesToValAddress(valPubKey.Address()) + valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) // test how the validator is set from a purely unbonbed pool @@ -196,9 +196,9 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // require all the validators have their respective statuses for valIdx, status := range expectedValStatus { valAddr := validators[valIdx].OperatorAddress - err := sdk.ValidateValAddress(valAddr) + addr, err := sdk.ValAddressFromBech32(valAddr) assert.NoError(t, err) - val, _ := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(valAddr)) + val, _ := app.StakingKeeper.GetValidator(ctx, addr) assert.Equal( t, status, val.GetStatus(), @@ -229,7 +229,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.BytesToConsAddress(PKs[0].Address()), 0, 100, sdk.OneDec()) + app.StakingKeeper.Slash(ctx, sdk.ConsAddress(PKs[0].Address()), 0, 100, sdk.OneDec()) // apply TM updates applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1) // validator should be unbonding @@ -273,7 +273,7 @@ func TestValidatorBasics(t *testing.T) { assert.True(ValEq(t, validators[0], resVal)) // retrieve from consensus - resVal, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.BytesToConsAddress(PKs[0].Address())) + resVal, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.ConsAddress(PKs[0].Address())) require.True(t, found) assert.True(ValEq(t, validators[0], resVal)) resVal, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) @@ -350,7 +350,7 @@ func TestGetValidatorSortingUnmixed(t *testing.T) { n := len(amts) var validators [5]types.Validator for i, amt := range amts { - validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) validators[i].Status = types.Bonded validators[i].Tokens = amt validators[i].DelegatorShares = sdk.NewDecFromInt(amt) @@ -443,22 +443,22 @@ func TestGetValidatorSortingMixed(t *testing.T) { var validators [5]types.Validator for i, amt := range amts { - validators[i] = teststaking.NewValidator(t, addrs[i].ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), 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, addrs[0].ToValAddress()) + val0, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[0])) require.True(t, found) - val1, found := app.StakingKeeper.GetValidator(ctx, addrs[1].ToValAddress()) + val1, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[1])) require.True(t, found) - val2, found := app.StakingKeeper.GetValidator(ctx, addrs[2].ToValAddress()) + val2, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[2])) require.True(t, found) - val3, found := app.StakingKeeper.GetValidator(ctx, addrs[3].ToValAddress()) + val3, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[3])) require.True(t, found) - val4, found := app.StakingKeeper.GetValidator(ctx, addrs[4].ToValAddress()) + val4, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[4])) require.True(t, found) require.Equal(t, types.Bonded, val0.Status) require.Equal(t, types.Unbonding, val1.Status) @@ -491,7 +491,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, addrs[i].ToValAddress(), PKs[i], moniker) + validators[i] = newMonikerValidator(t, sdk.ValAddress(addrs[i]), PKs[i], moniker) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) @@ -599,9 +599,9 @@ func TestValidatorBondHeight(t *testing.T) { // initialize some validators into the state var validators [3]types.Validator - 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]) + 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]) tokens0 := app.StakingKeeper.TokensFromConsensusPower(ctx, 200) tokens1 := app.StakingKeeper.TokensFromConsensusPower(ctx, 100) @@ -647,7 +647,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, addrs[i].ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[i], true) @@ -685,7 +685,7 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) { var validators [2]types.Validator for i, power := range powers { valPubKey := PKs[i+1] - valAddr := sdk.BytesToValAddress(valPubKey.Address()) + valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = teststaking.NewValidator(t, valAddr, valPubKey) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) @@ -713,7 +713,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, addrs[i].ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) @@ -736,7 +736,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, addrs[i].ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) @@ -821,7 +821,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, addrs[i].ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } @@ -854,7 +854,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, addrs[i].ToValAddress(), PKs[i]) + validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } @@ -898,7 +898,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // initialize some validators into the state for i, power := range powers { valPubKey := PKs[i+1] - valAddr := sdk.BytesToValAddress(valPubKey.Address()) + valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = teststaking.NewValidator(t, valAddr, valPubKey) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) @@ -931,7 +931,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.BytesToValAddress(valPubKey.Address()) + valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) amt := sdk.NewInt(100) validator := teststaking.NewValidator(t, valAddr, valPubKey) @@ -945,7 +945,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // add a new validator that increases in power valPubKey = PKs[len(validators)+2] - valAddr = sdk.BytesToValAddress(valPubKey.Address()) + valAddr = sdk.ValAddress(valPubKey.Address().Bytes()) validator = teststaking.NewValidator(t, valAddr, valPubKey) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 500) @@ -977,7 +977,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { for i, power := range powers { moniker := fmt.Sprintf("%d", i) valPubKey := PKs[i+1] - valAddr := sdk.BytesToValAddress(valPubKey.Address()) + valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = newMonikerValidator(t, valAddr, valPubKey, moniker) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) diff --git a/x/staking/legacy/v040/keys.go b/x/staking/legacy/v040/keys.go index ce2a96f512..b3ce8b4be8 100644 --- a/x/staking/legacy/v040/keys.go +++ b/x/staking/legacy/v040/keys.go @@ -85,16 +85,15 @@ func GetValidatorsByPowerIndexKey(validator types.Validator) []byte { powerBytesLen := len(powerBytes) // 8 // key is of format prefix || powerbytes || addrBytes - key := make([]byte, 1+powerBytesLen+v040auth.ValAddrLen) + key := make([]byte, 1+powerBytesLen+v040auth.AddrLen) key[0] = ValidatorsByPowerIndexKey[0] copy(key[1:powerBytesLen+1], powerBytes) - err := sdk.ValidateValAddress(validator.OperatorAddress) + addr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) if err != nil { panic(err) } - addr := sdk.ValAddress(validator.OperatorAddress) - operAddrInvr := sdk.CopyBytes(addr.Bytes()) + operAddrInvr := sdk.CopyBytes(addr) for i, b := range operAddrInvr { operAddrInvr[i] = ^b @@ -185,7 +184,7 @@ func GetDelegationsKey(delAddr sdk.AccAddress) []byte { // VALUE: staking/UnbondingDelegation func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { return append( - GetUBDsKey(delAddr), + GetUBDsKey(delAddr.Bytes()), valAddr.Bytes()...) } @@ -205,7 +204,7 @@ func GetUBDKeyFromValIndexKey(indexKey []byte) []byte { valAddr := addrs[:v040auth.AddrLen] delAddr := addrs[v040auth.AddrLen:] - return GetUBDKey(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)) + return GetUBDKey(delAddr, valAddr) } // gets the prefix for all unbonding delegations from a delegator @@ -227,11 +226,11 @@ 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+v040auth.AddrLen+v040auth.ValAddrLen*2) + key := make([]byte, 1+v040auth.AddrLen*3) - copy(key[0:v040auth.AddrLen+1], GetREDsKey(delAddr)) - copy(key[v040auth.AddrLen+1:v040auth.AddrLen+v040auth.ValAddrLen+1], valSrcAddr.Bytes()) - copy(key[v040auth.AddrLen+v040auth.ValAddrLen+1:v040auth.AddrLen+v040auth.ValAddrLen*2+1], valDstAddr.Bytes()) + copy(key[0:v040auth.AddrLen+1], GetREDsKey(delAddr.Bytes())) + copy(key[v040auth.AddrLen+1:2*v040auth.AddrLen+1], valSrcAddr.Bytes()) + copy(key[2*v040auth.AddrLen+1:3*v040auth.AddrLen+1], valDstAddr.Bytes()) return key } @@ -243,10 +242,10 @@ func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.V offset := len(REDSFromValsSrcKey) // key is of the form REDSFromValsSrcKey || delAddr || valDstAddr - key := make([]byte, len(REDSFromValsSrcKey)+v040auth.AddrLen+v040auth.ValAddrLen) + key := make([]byte, len(REDSFromValsSrcKey)+2*v040auth.AddrLen) copy(key[0:offset], REDSFromValsSrcKey) copy(key[offset:offset+v040auth.AddrLen], delAddr.Bytes()) - copy(key[offset+v040auth.AddrLen:offset+v040auth.AddrLen+v040auth.ValAddrLen], valDstAddr.Bytes()) + copy(key[offset+v040auth.AddrLen:offset+2*v040auth.AddrLen], valDstAddr.Bytes()) return key } @@ -258,10 +257,10 @@ func GetREDByValDstIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.V offset := len(REDSToValsDstKey) // key is of the form REDSToValsDstKey || delAddr || valSrcAddr - key := make([]byte, len(REDSToValsDstKey)+v040auth.AddrLen+v040auth.ValAddrLen) + key := make([]byte, len(REDSToValsDstKey)+2*v040auth.AddrLen) copy(key[0:offset], REDSToValsDstKey) copy(key[offset:offset+v040auth.AddrLen], delAddr.Bytes()) - copy(key[offset+v040auth.AddrLen:offset+v040auth.AddrLen+v040auth.ValAddrLen], valSrcAddr.Bytes()) + copy(key[offset+v040auth.AddrLen:offset+2*v040auth.AddrLen], valSrcAddr.Bytes()) return key } @@ -273,9 +272,9 @@ func GetREDKeyFromValSrcIndexKey(indexKey []byte) []byte { panic("unexpected key length") } - valSrcAddr := sdk.ValAddress(indexKey[1 : v040auth.AddrLen+1]) - delAddr := sdk.AccAddress(indexKey[v040auth.AddrLen+1 : 2*v040auth.AddrLen+1]) - valDstAddr := sdk.ValAddress(indexKey[2*v040auth.AddrLen+1 : 3*v040auth.AddrLen+1]) + valSrcAddr := indexKey[1 : v040auth.AddrLen+1] + delAddr := indexKey[v040auth.AddrLen+1 : 2*v040auth.AddrLen+1] + valDstAddr := indexKey[2*v040auth.AddrLen+1 : 3*v040auth.AddrLen+1] return GetREDKey(delAddr, valSrcAddr, valDstAddr) } @@ -287,9 +286,9 @@ func GetREDKeyFromValDstIndexKey(indexKey []byte) []byte { panic("unexpected key length") } - valDstAddr := sdk.ValAddress(indexKey[1 : v040auth.AddrLen+1]) - delAddr := sdk.AccAddress(indexKey[v040auth.AddrLen+1 : 2*v040auth.AddrLen+1]) - valSrcAddr := sdk.ValAddress(indexKey[2*v040auth.AddrLen+1 : 3*v040auth.AddrLen+1]) + valDstAddr := indexKey[1 : v040auth.AddrLen+1] + delAddr := indexKey[v040auth.AddrLen+1 : 2*v040auth.AddrLen+1] + valSrcAddr := indexKey[2*v040auth.AddrLen+1 : 3*v040auth.AddrLen+1] return GetREDKey(delAddr, valSrcAddr, valDstAddr) } diff --git a/x/staking/legacy/v043/store.go b/x/staking/legacy/v043/store.go index ec897cc318..3358a7f220 100644 --- a/x/staking/legacy/v043/store.go +++ b/x/staking/legacy/v043/store.go @@ -14,7 +14,7 @@ import ( // prefix_bytes | address_1_bytes | address_2_bytes | address_3_bytes // into format: // prefix_bytes | address_1_len (1 byte) | address_1_bytes | address_2_len (1 byte) | address_2_bytes | address_3_len (1 byte) | address_3_bytes -func migratePrefixAddressValAddressValAddress(store sdk.KVStore, prefixBz []byte) { +func migratePrefixAddressAddressAddress(store sdk.KVStore, prefixBz []byte) { oldStore := prefix.NewStore(store, prefixBz) oldStoreIter := oldStore.Iterator(nil, nil) @@ -22,33 +22,8 @@ func migratePrefixAddressValAddressValAddress(store sdk.KVStore, prefixBz []byte for ; oldStoreIter.Valid(); oldStoreIter.Next() { addr1 := oldStoreIter.Key()[:v040auth.AddrLen] - addr2 := oldStoreIter.Key()[v040auth.AddrLen : v040auth.AddrLen+v040auth.ValAddrLen] - addr3 := oldStoreIter.Key()[v040auth.AddrLen+v040auth.ValAddrLen:] - newStoreKey := append(append(append( - prefixBz, - address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...), address.MustLengthPrefix(addr3)..., - ) - - // Set new key on store. Values don't change. - store.Set(newStoreKey, oldStoreIter.Value()) - oldStore.Delete(oldStoreIter.Key()) - } -} - -// migratePrefixAddressAddressAddress is a helper function that migrates all keys of format: -// prefix_bytes | address_1_bytes | address_2_bytes | address_3_bytes -// into format: -// prefix_bytes | address_1_len (1 byte) | address_1_bytes | address_2_len (1 byte) | address_2_bytes | address_3_len (1 byte) | address_3_bytes -func migratePrefixValAddressAddressValAddress(store sdk.KVStore, prefixBz []byte) { - oldStore := prefix.NewStore(store, prefixBz) - - oldStoreIter := oldStore.Iterator(nil, nil) - defer oldStoreIter.Close() - - for ; oldStoreIter.Valid(); oldStoreIter.Next() { - addr1 := oldStoreIter.Key()[:v040auth.ValAddrLen] - addr2 := oldStoreIter.Key()[v040auth.ValAddrLen : v040auth.ValAddrLen+v040auth.AddrLen] - addr3 := oldStoreIter.Key()[v040auth.ValAddrLen+v040auth.AddrLen:] + addr2 := oldStoreIter.Key()[v040auth.AddrLen : 2*v040auth.AddrLen] + addr3 := oldStoreIter.Key()[2*v040auth.AddrLen:] newStoreKey := append(append(append( prefixBz, address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...), address.MustLengthPrefix(addr3)..., @@ -94,10 +69,10 @@ func MigrateStore(ctx sdk.Context, storeKey sdk.StoreKey) error { v043distribution.MigratePrefixAddressAddress(store, v040staking.DelegationKey) v043distribution.MigratePrefixAddressAddress(store, v040staking.UnbondingDelegationKey) - v043distribution.MigratePrefixValAddressAddress(store, v040staking.UnbondingDelegationByValIndexKey) - migratePrefixAddressValAddressValAddress(store, v040staking.RedelegationKey) - migratePrefixValAddressAddressValAddress(store, v040staking.RedelegationByValSrcIndexKey) - migratePrefixValAddressAddressValAddress(store, v040staking.RedelegationByValDstIndexKey) + v043distribution.MigratePrefixAddressAddress(store, v040staking.UnbondingDelegationByValIndexKey) + migratePrefixAddressAddressAddress(store, v040staking.RedelegationKey) + migratePrefixAddressAddressAddress(store, v040staking.RedelegationByValSrcIndexKey) + migratePrefixAddressAddressAddress(store, v040staking.RedelegationByValDstIndexKey) return nil } diff --git a/x/staking/legacy/v043/store_test.go b/x/staking/legacy/v043/store_test.go index ff9ebb9bde..29bbbc3f66 100644 --- a/x/staking/legacy/v043/store_test.go +++ b/x/staking/legacy/v043/store_test.go @@ -23,12 +23,12 @@ func TestStoreMigration(t *testing.T) { store := ctx.KVStore(stakingKey) _, pk1, addr1 := testdata.KeyTestPubAddr() - valAddr1 := sdk.AccAddress(addr1).ToValAddress() + valAddr1 := sdk.ValAddress(addr1) val := teststaking.NewValidator(t, valAddr1, pk1) - _, _, addr2 := testdata.KeyTestPubAddr() - valAddr2 := sdk.AccAddress(addr2).ToValAddress() + _, pk1, addr2 := testdata.KeyTestPubAddr() + valAddr2 := sdk.ValAddress(addr2) _, _, addr3 := testdata.KeyTestPubAddr() - consAddr := sdk.AccAddress(addr3).ToConsAddress() + consAddr := sdk.ConsAddress(addr3) _, _, addr4 := testdata.KeyTestPubAddr() now := time.Now() // Use dummy value for all keys. diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 3ceb69a70c..4da2479a6b 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.BytesToAccAddress(delPk1.Address()) - valAddr1 = sdk.BytesToValAddress(delPk1.Address()) + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) ) func makeTestCodec() (cdc *codec.LegacyAmino) { diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index cbf564dcd1..0443f1e5c1 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 := simState.Accounts[i].Address.ToValAddress() + valAddr := sdk.ValAddress(simState.Accounts[i].Address) 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 2b5816dfa7..9f7ac473c0 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -97,7 +97,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 := simAccount.Address.ToValAddress() + address := sdk.ValAddress(simAccount.Address) // ensure the validator doesn't exist already _, found := k.GetValidator(ctx, address) @@ -191,7 +191,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, val.GetOperator().ToAccAddress()) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(val.GetOperator())) 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 cdb48c08cf..e5e21a073d 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, validator0.GetOperator(), issuedShares) + delegation := types.NewDelegation(delegator.Address, validator1.GetOperator(), issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) - app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) + app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator1.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, sdk.OneDec(), 200)) setupValidatorRewards(app, ctx, validator0.GetOperator()) setupValidatorRewards(app, ctx, validator1.GetOperator()) @@ -257,8 +257,8 @@ 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, "linkvaloper17s94pzwhsn4ah25tec27w70n65h5t2sc2g5u4z", msg.ValidatorDstAddress) - require.Equal(t, "linkvaloper1h6a7shta7jyc72hyznkys683z98z36e0qrqd3d", msg.ValidatorSrcAddress) + require.Equal(t, "linkvaloper1h6a7shta7jyc72hyznkys683z98z36e0qrqd3d", msg.ValidatorDstAddress) + require.Equal(t, "linkvaloper17s94pzwhsn4ah25tec27w70n65h5t2sc2g5u4z", msg.ValidatorSrcAddress) require.Len(t, futureOperations, 0) } @@ -303,7 +303,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.BytesToValAddress(account.PubKey.Address()) + valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) 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 e18a836b3b..599ec1efe0 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()) - 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()) + 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()) emptyAddr sdk.ValAddress emptyPubkey cryptotypes.PubKey diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index 2ffc720362..734824d612 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -60,17 +60,19 @@ func UnmarshalDelegation(cdc codec.BinaryCodec, value []byte) (delegation Delega } func (d Delegation) GetDelegatorAddr() sdk.AccAddress { - return sdk.AccAddress(d.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) + if err != nil { + panic(err) + } + return delAddr } - func (d Delegation) GetValidatorAddr() sdk.ValAddress { - err := sdk.ValidateValAddress(d.ValidatorAddress) + addr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) if err != nil { panic(err) } - return sdk.ValAddress(d.ValidatorAddress) + return addr } - 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 8564497c75..1b21e0ded1 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -47,20 +47,18 @@ var ( ValidatorQueueKey = []byte{0x43} // prefix for the timestamps in validator queue HistoricalInfoKey = []byte{0x50} // prefix for the historical info - - AddressDelimiter = "," ) // GetValidatorKey creates the key for the validator with address // VALUE: staking/Validator func GetValidatorKey(operatorAddr sdk.ValAddress) []byte { - return append(ValidatorsKey, address.MustLengthPrefix(operatorAddr.Bytes())...) + return append(ValidatorsKey, address.MustLengthPrefix(operatorAddr)...) } // GetValidatorByConsAddrKey creates the key for the validator with pubkey // VALUE: validator operator address ([]byte) func GetValidatorByConsAddrKey(addr sdk.ConsAddress) []byte { - return append(ValidatorsByConsAddrKey, address.MustLengthPrefix(addr.Bytes())...) + return append(ValidatorsByConsAddrKey, address.MustLengthPrefix(addr)...) } // AddressFromValidatorsKey creates the validator operator address from ValidatorsKey @@ -88,11 +86,11 @@ func GetValidatorsByPowerIndexKey(validator Validator, powerReduction sdk.Int) [ powerBytes := consensusPowerBytes powerBytesLen := len(powerBytes) // 8 - err := sdk.ValidateValAddress(validator.OperatorAddress) + addr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) if err != nil { panic(err) } - operAddrInvr := sdk.CopyBytes([]byte(validator.OperatorAddress)) + operAddrInvr := sdk.CopyBytes(addr) addrLen := len(operAddrInvr) for i, b := range operAddrInvr { @@ -112,7 +110,7 @@ func GetValidatorsByPowerIndexKey(validator Validator, powerReduction sdk.Int) [ // GetLastValidatorPowerKey creates the bonded validator index key for an operator address func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte { - return append(LastValidatorPowerKey, address.MustLengthPrefix(operator.Bytes())...) + return append(LastValidatorPowerKey, address.MustLengthPrefix(operator)...) } // ParseValidatorPowerRankKey parses the validators operator address from power rank key @@ -176,24 +174,24 @@ func ParseValidatorQueueKey(bz []byte) (time.Time, int64, error) { // GetDelegationKey creates the key for delegator bond with validator // VALUE: staking/Delegation func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { - return append(GetDelegationsKey(delAddr), address.MustLengthPrefix(valAddr.Bytes())...) + return append(GetDelegationsKey(delAddr), address.MustLengthPrefix(valAddr)...) } // GetDelegationsKey creates the prefix for a delegator for all validators func GetDelegationsKey(delAddr sdk.AccAddress) []byte { - return append(DelegationKey, address.MustLengthPrefix(delAddr.Bytes())...) + return append(DelegationKey, address.MustLengthPrefix(delAddr)...) } // GetUBDKey creates 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), address.MustLengthPrefix(valAddr.Bytes())...) + return append(GetUBDsKey(delAddr.Bytes()), address.MustLengthPrefix(valAddr)...) } // GetUBDByValIndexKey creates 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), address.MustLengthPrefix(delAddr.Bytes())...) + return append(GetUBDsByValIndexKey(valAddr), address.MustLengthPrefix(delAddr)...) } // GetUBDKeyFromValIndexKey rearranges the ValIndexKey to get the UBDKey @@ -201,20 +199,20 @@ func GetUBDKeyFromValIndexKey(indexKey []byte) []byte { addrs := indexKey[1:] // remove prefix bytes valAddrLen := addrs[0] - valAddr := sdk.ValAddress(addrs[1 : 1+valAddrLen]) - delAddr := sdk.AccAddress(addrs[valAddrLen+2:]) + valAddr := addrs[1 : 1+valAddrLen] + delAddr := addrs[valAddrLen+2:] return GetUBDKey(delAddr, valAddr) } // GetUBDsKey creates the prefix for all unbonding delegations from a delegator func GetUBDsKey(delAddr sdk.AccAddress) []byte { - return append(UnbondingDelegationKey, address.MustLengthPrefix(delAddr.Bytes())...) + return append(UnbondingDelegationKey, address.MustLengthPrefix(delAddr)...) } // GetUBDsByValIndexKey creates the prefix keyspace for the indexes of unbonding delegations for a validator func GetUBDsByValIndexKey(valAddr sdk.ValAddress) []byte { - return append(UnbondingDelegationByValIndexKey, address.MustLengthPrefix(valAddr.Bytes())...) + return append(UnbondingDelegationByValIndexKey, address.MustLengthPrefix(valAddr)...) } // GetUnbondingDelegationTimeKey creates the prefix for all unbonding delegations from a delegator @@ -229,7 +227,7 @@ func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) [] // key is of the form GetREDsKey || valSrcAddrLen (1 byte) || valSrcAddr || valDstAddrLen (1 byte) || valDstAddr key := make([]byte, 1+3+len(delAddr)+len(valSrcAddr)+len(valDstAddr)) - copy(key[0:2+len(delAddr)], GetREDsKey(delAddr)) + copy(key[0:2+len(delAddr)], GetREDsKey(delAddr.Bytes())) key[2+len(delAddr)] = byte(len(valSrcAddr)) copy(key[3+len(delAddr):3+len(delAddr)+len(valSrcAddr)], valSrcAddr.Bytes()) key[3+len(delAddr)+len(valSrcAddr)] = byte(len(valDstAddr)) @@ -278,10 +276,10 @@ func GetREDKeyFromValSrcIndexKey(indexKey []byte) []byte { addrs := indexKey[1:] valSrcAddrLen := addrs[0] - valSrcAddr := sdk.ValAddress(addrs[1 : valSrcAddrLen+1]) + valSrcAddr := addrs[1 : valSrcAddrLen+1] delAddrLen := addrs[valSrcAddrLen+1] - delAddr := sdk.AccAddress(addrs[valSrcAddrLen+2 : valSrcAddrLen+2+delAddrLen]) - valDstAddr := sdk.ValAddress(addrs[valSrcAddrLen+delAddrLen+3:]) + delAddr := addrs[valSrcAddrLen+2 : valSrcAddrLen+2+delAddrLen] + valDstAddr := addrs[valSrcAddrLen+delAddrLen+3:] return GetREDKey(delAddr, valSrcAddr, valDstAddr) } @@ -292,10 +290,10 @@ func GetREDKeyFromValDstIndexKey(indexKey []byte) []byte { addrs := indexKey[1:] valDstAddrLen := addrs[0] - valDstAddr := sdk.ValAddress(addrs[1 : valDstAddrLen+1]) + valDstAddr := addrs[1 : valDstAddrLen+1] delAddrLen := addrs[valDstAddrLen+1] - delAddr := sdk.AccAddress(addrs[valDstAddrLen+2 : valDstAddrLen+2+delAddrLen]) - valSrcAddr := sdk.ValAddress(addrs[valDstAddrLen+delAddrLen+3:]) + delAddr := addrs[valDstAddrLen+2 : valDstAddrLen+2+delAddrLen] + valSrcAddr := addrs[valDstAddrLen+delAddrLen+3:] return GetREDKey(delAddr, valSrcAddr, valDstAddr) } @@ -310,25 +308,25 @@ func GetRedelegationTimeKey(timestamp time.Time) []byte { // GetREDsKey returns a key prefix for indexing a redelegation from a delegator // address. func GetREDsKey(delAddr sdk.AccAddress) []byte { - return append(RedelegationKey, address.MustLengthPrefix(delAddr.Bytes())...) + return append(RedelegationKey, address.MustLengthPrefix(delAddr)...) } // GetREDsFromValSrcIndexKey returns a key prefix for indexing a redelegation to // a source validator. func GetREDsFromValSrcIndexKey(valSrcAddr sdk.ValAddress) []byte { - return append(RedelegationByValSrcIndexKey, address.MustLengthPrefix(valSrcAddr.Bytes())...) + return append(RedelegationByValSrcIndexKey, address.MustLengthPrefix(valSrcAddr)...) } // GetREDsToValDstIndexKey returns a key prefix for indexing a redelegation to a // destination (target) validator. func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte { - return append(RedelegationByValDstIndexKey, address.MustLengthPrefix(valDstAddr.Bytes())...) + return append(RedelegationByValDstIndexKey, address.MustLengthPrefix(valDstAddr)...) } // 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), address.MustLengthPrefix(delAddr.Bytes())...) + return append(GetREDsToValDstIndexKey(valDstAddr), address.MustLengthPrefix(delAddr)...) } // 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 26b1e6889e..4ec884515a 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.BytesToValAddress(keysAddr1) + valAddr1 := sdk.ValAddress(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, "2300000000000000003293969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, - {val2, "2300000000000000013293969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, - {val3, "23000000000000000a3293969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, - {val4, "2300000100000000003293969194899e93908f9a8dce89cf8b97859889858fc7898bc98ec8868c8b929992c89ec6888998cf8f8f8c9992c6cd9998c6"}, + {val1, "230000000000000000149c288ede7df62742fc3b7d0962045a8cef0f79f6"}, + {val2, "230000000000000001149c288ede7df62742fc3b7d0962045a8cef0f79f6"}, + {val3, "23000000000000000a149c288ede7df62742fc3b7d0962045a8cef0f79f6"}, + {val4, "230000010000000000149c288ede7df62742fc3b7d0962045a8cef0f79f6"}, } for i, tt := range tests { got := hex.EncodeToString(types.GetValidatorsByPowerIndexKey(tt.validator, sdk.DefaultPowerReduction)) @@ -56,12 +56,12 @@ func TestGetREDByValDstIndexKey(t *testing.T) { valDstAddr sdk.ValAddress wantHex string }{ - {sdk.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), - "36326c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d39326667392b6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b326c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d3932666739"}, - {sdk.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr2), sdk.BytesToValAddress(keysAddr3), - "36326c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a757063373364613074633273342b6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b326c696e6b76616c6f70657231746d656d74756a75326a3278366a35666c7378736e356833796573353273386a7a37736e7777"}, - {sdk.BytesToAccAddress(keysAddr2), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr3), - "36326c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a757063373364613074633273342b6c696e6b31746d656d74756a75326a3278366a35666c7378736e356833796573353273386a73326a777161326c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d3932666739"}, + {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), + "361463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f08609"}, + {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), + "36143ab62f0d93849be495e21e3e9013a517038f45bd1463d771218209d8bd03c482f69dfba57310f08609145ef3b5f25c54946d4a89fc0d09d2f126614540f2"}, + {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), + "36143ab62f0d93849be495e21e3e9013a517038f45bd145ef3b5f25c54946d4a89fc0d09d2f126614540f21463d771218209d8bd03c482f69dfba57310f08609"}, } 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.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr1), - "35326c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d39326667392b6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b326c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d3932666739"}, - {sdk.BytesToAccAddress(keysAddr1), sdk.BytesToValAddress(keysAddr2), sdk.BytesToValAddress(keysAddr3), - "35326c696e6b76616c6f70657231746d656d74756a75326a3278366a35666c7378736e356833796573353273386a7a37736e77772b6c696e6b31763074687a67767a703876743671377973746d666d376139777667307070736666336735786b326c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a75706337336461307463327334"}, - {sdk.BytesToAccAddress(keysAddr2), sdk.BytesToValAddress(keysAddr1), sdk.BytesToValAddress(keysAddr3), - "35326c696e6b76616c6f70657231763074687a67767a703876743671377973746d666d37613977766730707073666d39326667392b6c696e6b31746d656d74756a75326a3278366a35666c7378736e356833796573353273386a73326a777161326c696e6b76616c6f7065723138326d7a3772766e736a64376639307a72636c66717961397a75706337336461307463327334"}, + {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), + "351463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f08609"}, + {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), + "35145ef3b5f25c54946d4a89fc0d09d2f126614540f21463d771218209d8bd03c482f69dfba57310f08609143ab62f0d93849be495e21e3e9013a517038f45bd"}, + {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), + "351463d771218209d8bd03c482f69dfba57310f08609145ef3b5f25c54946d4a89fc0d09d2f126614540f2143ab62f0d93849be495e21e3e9013a517038f45bd"}, } 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 0f04e1bb40..e0c50463e0 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -43,7 +43,7 @@ func NewMsgCreateValidator( } return &MsgCreateValidator{ Description: description, - DelegatorAddress: valAddr.ToAccAddress().String(), + DelegatorAddress: sdk.AccAddress(valAddr).String(), ValidatorAddress: valAddr.String(), Pubkey: pkAny, Value: selfDelegation, @@ -64,10 +64,17 @@ 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 - addrs := []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} - valAddr := sdk.ValAddress(msg.ValidatorAddress).ToAccAddress() - if !addrs[0].Equals(valAddr) { - addrs = append(addrs, valAddr) + 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)) } return addrs @@ -82,23 +89,23 @@ 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 - delAddrBytes, err := sdk.AccAddressToBytes(msg.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) if err != nil { return err } - if len(delAddrBytes) == 0 { + if delAddr.Empty() { return ErrEmptyDelegatorAddr } - valAddrBytes, err := sdk.ValAddressToBytes(msg.ValidatorAddress) - if err != nil { - return err - } - if len(valAddrBytes) == 0 { + if msg.ValidatorAddress == "" { return ErrEmptyValidatorAddr } - if !bytes.Equal(delAddrBytes, valAddrBytes) { + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + if err != nil { + return err + } + if !sdk.AccAddress(valAddr).Equals(delAddr) { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "validator address is invalid") } @@ -161,7 +168,11 @@ func (msg MsgEditValidator) Type() string { return TypeMsgEditValidator } // GetSigners implements the sdk.Msg interface. func (msg MsgEditValidator) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{sdk.ValAddress(msg.ValidatorAddress).ToAccAddress()} + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{valAddr.Bytes()} } // GetSignBytes implements the sdk.Msg interface. @@ -175,9 +186,6 @@ 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") @@ -217,11 +225,11 @@ func (msg MsgDelegate) Type() string { return TypeMsgDelegate } // GetSigners implements the sdk.Msg interface. func (msg MsgDelegate) GetSigners() []sdk.AccAddress { - err := sdk.ValidateAccAddress(msg.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} + return []sdk.AccAddress{delAddr} } // GetSignBytes implements the sdk.Msg interface. @@ -235,16 +243,10 @@ 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 sdkerrors.Wrap( @@ -277,11 +279,11 @@ func (msg MsgBeginRedelegate) Type() string { return TypeMsgBeginRedelegate } // GetSigners implements the sdk.Msg interface func (msg MsgBeginRedelegate) GetSigners() []sdk.AccAddress { - err := sdk.ValidateAccAddress(msg.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} + return []sdk.AccAddress{delAddr} } // GetSignBytes implements the sdk.Msg interface. @@ -295,23 +297,14 @@ 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 sdkerrors.Wrap( @@ -341,11 +334,11 @@ func (msg MsgUndelegate) Type() string { return TypeMsgUndelegate } // GetSigners implements the sdk.Msg interface. func (msg MsgUndelegate) GetSigners() []sdk.AccAddress { - err := sdk.ValidateAccAddress(msg.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) if err != nil { panic(err) } - return []sdk.AccAddress{sdk.AccAddress(msg.DelegatorAddress)} + return []sdk.AccAddress{delAddr} } // GetSignBytes implements the sdk.Msg interface. @@ -359,16 +352,10 @@ 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 sdkerrors.Wrap( diff --git a/x/staking/types/msg_test.go b/x/staking/types/msg_test.go index 5d3b350b5c..7e73972261 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -126,12 +126,12 @@ func TestMsgDelegate(t *testing.T) { bond sdk.Coin expectPass bool }{ - {"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}, + {"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}, } for _, tc := range tests { @@ -154,12 +154,12 @@ func TestMsgBeginRedelegate(t *testing.T) { amount sdk.Coin expectPass bool }{ - {"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}, + {"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}, } for _, tc := range tests { @@ -181,11 +181,11 @@ func TestMsgUndelegate(t *testing.T) { amount sdk.Coin expectPass bool }{ - {"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}, + {"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}, } for _, tc := range tests { diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 12426eb839..ffb231bd17 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -98,9 +98,7 @@ func (v Validators) Len() int { // Implements sort interface func (v Validators) Less(i, j int) bool { - valIBytes, _ := sdk.ValAddressToBytes(v[i].GetOperator().String()) - valJBytes, _ := sdk.ValAddressToBytes(v[j].GetOperator().String()) - return bytes.Compare(valIBytes, valJBytes) == -1 + return bytes.Compare(v[i].GetOperator().Bytes(), v[j].GetOperator().Bytes()) == -1 } // Implements sort interface @@ -124,9 +122,7 @@ func (valz ValidatorsByVotingPower) Less(i, j int, r sdk.Int) bool { if errI != nil || errJ != nil { return false } - bytesI, _ := sdk.ConsAddressToBytes(addrI.String()) - bytesJ, _ := sdk.ConsAddressToBytes(addrJ.String()) - return bytes.Compare(bytesI, bytesJ) == -1 + return bytes.Compare(addrI, addrJ) == -1 } return valz[i].ConsensusPower(r) > valz[j].ConsensusPower(r) } @@ -462,9 +458,13 @@ 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 "" + return nil } - return sdk.ValAddress(v.OperatorAddress) + addr, err := sdk.ValAddressFromBech32(v.OperatorAddress) + if err != nil { + panic(err) + } + return addr } // ConsPubKey returns the validator PubKey as a cryptotypes.PubKey. @@ -497,10 +497,10 @@ func (v Validator) OcConsPublicKey() (ocprotocrypto.PublicKey, error) { func (v Validator) GetConsAddr() (sdk.ConsAddress, error) { pk, ok := v.ConsensusPubkey.GetCachedValue().(cryptotypes.PubKey) if !ok { - return "", sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expecting cryptotypes.PubKey, got %T", pk) + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expecting cryptotypes.PubKey, got %T", pk) } - return sdk.BytesToConsAddress(pk.Address()), nil + return sdk.ConsAddress(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 39e6e0b09c..f4e4b96f98 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.BytesToValAddress(pk.Address()), pk) + vals[i] = newValidator(t, sdk.ValAddress(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.BytesToValAddress(pk2.Address()), pk) + vals[i] = newValidator(t, sdk.ValAddress(pk2.Address()), pk) vals[i].Status = types.Bonded vals[i].Tokens = sdk.NewInt(rand.Int63()) } @@ -310,7 +310,7 @@ func TestValidatorToTm(t *testing.T) { for i := range vals { pk := ed25519.GenPrivKey().PubKey() - val := newValidator(t, sdk.BytesToValAddress(pk.Address()), pk) + val := newValidator(t, sdk.ValAddress(pk.Address()), pk) val.Status = types.Bonded val.Tokens = sdk.NewInt(rand.Int63()) vals[i] = val diff --git a/x/stakingplus/authz.go b/x/stakingplus/authz.go index 5a56f8c969..7370acd69b 100644 --- a/x/stakingplus/authz.go +++ b/x/stakingplus/authz.go @@ -27,7 +27,7 @@ func (a CreateValidatorAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (foun } func (a CreateValidatorAuthorization) ValidateBasic() error { - if err := sdk.ValidateValAddress(a.ValidatorAddress); err != nil { + if _, err := sdk.ValAddressFromBech32(a.ValidatorAddress); err != nil { return err } diff --git a/x/stakingplus/keeper/keeper_test.go b/x/stakingplus/keeper/keeper_test.go index e2ac69a12c..d3ec6f3586 100644 --- a/x/stakingplus/keeper/keeper_test.go +++ b/x/stakingplus/keeper/keeper_test.go @@ -10,24 +10,24 @@ import ( "github.com/line/lbm-sdk/simapp" sdk "github.com/line/lbm-sdk/types" "github.com/line/lbm-sdk/x/foundation" - stakingtypes "github.com/line/lbm-sdk/x/staking/types" + govtypes "github.com/line/lbm-sdk/x/gov/types" + minttypes "github.com/line/lbm-sdk/x/mint/types" stakingkeeper "github.com/line/lbm-sdk/x/staking/keeper" + stakingtypes "github.com/line/lbm-sdk/x/staking/types" "github.com/line/lbm-sdk/x/stakingplus" "github.com/line/lbm-sdk/x/stakingplus/keeper" - govtypes "github.com/line/lbm-sdk/x/gov/types" - minttypes "github.com/line/lbm-sdk/x/mint/types" ) type KeeperTestSuite struct { suite.Suite - ctx sdk.Context + ctx sdk.Context - app *simapp.SimApp - keeper stakingkeeper.Keeper + app *simapp.SimApp + keeper stakingkeeper.Keeper msgServer stakingtypes.MsgServer stranger sdk.AccAddress - grantee sdk.AccAddress + grantee sdk.AccAddress balance sdk.Int } @@ -41,7 +41,7 @@ func (s *KeeperTestSuite) SetupTest() { s.msgServer = keeper.NewMsgServerImpl(s.keeper, s.app.FoundationKeeper) createAddress := func() sdk.AccAddress { - return sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + return sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } s.stranger = createAddress() @@ -70,11 +70,11 @@ func (s *KeeperTestSuite) SetupTest() { // allow Msg/CreateValidator s.app.FoundationKeeper.SetParams(s.ctx, &foundation.Params{ - Enabled: true, + Enabled: true, FoundationTax: sdk.ZeroDec(), }) err := s.app.FoundationKeeper.Grant(s.ctx, govtypes.ModuleName, s.grantee, &stakingplus.CreateValidatorAuthorization{ - ValidatorAddress: s.grantee.ToValAddress().String(), + ValidatorAddress: sdk.ValAddress(s.grantee).String(), }) s.Require().NoError(err) } diff --git a/x/stakingplus/keeper/msg_server.go b/x/stakingplus/keeper/msg_server.go index 531c3d674a..506df41ec4 100644 --- a/x/stakingplus/keeper/msg_server.go +++ b/x/stakingplus/keeper/msg_server.go @@ -1,6 +1,7 @@ package keeper import ( + "github.com/line/lbm-sdk/types/errors" stakingkeeper "github.com/line/lbm-sdk/x/staking/keeper" stakingtypes "github.com/line/lbm-sdk/x/staking/types" @@ -31,7 +32,10 @@ var _ stakingtypes.MsgServer = msgServer{} func (k msgServer) CreateValidator(goCtx context.Context, msg *stakingtypes.MsgCreateValidator) (*stakingtypes.MsgCreateValidatorResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if k.fk.GetEnabled(ctx) { - grantee := sdk.AccAddress(msg.DelegatorAddress) + grantee, err := sdk.AccAddressFromBech32(msg.DelegatorAddress) + if err != nil { + return nil, errors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", msg.DelegatorAddress) + } if err := k.fk.Accept(ctx, govtypes.ModuleName, grantee, msg); err != nil { return nil, err } diff --git a/x/stakingplus/keeper/msg_server_test.go b/x/stakingplus/keeper/msg_server_test.go index 8512d2906e..6b4eef982c 100644 --- a/x/stakingplus/keeper/msg_server_test.go +++ b/x/stakingplus/keeper/msg_server_test.go @@ -9,11 +9,11 @@ import ( func (s *KeeperTestSuite) TestMsgCreateValidator() { testCases := map[string]struct { delegator sdk.AccAddress - valid bool + valid bool }{ "valid request": { delegator: s.grantee, - valid: true, + valid: true, }, "no grant found": { delegator: s.stranger, @@ -27,7 +27,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { pk := simapp.CreateTestPubKeys(1)[0] delegation := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) req, err := stakingtypes.NewMsgCreateValidator( - tc.delegator.ToValAddress(), + sdk.ValAddress(tc.delegator), pk, delegation, stakingtypes.Description{}, diff --git a/x/token/genesis.go b/x/token/genesis.go index 70566e0a89..b23f152c16 100644 --- a/x/token/genesis.go +++ b/x/token/genesis.go @@ -24,7 +24,7 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidRequest.Wrap("balances cannot be empty") } for _, balance := range contractBalances.Balances { - if err := sdk.ValidateAccAddress(balance.Address); err != nil { + if _, err := sdk.AccAddressFromBech32(balance.Address); err != nil { return err } if err := validateAmount(balance.Amount); err != nil { @@ -63,7 +63,7 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidRequest.Wrap("grants cannot be empty") } for _, grant := range contractGrants.Grants { - if err := sdk.ValidateAccAddress(grant.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(grant.Grantee); err != nil { return err } if err := ValidatePermission(grant.Permission); err != nil { @@ -81,10 +81,10 @@ func ValidateGenesis(data GenesisState) error { return sdkerrors.ErrInvalidRequest.Wrap("authorizations cannot be empty") } for _, authorization := range contractAuthorizations.Authorizations { - if err := sdk.ValidateAccAddress(authorization.Holder); err != nil { + if _, err := sdk.AccAddressFromBech32(authorization.Holder); err != nil { return err } - if err := sdk.ValidateAccAddress(authorization.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(authorization.Operator); err != nil { return err } } diff --git a/x/token/genesis_test.go b/x/token/genesis_test.go index 8dc31da844..9b07779f19 100644 --- a/x/token/genesis_test.go +++ b/x/token/genesis_test.go @@ -12,7 +12,7 @@ import ( ) func TestValidateGenesis(t *testing.T) { - addr := sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) testCases := map[string]struct { gs *token.GenesisState valid bool diff --git a/x/token/keeper/genesis.go b/x/token/keeper/genesis.go index 44bc25176a..b2add2a356 100644 --- a/x/token/keeper/genesis.go +++ b/x/token/keeper/genesis.go @@ -14,7 +14,11 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *token.GenesisState) { for _, contractBalances := range data.Balances { for _, balance := range contractBalances.Balances { - k.setBalance(ctx, contractBalances.ContractId, sdk.AccAddress(balance.Address), balance.Amount) + addr, err := sdk.AccAddressFromBech32(balance.Address) + if err != nil { + panic(err) + } + k.setBalance(ctx, contractBalances.ContractId, addr, balance.Amount) } } @@ -24,13 +28,25 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *token.GenesisState) { for _, contractGrants := range data.Grants { for _, grant := range contractGrants.Grants { - k.setGrant(ctx, contractGrants.ContractId, sdk.AccAddress(grant.Grantee), grant.Permission) + grantee, err := sdk.AccAddressFromBech32(grant.Grantee) + if err != nil { + panic(err) + } + k.setGrant(ctx, contractGrants.ContractId, grantee, grant.Permission) } } for _, contractAuthorizations := range data.Authorizations { for _, authorization := range contractAuthorizations.Authorizations { - k.setAuthorization(ctx, contractAuthorizations.ContractId, sdk.AccAddress(authorization.Holder), sdk.AccAddress(authorization.Operator)) + holder, err := sdk.AccAddressFromBech32(authorization.Holder) + if err != nil { + panic(err) + } + operator, err := sdk.AccAddressFromBech32(authorization.Operator) + if err != nil { + panic(err) + } + k.setAuthorization(ctx, contractAuthorizations.ContractId, holder, operator) } } diff --git a/x/token/keeper/grpc_query.go b/x/token/keeper/grpc_query.go index 380e6cdf09..766cbd7e2e 100644 --- a/x/token/keeper/grpc_query.go +++ b/x/token/keeper/grpc_query.go @@ -36,12 +36,13 @@ func (s queryServer) Balance(c context.Context, req *token.QueryBalanceRequest) if err := token.ValidateContractID(req.ContractId); err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Address); err != nil { + addr, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", req.Address) } ctx := sdk.UnwrapSDKContext(c) - balance := s.keeper.GetBalance(ctx, req.ContractId, sdk.AccAddress(req.Address)) + balance := s.keeper.GetBalance(ctx, req.ContractId, addr) return &token.QueryBalanceResponse{Amount: balance}, nil } @@ -156,7 +157,8 @@ func (s queryServer) Grant(c context.Context, req *token.QueryGrantRequest) (*to if err := token.ValidateContractID(req.ContractId); err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Grantee); err != nil { + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.Grantee) } @@ -165,7 +167,7 @@ func (s queryServer) Grant(c context.Context, req *token.QueryGrantRequest) (*to } ctx := sdk.UnwrapSDKContext(c) - grant, err := s.keeper.GetGrant(ctx, req.ContractId, sdk.AccAddress(req.Grantee), req.Permission) + grant, err := s.keeper.GetGrant(ctx, req.ContractId, grantee, req.Permission) if err != nil { return nil, err } @@ -181,13 +183,14 @@ func (s queryServer) GranteeGrants(c context.Context, req *token.QueryGranteeGra if err := token.ValidateContractID(req.ContractId); err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Grantee); err != nil { + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.Grantee) } ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) - grantStore := prefix.NewStore(store, grantKeyPrefixByGrantee(req.ContractId, sdk.AccAddress(req.Grantee))) + grantStore := prefix.NewStore(store, grantKeyPrefixByGrantee(req.ContractId, grantee)) var grants []token.Grant pageRes, err := query.Paginate(grantStore, req.Pagination, func(key []byte, _ []byte) error { permission := token.Permission(key[0]) @@ -212,15 +215,17 @@ func (s queryServer) Authorization(c context.Context, req *token.QueryAuthorizat if err := token.ValidateContractID(req.ContractId); err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Operator); err != nil { + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) } - if err := sdk.ValidateAccAddress(req.Holder); err != nil { + holder, err := sdk.AccAddressFromBech32(req.Holder) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", req.Holder) } ctx := sdk.UnwrapSDKContext(c) - authorization, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.Holder), sdk.AccAddress(req.Operator)) + authorization, err := s.keeper.GetAuthorization(ctx, req.ContractId, holder, operator) if err != nil { return nil, err } @@ -236,13 +241,14 @@ func (s queryServer) OperatorAuthorizations(c context.Context, req *token.QueryO if err := token.ValidateContractID(req.ContractId); err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Operator); err != nil { + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) } ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) - authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, sdk.AccAddress(req.Operator))) + authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, operator)) var authorizations []token.Authorization pageRes, err := query.Paginate(authorizationStore, req.Pagination, func(key []byte, value []byte) error { holder := sdk.AccAddress(key) @@ -267,16 +273,18 @@ func (s queryServer) Approved(c context.Context, req *token.QueryApprovedRequest if err := token.ValidateContractID(req.ContractId); err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Address); err != nil { + addr, err := sdk.AccAddressFromBech32(req.Address) + if err != nil { return nil, err } - if err := sdk.ValidateAccAddress(req.Approver); err != nil { + approver, err := sdk.AccAddressFromBech32(req.Approver) + if err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) - _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.Approver), sdk.AccAddress(req.Address)) - approved := (err == nil) + _, err = s.keeper.GetAuthorization(ctx, req.ContractId, approver, addr) + approved := err == nil return &token.QueryApprovedResponse{Approved: approved}, nil } diff --git a/x/token/keeper/keeper_test.go b/x/token/keeper/keeper_test.go index 62f1603280..646cdb4f82 100644 --- a/x/token/keeper/keeper_test.go +++ b/x/token/keeper/keeper_test.go @@ -34,15 +34,15 @@ type KeeperTestSuite struct { } func createRandomAccounts(accNum int) []sdk.AccAddress { - seenAddresses := make(map[sdk.AccAddress]bool, accNum) + seenAddresses := make(map[string]bool, accNum) addresses := make([]sdk.AccAddress, accNum) for i := 0; i < accNum; i++ { var address sdk.AccAddress for { pk := secp256k1.GenPrivKey().PubKey() - address = sdk.BytesToAccAddress(pk.Address()) - if !seenAddresses[address] { - seenAddresses[address] = true + address = sdk.AccAddress(pk.Address()) + if !seenAddresses[address.String()] { + seenAddresses[address.String()] = true break } } diff --git a/x/token/keeper/keys.go b/x/token/keeper/keys.go index d4eb82e85a..f18ccf163f 100644 --- a/x/token/keeper/keys.go +++ b/x/token/keeper/keys.go @@ -55,7 +55,7 @@ func splitBalanceKey(key []byte) (contractID string, address sdk.AccAddress) { contractID = string(key[begin:end]) begin = end - address = sdk.AccAddress(key[begin:]) + address = key[begin:] return } @@ -143,7 +143,7 @@ func splitGrantKey(key []byte) (contractID string, grantee sdk.AccAddress, permi begin = end + 1 end = begin + int(key[begin-1]) - grantee = sdk.AccAddress(key[begin:end]) + grantee = key[begin:end] begin = end permission = token.Permission(key[begin]) @@ -199,10 +199,10 @@ func splitAuthorizationKey(key []byte) (contractID string, operator, holder sdk. begin = end + 1 end = begin + int(key[begin-1]) - operator = sdk.AccAddress(key[begin:end]) + operator = key[begin:end] begin = end - holder = sdk.AccAddress(key[begin:]) + holder = key[begin:] return } diff --git a/x/token/keeper/msg_server.go b/x/token/keeper/msg_server.go index 38bfc95991..46d12c849e 100644 --- a/x/token/keeper/msg_server.go +++ b/x/token/keeper/msg_server.go @@ -26,7 +26,15 @@ var _ token.MsgServer = msgServer{} func (s msgServer) Send(c context.Context, req *token.MsgSend) (*token.MsgSendResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.Send(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.From) + } + to, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", req.To) + } + if err := s.keeper.Send(ctx, req.ContractId, from, to, req.Amount); err != nil { return nil, err } @@ -49,11 +57,24 @@ func (s msgServer) Send(c context.Context, req *token.MsgSend) (*token.MsgSendRe func (s msgServer) OperatorSend(c context.Context, req *token.MsgOperatorSend) (*token.MsgOperatorSendResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Operator)); err != nil { + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.From) + } + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) + } + to, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", req.To) + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, from, operator); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - if err := s.keeper.Send(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + if err := s.keeper.Send(ctx, req.ContractId, from, to, req.Amount); err != nil { return nil, err } @@ -76,11 +97,24 @@ func (s msgServer) OperatorSend(c context.Context, req *token.MsgOperatorSend) ( func (s msgServer) TransferFrom(c context.Context, req *token.MsgTransferFrom) (*token.MsgTransferFromResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.Proxy)); err != nil { + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.From) + } + proxy, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", req.Proxy) + } + to, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.To) + } + + if _, err := s.keeper.GetAuthorization(ctx, req.ContractId, from, proxy); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } - if err := s.keeper.Send(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + if err := s.keeper.Send(ctx, req.ContractId, from, to, req.Amount); err != nil { return nil, err } @@ -102,7 +136,15 @@ func (s msgServer) TransferFrom(c context.Context, req *token.MsgTransferFrom) ( // AuthorizeOperator allows one to send tokens on behalf of the token holder func (s msgServer) AuthorizeOperator(c context.Context, req *token.MsgAuthorizeOperator) (*token.MsgAuthorizeOperatorResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, sdk.AccAddress(req.Holder), sdk.AccAddress(req.Operator)); err != nil { + holder, err := sdk.AccAddressFromBech32(req.Holder) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", req.Holder) + } + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) + } + if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, holder, operator); err != nil { return nil, err } @@ -122,7 +164,15 @@ func (s msgServer) AuthorizeOperator(c context.Context, req *token.MsgAuthorizeO // RevokeOperator revokes one to send tokens on behalf of the token holder func (s msgServer) RevokeOperator(c context.Context, req *token.MsgRevokeOperator) (*token.MsgRevokeOperatorResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.RevokeOperator(ctx, req.ContractId, sdk.AccAddress(req.Holder), sdk.AccAddress(req.Operator)); err != nil { + holder, err := sdk.AccAddressFromBech32(req.Holder) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", req.Holder) + } + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) + } + if err := s.keeper.RevokeOperator(ctx, req.ContractId, holder, operator); err != nil { return nil, err } @@ -140,7 +190,15 @@ func (s msgServer) RevokeOperator(c context.Context, req *token.MsgRevokeOperato // Approve allows one to send tokens on behalf of the approver func (s msgServer) Approve(c context.Context, req *token.MsgApprove) (*token.MsgApproveResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, sdk.AccAddress(req.Approver), sdk.AccAddress(req.Proxy)); err != nil { + approver, err := sdk.AccAddressFromBech32(req.Approver) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid approver address: %s", req.Approver) + } + proxy, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", req.Proxy) + } + if err := s.keeper.AuthorizeOperator(ctx, req.ContractId, approver, proxy); err != nil { return nil, err } @@ -171,7 +229,15 @@ func (s msgServer) Issue(c context.Context, req *token.MsgIssue) (*token.MsgIssu Mintable: req.Mintable, } - s.keeper.Issue(ctx, class, sdk.AccAddress(req.Owner), sdk.AccAddress(req.To), req.Amount) + owner, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", req.Owner) + } + to, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", req.To) + } + s.keeper.Issue(ctx, class, owner, to, req.Amount) return &token.MsgIssueResponse{Id: contractID}, nil } @@ -180,9 +246,14 @@ func (s msgServer) Issue(c context.Context, req *token.MsgIssue) (*token.MsgIssu func (s msgServer) Grant(c context.Context, req *token.MsgGrant) (*token.MsgGrantResponse, error) { ctx := sdk.UnwrapSDKContext(c) - granter := sdk.AccAddress(req.Granter) - grantee := sdk.AccAddress(req.Grantee) - + granter, err := sdk.AccAddressFromBech32(req.Granter) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", req.Granter) + } + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.Grantee) + } if _, err := s.keeper.GetGrant(ctx, req.ContractId, granter, req.Permission); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -199,8 +270,10 @@ func (s msgServer) Grant(c context.Context, req *token.MsgGrant) (*token.MsgGran func (s msgServer) Abandon(c context.Context, req *token.MsgAbandon) (*token.MsgAbandonResponse, error) { ctx := sdk.UnwrapSDKContext(c) - grantee := sdk.AccAddress(req.Grantee) - + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.Grantee) + } if _, err := s.keeper.GetGrant(ctx, req.ContractId, grantee, req.Permission); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } @@ -214,8 +287,14 @@ func (s msgServer) Abandon(c context.Context, req *token.MsgAbandon) (*token.Msg func (s msgServer) GrantPermission(c context.Context, req *token.MsgGrantPermission) (*token.MsgGrantPermissionResponse, error) { ctx := sdk.UnwrapSDKContext(c) - granter := sdk.AccAddress(req.From) - grantee := sdk.AccAddress(req.To) + granter, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", req.From) + } + grantee, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.To) + } permission := token.Permission(token.LegacyPermissionFromString(req.Permission)) if _, err := s.keeper.GetGrant(ctx, req.ContractId, granter, permission); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) @@ -233,7 +312,10 @@ func (s msgServer) GrantPermission(c context.Context, req *token.MsgGrantPermiss func (s msgServer) RevokePermission(c context.Context, req *token.MsgRevokePermission) (*token.MsgRevokePermissionResponse, error) { ctx := sdk.UnwrapSDKContext(c) - grantee := sdk.AccAddress(req.From) + grantee, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.From) + } permission := token.Permission(token.LegacyPermissionFromString(req.Permission)) if _, err := s.keeper.GetGrant(ctx, req.ContractId, grantee, permission); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) @@ -247,7 +329,15 @@ func (s msgServer) RevokePermission(c context.Context, req *token.MsgRevokePermi // Mint defines a method to mint tokens func (s msgServer) Mint(c context.Context, req *token.MsgMint) (*token.MsgMintResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.Mint(ctx, req.ContractId, sdk.AccAddress(req.From), sdk.AccAddress(req.To), req.Amount); err != nil { + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.From) + } + to, err := sdk.AccAddressFromBech32(req.To) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", req.To) + } + if err := s.keeper.Mint(ctx, req.ContractId, from, to, req.Amount); err != nil { return nil, err } @@ -257,7 +347,11 @@ func (s msgServer) Mint(c context.Context, req *token.MsgMint) (*token.MsgMintRe // Burn defines a method to burn tokens func (s msgServer) Burn(c context.Context, req *token.MsgBurn) (*token.MsgBurnResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.Burn(ctx, req.ContractId, sdk.AccAddress(req.From), req.Amount); err != nil { + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.From) + } + if err := s.keeper.Burn(ctx, req.ContractId, from, req.Amount); err != nil { return nil, err } @@ -267,7 +361,15 @@ func (s msgServer) Burn(c context.Context, req *token.MsgBurn) (*token.MsgBurnRe // OperatorBurn defines a method for the operator to burn tokens on the behalf of the holder. func (s msgServer) OperatorBurn(c context.Context, req *token.MsgOperatorBurn) (*token.MsgOperatorBurnResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.OperatorBurn(ctx, req.ContractId, sdk.AccAddress(req.Operator), sdk.AccAddress(req.From), req.Amount); err != nil { + operator, err := sdk.AccAddressFromBech32(req.Operator) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", req.Operator) + } + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.From) + } + if err := s.keeper.OperatorBurn(ctx, req.ContractId, operator, from, req.Amount); err != nil { return nil, err } @@ -277,7 +379,15 @@ func (s msgServer) OperatorBurn(c context.Context, req *token.MsgOperatorBurn) ( // BurnFrom defines a method for the proxy to burn tokens on the behalf of the holder. func (s msgServer) BurnFrom(c context.Context, req *token.MsgBurnFrom) (*token.MsgBurnFromResponse, error) { ctx := sdk.UnwrapSDKContext(c) - if err := s.keeper.OperatorBurn(ctx, req.ContractId, sdk.AccAddress(req.Proxy), sdk.AccAddress(req.From), req.Amount); err != nil { + proxy, err := sdk.AccAddressFromBech32(req.Proxy) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", req.Proxy) + } + from, err := sdk.AccAddressFromBech32(req.From) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", req.From) + } + if err := s.keeper.OperatorBurn(ctx, req.ContractId, proxy, from, req.Amount); err != nil { return nil, err } @@ -288,7 +398,10 @@ func (s msgServer) BurnFrom(c context.Context, req *token.MsgBurnFrom) (*token.M func (s msgServer) Modify(c context.Context, req *token.MsgModify) (*token.MsgModifyResponse, error) { ctx := sdk.UnwrapSDKContext(c) - grantee := sdk.AccAddress(req.Owner) + grantee, err := sdk.AccAddressFromBech32(req.Owner) + if err != nil { + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", req.Owner) + } if _, err := s.keeper.GetGrant(ctx, req.ContractId, grantee, token.PermissionModify); err != nil { return nil, sdkerrors.ErrUnauthorized.Wrap(err.Error()) } diff --git a/x/token/keeper/send_test.go b/x/token/keeper/send_test.go index 348900c369..4bfdb89147 100644 --- a/x/token/keeper/send_test.go +++ b/x/token/keeper/send_test.go @@ -49,15 +49,19 @@ func (s *KeeperTestSuite) TestAuthorizeOperator() { s.contractID: "valid", dummyContractID: "not-exists", } - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", - s.stranger: "stranger", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", + s.stranger.String(): "stranger", } for id, idDesc := range contractDescriptions { - for operator, operatorDesc := range userDescriptions { - for from, fromDesc := range userDescriptions { + for operatorStr, operatorDesc := range userDescriptions { + operator, err := sdk.AccAddressFromBech32(operatorStr) + s.Require().NoError(err) + for fromStr, fromDesc := range userDescriptions { + from, err := sdk.AccAddressFromBech32(fromStr) + s.Require().NoError(err) name := fmt.Sprintf("ContractID: %s, Operator: %s, From: %s", idDesc, operatorDesc, fromDesc) s.Run(name, func() { ctx, _ := s.ctx.CacheContext() @@ -87,14 +91,18 @@ func (s *KeeperTestSuite) TestRevokeOperator() { s.contractID: "valid", dummyContractID: "not-exists", } - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", } for id, idDesc := range contractDescriptions { - for operator, operatorDesc := range userDescriptions { - for from, fromDesc := range userDescriptions { + for operatorStr, operatorDesc := range userDescriptions { + operator, err := sdk.AccAddressFromBech32(operatorStr) + s.Require().NoError(err) + for fromStr, fromDesc := range userDescriptions { + from, err := sdk.AccAddressFromBech32(fromStr) + s.Require().NoError(err) name := fmt.Sprintf("ContractID: %s, Operator: %s, From: %s", idDesc, operatorDesc, fromDesc) s.Run(name, func() { ctx, _ := s.ctx.CacheContext() diff --git a/x/token/keeper/supply.go b/x/token/keeper/supply.go index 0a370d102f..c04e833a73 100644 --- a/x/token/keeper/supply.go +++ b/x/token/keeper/supply.go @@ -19,7 +19,7 @@ func (k Keeper) Issue(ctx sdk.Context, class token.TokenClass, owner, to sdk.Acc ) } for _, permission := range permissions { - k.Grant(ctx, class.ContractId, "", owner, permission) + k.Grant(ctx, class.ContractId, nil, owner, permission) } k.mintToken(ctx, class.ContractId, to, amount) diff --git a/x/token/keeper/supply_test.go b/x/token/keeper/supply_test.go index 200db9e19d..a5d77cb55d 100644 --- a/x/token/keeper/supply_test.go +++ b/x/token/keeper/supply_test.go @@ -36,14 +36,16 @@ func (s *KeeperTestSuite) TestIssue() { } func (s *KeeperTestSuite) TestMint() { - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", } to := s.vendor amount := sdk.OneInt() - for grantee, desc := range userDescriptions { + for granteeStr, desc := range userDescriptions { + grantee, err := sdk.AccAddressFromBech32(granteeStr) + s.Require().NoError(err) name := fmt.Sprintf("Grantee: %s", desc) s.Run(name, func() { ctx, _ := s.ctx.CacheContext() @@ -60,16 +62,18 @@ func (s *KeeperTestSuite) TestMint() { } func (s *KeeperTestSuite) TestBurn() { - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", } amountDescriptions := map[sdk.Int]string{ s.balance: "limit", s.balance.Add(sdk.OneInt()): "excess", } - for from, fromDesc := range userDescriptions { + for fromStr, fromDesc := range userDescriptions { + from, err := sdk.AccAddressFromBech32(fromStr) + s.Require().NoError(err) for amount, amountDesc := range amountDescriptions { name := fmt.Sprintf("From: %s, Amount: %s", fromDesc, amountDesc) s.Run(name, func() { @@ -88,17 +92,21 @@ func (s *KeeperTestSuite) TestBurn() { } func (s *KeeperTestSuite) TestOperatorBurn() { - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", } amountDescriptions := map[sdk.Int]string{ s.balance: "limit", s.balance.Add(sdk.OneInt()): "excess", } - for operator, operatorDesc := range userDescriptions { - for from, fromDesc := range userDescriptions { + for operatorStr, operatorDesc := range userDescriptions { + operator, err := sdk.AccAddressFromBech32(operatorStr) + s.Require().NoError(err) + for fromStr, fromDesc := range userDescriptions { + from, err := sdk.AccAddressFromBech32(fromStr) + s.Require().NoError(err) for amount, amountDesc := range amountDescriptions { name := fmt.Sprintf("Operator: %s, From: %s, Amount: %s", operatorDesc, fromDesc, amountDesc) s.Run(name, func() { @@ -123,10 +131,10 @@ func (s *KeeperTestSuite) TestModify() { s.contractID: "valid", "fee1dead": "not-exist", } - userDescriptions := map[sdk.AccAddress]string{ - s.vendor: "vendor", - s.operator: "operator", - s.customer: "customer", + userDescriptions := map[string]string{ + s.vendor.String(): "vendor", + s.operator.String(): "operator", + s.customer.String(): "customer", } changes := []token.Pair{ {Field: token.AttributeKeyName.String(), Value: "new name"}, @@ -135,7 +143,9 @@ func (s *KeeperTestSuite) TestModify() { } for contractID, contractDesc := range contractDescriptions { - for grantee, granteeDesc := range userDescriptions { + for granteeStr, granteeDesc := range userDescriptions { + grantee, err := sdk.AccAddressFromBech32(granteeStr) + s.Require().NoError(err) name := fmt.Sprintf("Grantee: %s, Contract: %s", granteeDesc, contractDesc) s.Run(name, func() { ctx, _ := s.ctx.CacheContext() diff --git a/x/token/msgs.go b/x/token/msgs.go index d0f45fc1dc..3a89685891 100644 --- a/x/token/msgs.go +++ b/x/token/msgs.go @@ -13,10 +13,10 @@ func (m MsgSend) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -29,7 +29,7 @@ func (m MsgSend) ValidateBasic() error { // GetSigners implements Msg func (m MsgSend) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -41,13 +41,13 @@ func (m MsgOperatorSend) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -60,7 +60,7 @@ func (m MsgOperatorSend) ValidateBasic() error { // GetSigners implements Msg func (m MsgOperatorSend) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -72,13 +72,13 @@ func (m MsgTransferFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -91,7 +91,7 @@ func (m MsgTransferFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgTransferFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } @@ -103,10 +103,10 @@ func (m MsgAuthorizeOperator) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Holder); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Holder); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", m.Holder) } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -115,7 +115,7 @@ func (m MsgAuthorizeOperator) ValidateBasic() error { // GetSigners implements Msg. func (m MsgAuthorizeOperator) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Holder) + signer, _ := sdk.AccAddressFromBech32(m.Holder) return []sdk.AccAddress{signer} } @@ -127,10 +127,10 @@ func (m MsgRevokeOperator) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Holder); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Holder); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid holder address: %s", m.Holder) } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } @@ -139,7 +139,7 @@ func (m MsgRevokeOperator) ValidateBasic() error { // GetSigners implements Msg. func (m MsgRevokeOperator) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Holder) + signer, _ := sdk.AccAddressFromBech32(m.Holder) return []sdk.AccAddress{signer} } @@ -151,10 +151,10 @@ func (m MsgApprove) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Approver); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Approver); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid approver address: %s", m.Approver) } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } @@ -163,7 +163,7 @@ func (m MsgApprove) ValidateBasic() error { // GetSigners implements Msg. func (m MsgApprove) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Approver) + signer, _ := sdk.AccAddressFromBech32(m.Approver) return []sdk.AccAddress{signer} } @@ -171,11 +171,11 @@ var _ sdk.Msg = (*MsgIssue)(nil) // ValidateBasic implements Msg. func (m MsgIssue) ValidateBasic() error { - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", m.Owner) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -208,7 +208,7 @@ func (m MsgIssue) ValidateBasic() error { // GetSigners implements Msg. func (m MsgIssue) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Owner) + signer, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{signer} } @@ -220,10 +220,10 @@ func (m MsgGrant) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Granter); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Granter); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", m.Granter) } - if err := sdk.ValidateAccAddress(m.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Grantee); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.Grantee) } @@ -236,7 +236,7 @@ func (m MsgGrant) ValidateBasic() error { // GetSigners implements Msg func (m MsgGrant) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Granter) + signer, _ := sdk.AccAddressFromBech32(m.Granter) return []sdk.AccAddress{signer} } @@ -248,7 +248,7 @@ func (m MsgAbandon) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Grantee); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Grantee); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.Grantee) } @@ -261,7 +261,7 @@ func (m MsgAbandon) ValidateBasic() error { // GetSigners implements Msg func (m MsgAbandon) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Grantee) + signer, _ := sdk.AccAddressFromBech32(m.Grantee) return []sdk.AccAddress{signer} } @@ -273,10 +273,10 @@ func (m MsgGrantPermission) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.To) } @@ -289,7 +289,7 @@ func (m MsgGrantPermission) ValidateBasic() error { // GetSigners implements Msg func (m MsgGrantPermission) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -301,7 +301,7 @@ func (m MsgRevokePermission) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -314,7 +314,7 @@ func (m MsgRevokePermission) ValidateBasic() error { // GetSigners implements Msg func (m MsgRevokePermission) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -325,11 +325,11 @@ func (m MsgMint) ValidateBasic() error { if err := ValidateContractID(m.ContractId); err != nil { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.From) } - if err := sdk.ValidateAccAddress(m.To); err != nil { + if _, err := sdk.AccAddressFromBech32(m.To); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", m.To) } @@ -342,7 +342,7 @@ func (m MsgMint) ValidateBasic() error { // GetSigners implements Msg func (m MsgMint) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -353,7 +353,7 @@ func (m MsgBurn) ValidateBasic() error { if err := ValidateContractID(m.ContractId); err != nil { return err } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -366,7 +366,7 @@ func (m MsgBurn) ValidateBasic() error { // GetSigners implements Msg func (m MsgBurn) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.From) + signer, _ := sdk.AccAddressFromBech32(m.From) return []sdk.AccAddress{signer} } @@ -378,10 +378,10 @@ func (m MsgOperatorBurn) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Operator); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Operator); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid operator address: %s", m.Operator) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -394,7 +394,7 @@ func (m MsgOperatorBurn) ValidateBasic() error { // GetSigners implements Msg func (m MsgOperatorBurn) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Operator) + signer, _ := sdk.AccAddressFromBech32(m.Operator) return []sdk.AccAddress{signer} } @@ -406,10 +406,10 @@ func (m MsgBurnFrom) ValidateBasic() error { return err } - if err := sdk.ValidateAccAddress(m.Proxy); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Proxy); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid proxy address: %s", m.Proxy) } - if err := sdk.ValidateAccAddress(m.From); err != nil { + if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", m.From) } @@ -422,7 +422,7 @@ func (m MsgBurnFrom) ValidateBasic() error { // GetSigners implements Msg func (m MsgBurnFrom) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Proxy) + signer, _ := sdk.AccAddressFromBech32(m.Proxy) return []sdk.AccAddress{signer} } @@ -433,7 +433,7 @@ func (m MsgModify) ValidateBasic() error { if err := ValidateContractID(m.ContractId); err != nil { return err } - if err := sdk.ValidateAccAddress(m.Owner); err != nil { + if _, err := sdk.AccAddressFromBech32(m.Owner); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", m.Owner) } @@ -457,6 +457,6 @@ func (m MsgModify) ValidateBasic() error { // GetSigners implements Msg func (m MsgModify) GetSigners() []sdk.AccAddress { - signer := sdk.AccAddress(m.Owner) + signer, _ := sdk.AccAddressFromBech32(m.Owner) return []sdk.AccAddress{signer} } diff --git a/x/token/msgs_test.go b/x/token/msgs_test.go index 3990605697..8c89a8d69c 100644 --- a/x/token/msgs_test.go +++ b/x/token/msgs_test.go @@ -13,7 +13,7 @@ import ( func TestMsgSend(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -32,7 +32,6 @@ func TestMsgSend(t *testing.T) { }, "empty from": { contractID: "deadbeef", - from: "", to: addrs[1], amount: sdk.OneInt(), }, @@ -62,21 +61,21 @@ func TestMsgSend(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgOperatorSend(t *testing.T) { addrs := make([]sdk.AccAddress, 3) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -137,21 +136,21 @@ func TestMsgOperatorSend(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgTransferFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 3) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -212,21 +211,21 @@ func TestMsgTransferFrom(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.proxy}, msg.GetSigners()) } } func TestMsgAuthorizeOperator(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -250,8 +249,8 @@ func TestMsgAuthorizeOperator(t *testing.T) { operator: addrs[1], }, "empty operator": { - contractID: "deadbeef", holder: addrs[0], + contractID: "deadbeef", }, } @@ -262,21 +261,21 @@ func TestMsgAuthorizeOperator(t *testing.T) { Operator: tc.operator.String(), } - require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) } } func TestMsgRevokeOperator(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -312,21 +311,21 @@ func TestMsgRevokeOperator(t *testing.T) { Operator: tc.operator.String(), } - require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.holder}, msg.GetSigners()) } } func TestMsgApprove(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -362,21 +361,21 @@ func TestMsgApprove(t *testing.T) { Proxy: tc.proxy.String(), } - require.Equal(t, []sdk.AccAddress{tc.approver}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.approver}, msg.GetSigners()) } } func TestMsgIssue(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -502,21 +501,21 @@ func TestMsgIssue(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.owner}, msg.GetSigners()) } } func TestMsgMint(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -564,21 +563,21 @@ func TestMsgMint(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) } } func TestMsgBurn(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -615,21 +614,21 @@ func TestMsgBurn(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgOperatorBurn(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -677,21 +676,21 @@ func TestMsgOperatorBurn(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.operator}, msg.GetSigners()) } } func TestMsgBurnFrom(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -739,21 +738,21 @@ func TestMsgBurnFrom(t *testing.T) { Amount: tc.amount, } - require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) } } func TestMsgModify(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } validChange := token.Pair{Field: token.AttributeKeyName.String(), Value: "New test"} @@ -808,21 +807,21 @@ func TestMsgModify(t *testing.T) { Changes: tc.changes, } - require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) } } func TestMsgGrant(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -869,21 +868,21 @@ func TestMsgGrant(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.granter}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.granter}, msg.GetSigners()) } } func TestMsgAbandon(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -919,21 +918,21 @@ func TestMsgAbandon(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.grantee}, msg.GetSigners()) } } func TestMsgGrantPermission(t *testing.T) { addrs := make([]sdk.AccAddress, 2) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -980,21 +979,21 @@ func TestMsgGrantPermission(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } func TestMsgRevokePermission(t *testing.T) { addrs := make([]sdk.AccAddress, 1) for i := range addrs { - addrs[i] = sdk.BytesToAccAddress(secp256k1.GenPrivKey().PubKey().Address()) + addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } testCases := map[string]struct { @@ -1030,13 +1029,13 @@ func TestMsgRevokePermission(t *testing.T) { Permission: tc.permission, } - require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) - err := msg.ValidateBasic() - if tc.valid { - require.NoError(t, err, name) - } else { + if !tc.valid { require.Error(t, err, name) + return } + require.NoError(t, err, name) + + require.Equal(t, []sdk.AccAddress{tc.from}, msg.GetSigners()) } } diff --git a/x/upgrade/client/rest/tx.go b/x/upgrade/client/rest/tx.go index 2aa3ed8a5f..778ad60e43 100644 --- a/x/upgrade/client/rest/tx.go +++ b/x/upgrade/client/rest/tx.go @@ -71,7 +71,10 @@ func newPostPlanHandler(clientCtx client.Context) http.HandlerFunc { return } - fromAddr := sdk.AccAddress(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + if rest.CheckBadRequestError(w, err) { + return + } var t time.Time if req.UpgradeTime != "" { @@ -109,7 +112,10 @@ func newCancelPlanHandler(clientCtx client.Context) http.HandlerFunc { return } - fromAddr := sdk.AccAddress(req.BaseReq.From) + fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From) + if rest.CheckBadRequestError(w, err) { + return + } 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 5557c431fd..58abd3a22f 100644 --- a/x/wasm/client/cli/genesis_msg.go +++ b/x/wasm/client/cli/genesis_msg.go @@ -215,7 +215,6 @@ func GenesisListCodesCmd(defaultNodeHome string, genReader GenesisReader) *cobra return err } return printJSONOutput(cmd, all) - }, } cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") @@ -277,11 +276,11 @@ func getAllCodes(state *types.GenesisState) ([]CodeMeta, error) { accessConfig = *msg.InstantiatePermission } else { // default - err := sdk.ValidateAccAddress(msg.Sender) + creator, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, fmt.Errorf("sender: %s", err) } - accessConfig = state.Params.InstantiateDefaultPermission.With(sdk.AccAddress(msg.Sender)) + accessConfig = state.Params.InstantiateDefaultPermission.With(creator) } hash := sha256.Sum256(msg.WASMByteCode) all = append(all, CodeMeta{ @@ -483,29 +482,32 @@ func codeSeqValue(state *types.GenesisState) uint64 { func getActorAddress(cmd *cobra.Command) (sdk.AccAddress, error) { actorArg, err := cmd.Flags().GetString(flagRunAs) if err != nil { - return "", fmt.Errorf("run-as: %s", err.Error()) + return nil, fmt.Errorf("run-as: %s", err.Error()) } if len(actorArg) == 0 { - return "", errors.New("run-as address is required") + return nil, errors.New("run-as address is required") } - err = sdk.ValidateAccAddress(actorArg) + actorAddr, err := sdk.AccAddressFromBech32(actorArg) if err == nil { - return sdk.AccAddress(actorArg), nil + return actorAddr, nil } inBuf := bufio.NewReader(cmd.InOrStdin()) - keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend) + if err != nil { + return nil, err + } homeDir := client.GetClientContextFromCmd(cmd).HomeDir // attempt to lookup address from Keybase if no address was provided kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, homeDir, inBuf) if err != nil { - return "", err + return nil, err } info, err := kb.Key(actorArg) if err != nil { - return "", fmt.Errorf("failed to get address from Keybase: %w", err) + return nil, fmt.Errorf("failed to get address from Keybase: %w", err) } return info.GetAddress(), nil } diff --git a/x/wasm/client/cli/gov_tx.go b/x/wasm/client/cli/gov_tx.go index 54b42a36f8..84e9bfaf5f 100644 --- a/x/wasm/client/cli/gov_tx.go +++ b/x/wasm/client/cli/gov_tx.go @@ -624,11 +624,11 @@ func parseAccessConfig(config string) (types.AccessConfig, error) { case "everybody": return types.AllowEverybody, nil default: - err := sdk.ValidateAccAddress(config) + address, err := sdk.AccAddressFromBech32(config) if err != nil { return types.AccessConfig{}, fmt.Errorf("unable to parse address %s", config) } - return types.AccessTypeOnlyAddress.With(sdk.AccAddress(config)), nil + return types.AccessTypeOnlyAddress.With(address), nil } } @@ -658,6 +658,7 @@ func parseAccessConfigUpdates(args []string) ([]types.AccessConfigUpdate, error) } return updates, nil } + func ProposalUpdateInstantiateConfigCmd() *cobra.Command { bech32Prefix := sdk.GetConfig().GetBech32AccountAddrPrefix() cmd := &cobra.Command{ diff --git a/x/wasm/client/cli/query.go b/x/wasm/client/cli/query.go index d06e07a864..128ac8bc8d 100644 --- a/x/wasm/client/cli/query.go +++ b/x/wasm/client/cli/query.go @@ -229,13 +229,12 @@ func GetCmdGetContractInfo() *cobra.Command { Aliases: []string{"meta", "c"}, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) if err != nil { return err } - err = sdk.ValidateAccAddress(args[0]) + _, err = sdk.AccAddressFromBech32(args[0]) if err != nil { return err } @@ -272,7 +271,6 @@ func GetCmdGetContractState() *cobra.Command { GetCmdGetContractStateSmart(), ) return cmd - } func GetCmdGetContractStateAll() *cobra.Command { @@ -287,7 +285,7 @@ func GetCmdGetContractStateAll() *cobra.Command { return err } - err = sdk.ValidateAccAddress(args[0]) + _, err = sdk.AccAddressFromBech32(args[0]) if err != nil { return err } @@ -328,7 +326,7 @@ func GetCmdGetContractStateRaw() *cobra.Command { return err } - err = sdk.ValidateAccAddress(args[0]) + _, err = sdk.AccAddressFromBech32(args[0]) if err != nil { return err } @@ -369,7 +367,7 @@ func GetCmdGetContractStateSmart() *cobra.Command { return err } - err = sdk.ValidateAccAddress(args[0]) + _, err = sdk.AccAddressFromBech32(args[0]) if err != nil { return err } @@ -418,7 +416,7 @@ func GetCmdGetContractHistory() *cobra.Command { return err } - err = sdk.ValidateAccAddress(args[0]) + _, err = sdk.AccAddressFromBech32(args[0]) if err != nil { return err } diff --git a/x/wasm/client/cli/tx.go b/x/wasm/client/cli/tx.go index 6bdbdcd6b1..a89f15a408 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 != "" { - err := sdk.ValidateAccAddress(onlyAddrStr) + allowedAddr, err := sdk.AccAddressFromBech32(onlyAddrStr) if err != nil { return types.MsgStoreCode{}, sdkerrors.Wrap(err, flagInstantiateByAddress) } - x := types.AccessTypeOnlyAddress.With(sdk.AccAddress(onlyAddrStr)) + x := types.AccessTypeOnlyAddress.With(allowedAddr) perm = &x } else { everybodyStr, err := flags.GetString(flagInstantiateByEverybody) @@ -161,6 +161,7 @@ func InstantiateContractCmd() *cobra.Command { if err != nil { return err } + msg, err := parseInstantiateArgs(args[0], args[1], clientCtx.GetFromAddress(), cmd.Flags()) if err != nil { return err @@ -285,11 +286,11 @@ func parseStoreCodeAndInstantiateContractArgs(file string, initMsg string, sende return types.MsgStoreCodeAndInstantiateContract{}, fmt.Errorf("instantiate by address: %s", err) } if onlyAddrStr != "" { - err := sdk.ValidateAccAddress(onlyAddrStr) + addr, err := sdk.AccAddressFromBech32(onlyAddrStr) if err != nil { return types.MsgStoreCodeAndInstantiateContract{}, sdkerrors.Wrap(err, flagInstantiateByAddress) } - x := types.AccessTypeOnlyAddress.With(sdk.AccAddress(onlyAddrStr)) + x := types.AccessTypeOnlyAddress.With(addr) 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 84f304ccc5..4e145f7495 100644 --- a/x/wasm/client/rest/gov.go +++ b/x/wasm/client/rest/gov.go @@ -465,12 +465,12 @@ type wasmProposalData interface { } func toStdTxResponse(cliCtx client.Context, w http.ResponseWriter, data wasmProposalData) { - err := sdk.ValidateAccAddress(data.GetProposer()) + proposerAddr, err := sdk.AccAddressFromBech32(data.GetProposer()) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - msg, err := govtypes.NewMsgSubmitProposal(data.Content(), data.GetDeposit(), sdk.AccAddress(data.GetProposer())) + msg, err := govtypes.NewMsgSubmitProposal(data.Content(), data.GetDeposit(), proposerAddr) 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 f2107adad3..b188551c43 100644 --- a/x/wasm/client/rest/query.go +++ b/x/wasm/client/rest/query.go @@ -145,8 +145,7 @@ func listContractsByCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - addr := mux.Vars(r)["contractAddr"] - err := sdk.ValidateAccAddress(addr) + addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -156,7 +155,7 @@ func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContract, addr) + route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContract, addr.String()) res, height, err := cliCtx.Query(route) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -170,8 +169,7 @@ func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { func queryContractStateAllHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - addr := mux.Vars(r)["contractAddr"] - err := sdk.ValidateAccAddress(addr) + addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -181,8 +179,7 @@ func queryContractStateAllHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr, - keeper.QueryMethodContractStateAll) + route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateAll) res, height, err := cliCtx.Query(route) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -205,8 +202,7 @@ 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 := mux.Vars(r)["contractAddr"] - err := sdk.ValidateAccAddress(addr) + addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -222,8 +218,7 @@ func queryContractStateRawHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr, - keeper.QueryMethodContractStateRaw) + route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateRaw) res, height, err := cliCtx.QueryWithData(route, queryData) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -243,8 +238,7 @@ type smartResponse struct { func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { decoder := newArgDecoder(hex.DecodeString) - addr := mux.Vars(r)["contractAddr"] - err := sdk.ValidateAccAddress(addr) + addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -255,8 +249,7 @@ func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { return } - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr, - keeper.QueryMethodContractStateSmart) + route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateSmart) queryData, err := decoder.DecodeString(mux.Vars(r)["query"]) if err != nil { @@ -278,8 +271,7 @@ func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { func queryContractHistoryFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - addr := mux.Vars(r)["contractAddr"] - err := sdk.ValidateAccAddress(addr) + addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -303,7 +295,7 @@ func queryContractHistoryFn(cliCtx client.Context) http.HandlerFunc { } data := &types.QueryContractHistoryRequest{ - Address: addr, + Address: addr.String(), Pagination: pageReq, } bs, err := cliCtx.LegacyAmino.MarshalJSON(data) diff --git a/x/wasm/common_test.go b/x/wasm/common_test.go index 91f53a65df..35815dbb96 100644 --- a/x/wasm/common_test.go +++ b/x/wasm/common_test.go @@ -29,7 +29,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.ValidateAccAddress(addr) + _, err := sdk.AccAddressFromBech32(addr) require.NoError(t, err) return addr } @@ -43,7 +43,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.ValidateAccAddress(addr) + _, err := sdk.AccAddressFromBech32(addr) require.NoError(t, err) return codeID, addr } diff --git a/x/wasm/keeper/api.go b/x/wasm/keeper/api.go index b1b93927e1..fb483b6a80 100644 --- a/x/wasm/keeper/api.go +++ b/x/wasm/keeper/api.go @@ -1,8 +1,6 @@ package keeper import ( - "fmt" - wasmvm "github.com/line/wasmvm" wasmvmtypes "github.com/line/wasmvm/types" @@ -29,15 +27,14 @@ var ( func (a cosmwasmAPIImpl) humanAddress(canon []byte) (string, uint64, error) { gas := a.gasMultiplier.FromWasmVMGas(5) if err := sdk.VerifyAddressFormat(canon); err != nil { - //nolint:stylecheck - return "", gas, fmt.Errorf("expected %d byte address", sdk.BytesAddrLen) + return "", gas, err } - return sdk.BytesToAccAddress(canon).String(), gas, nil + return sdk.AccAddress(canon).String(), gas, nil } func (a cosmwasmAPIImpl) canonicalAddress(human string) ([]byte, uint64, error) { - bz, err := sdk.AccAddressToBytes(human) + bz, err := sdk.AccAddressFromBech32(human) return bz, a.gasMultiplier.ToWasmVMGas(4), err } diff --git a/x/wasm/keeper/authz_policy.go b/x/wasm/keeper/authz_policy.go index 6b9ecaf3a8..52abc913ae 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 != "" && admin.Equals(actor) + return admin != nil && admin.Equals(actor) } func (p DefaultAuthorizationPolicy) CanUpdateContractStatus() bool { diff --git a/x/wasm/keeper/contract_keeper.go b/x/wasm/keeper/contract_keeper.go index c8515608ad..144337f571 100644 --- a/x/wasm/keeper/contract_keeper.go +++ b/x/wasm/keeper/contract_keeper.go @@ -64,7 +64,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, "", p.authZPolicy) + return p.nested.setContractAdmin(ctx, contractAddress, caller, nil, 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 44386bc219..f992e3f8e0 100644 --- a/x/wasm/keeper/genesis.go +++ b/x/wasm/keeper/genesis.go @@ -37,12 +37,11 @@ func InitGenesis(ctx sdk.Context, keeper *Keeper, data types.GenesisState, staki var maxContractID int for i, contract := range data.Contracts { - err := sdk.ValidateAccAddress(contract.ContractAddress) + contractAddr, err := sdk.AccAddressFromBech32(contract.ContractAddress) if err != nil { return nil, sdkerrors.Wrapf(err, "address in contract number %d", i) } - err = keeper.importContract(ctx, sdk.AccAddress(contract.ContractAddress), &contract.ContractInfo, - contract.ContractState) + err = keeper.importContract(ctx, contractAddr, &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 145d26f52c..087a9670f9 100644 --- a/x/wasm/keeper/genesis_test.go +++ b/x/wasm/keeper/genesis_test.go @@ -65,9 +65,9 @@ func TestGenesisExportImport(t *testing.T) { f.Fuzz(&pinned) f.Fuzz(&contractExtension) - err := sdk.ValidateAccAddress(codeInfo.Creator) + creatorAddr, err := sdk.AccAddressFromBech32(codeInfo.Creator) require.NoError(t, err) - codeID, err := contractKeeper.Create(srcCtx, sdk.AccAddress(codeInfo.Creator), wasmCode, &codeInfo.InstantiateConfig) + codeID, err := contractKeeper.Create(srcCtx, creatorAddr, wasmCode, &codeInfo.InstantiateConfig) require.NoError(t, err) if pinned { contractKeeper.PinCode(srcCtx, codeID) @@ -258,7 +258,8 @@ func TestGenesisInit(t *testing.T) { }, }, Params: types.DefaultParams(), - }}, + }, + }, "happy path: code id in info and contract do match": { src: types.GenesisState{ Codes: []types.Code{{ @@ -538,7 +539,7 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) { assert.Equal(t, expCodeInfo, *gotCodeInfo) // verify contract - contractAddr := sdk.AccAddress("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") + contractAddr, _ := sdk.AccAddressFromBech32("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt") gotContractInfo := keeper.GetContractInfo(ctx, contractAddr) require.NotNil(t, gotContractInfo) contractCreatorAddr := "link1p0yx9c9q4xsnedlcn24gqfry5dcu6e9xkhv9aj" @@ -554,11 +555,12 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) { } assert.Equal(t, expContractInfo, *gotContractInfo) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - }, + expHistory := []types.ContractCodeHistoryEntry{ + { + Operation: types.ContractCodeHistoryOperationTypeGenesis, + CodeID: firstCodeID, + Updated: types.NewAbsoluteTxPosition(ctx), + }, } assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr)) assert.Equal(t, uint64(2), keeper.PeekAutoIncrementID(ctx, types.KeyLastCodeID)) @@ -569,9 +571,9 @@ func TestSupportedGenMsgTypes(t *testing.T) { wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) var ( - myAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, types.ContractAddrLen)) - verifierAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, types.ContractAddrLen)) - beneficiaryAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{3}, types.ContractAddrLen)) + myAddress sdk.AccAddress = bytes.Repeat([]byte{1}, types.ContractAddrLen) + verifierAddress sdk.AccAddress = bytes.Repeat([]byte{2}, types.ContractAddrLen) + beneficiaryAddress sdk.AccAddress = bytes.Repeat([]byte{3}, types.ContractAddrLen) ) const denom = "stake" importState := types.GenesisState{ diff --git a/x/wasm/keeper/handler_plugin_encoders_test.go b/x/wasm/keeper/handler_plugin_encoders_test.go index 15a7481451..18e9733929 100644 --- a/x/wasm/keeper/handler_plugin_encoders_test.go +++ b/x/wasm/keeper/handler_plugin_encoders_test.go @@ -30,9 +30,9 @@ func TestEncoding(t *testing.T) { addr3 = RandomAccountAddress(t) invalidAddr = "xrnd1d02kd90n38qvr3qb9qof83fn2d2" ) - valAddr := make([]byte, types.SDKAddrLen) + valAddr := make(sdk.ValAddress, types.SDKAddrLen) valAddr[0] = 12 - valAddr2 := make([]byte, types.SDKAddrLen) + valAddr2 := make(sdk.ValAddress, types.SDKAddrLen) valAddr2[1] = 123 jsonMsg := types.RawContractMessage(`{"foo": 123}`) @@ -249,7 +249,7 @@ func TestEncoding(t *testing.T) { srcMsg: wasmvmtypes.CosmosMsg{ Staking: &wasmvmtypes.StakingMsg{ Delegate: &wasmvmtypes.DelegateMsg{ - Validator: sdk.BytesToAccAddress(valAddr).String(), + Validator: valAddr.String(), Amount: wasmvmtypes.NewCoin(777, "stake"), }, }, @@ -257,7 +257,7 @@ func TestEncoding(t *testing.T) { output: []sdk.Msg{ &stakingtypes.MsgDelegate{ DelegatorAddress: addr1.String(), - ValidatorAddress: sdk.BytesToAccAddress(valAddr).String(), + ValidatorAddress: valAddr.String(), Amount: sdk.NewInt64Coin("stake", 777), }, }, @@ -286,7 +286,7 @@ func TestEncoding(t *testing.T) { srcMsg: wasmvmtypes.CosmosMsg{ Staking: &wasmvmtypes.StakingMsg{ Undelegate: &wasmvmtypes.UndelegateMsg{ - Validator: sdk.BytesToAccAddress(valAddr).String(), + Validator: valAddr.String(), Amount: wasmvmtypes.NewCoin(555, "stake"), }, }, @@ -294,7 +294,7 @@ func TestEncoding(t *testing.T) { output: []sdk.Msg{ &stakingtypes.MsgUndelegate{ DelegatorAddress: addr1.String(), - ValidatorAddress: sdk.BytesToAccAddress(valAddr).String(), + ValidatorAddress: valAddr.String(), Amount: sdk.NewInt64Coin("stake", 555), }, }, @@ -304,8 +304,8 @@ func TestEncoding(t *testing.T) { srcMsg: wasmvmtypes.CosmosMsg{ Staking: &wasmvmtypes.StakingMsg{ Redelegate: &wasmvmtypes.RedelegateMsg{ - SrcValidator: sdk.BytesToAccAddress(valAddr).String(), - DstValidator: sdk.BytesToAccAddress(valAddr2).String(), + SrcValidator: valAddr.String(), + DstValidator: valAddr2.String(), Amount: wasmvmtypes.NewCoin(222, "stake"), }, }, @@ -313,8 +313,8 @@ func TestEncoding(t *testing.T) { output: []sdk.Msg{ &stakingtypes.MsgBeginRedelegate{ DelegatorAddress: addr1.String(), - ValidatorSrcAddress: sdk.BytesToAccAddress(valAddr).String(), - ValidatorDstAddress: sdk.BytesToAccAddress(valAddr2).String(), + ValidatorSrcAddress: valAddr.String(), + ValidatorDstAddress: valAddr2.String(), Amount: sdk.NewInt64Coin("stake", 222), }, }, @@ -324,14 +324,14 @@ func TestEncoding(t *testing.T) { srcMsg: wasmvmtypes.CosmosMsg{ Distribution: &wasmvmtypes.DistributionMsg{ WithdrawDelegatorReward: &wasmvmtypes.WithdrawDelegatorRewardMsg{ - Validator: sdk.BytesToAccAddress(valAddr2).String(), + Validator: valAddr2.String(), }, }, }, output: []sdk.Msg{ &distributiontypes.MsgWithdrawDelegatorReward{ DelegatorAddress: addr1.String(), - ValidatorAddress: sdk.BytesToAccAddress(valAddr2).String(), + ValidatorAddress: valAddr2.String(), }, }, }, diff --git a/x/wasm/keeper/ibc.go b/x/wasm/keeper/ibc.go index 200aa52cdf..cd34d0e102 100644 --- a/x/wasm/keeper/ibc.go +++ b/x/wasm/keeper/ibc.go @@ -38,12 +38,9 @@ func PortIDForContract(addr sdk.AccAddress) string { func ContractFromPortID(portID string) (sdk.AccAddress, error) { if !strings.HasPrefix(portID, portIDPrefix) { - return "", sdkerrors.Wrapf(types.ErrInvalid, "without prefix") + return nil, sdkerrors.Wrapf(types.ErrInvalid, "without prefix") } - if err := sdk.ValidateAccAddress(portID[len(portIDPrefix):]); err != nil { - return "", sdkerrors.Wrapf(types.ErrInvalid, err.Error()) - } - return sdk.AccAddress(portID[len(portIDPrefix):]), nil + return sdk.AccAddressFromBech32(portID[len(portIDPrefix):]) } // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function diff --git a/x/wasm/keeper/ibc_test.go b/x/wasm/keeper/ibc_test.go index 150b9bc457..f1df4fa85d 100644 --- a/x/wasm/keeper/ibc_test.go +++ b/x/wasm/keeper/ibc_test.go @@ -31,7 +31,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, "", initMsgBz, "ibc-reflect-2", nil) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, creator, nil, initMsgBz, "ibc-reflect-2", nil) require.NoError(t, err) require.NotEqual(t, example.Contract, addr) @@ -80,5 +80,4 @@ func TestContractFromPortID(t *testing.T) { assert.Equal(t, spec.expAddr, gotAddr) }) } - } diff --git a/x/wasm/keeper/keeper.go b/x/wasm/keeper/keeper.go index faf994ec1d..425f958ebc 100644 --- a/x/wasm/keeper/keeper.go +++ b/x/wasm/keeper/keeper.go @@ -230,7 +230,7 @@ func (k Keeper) setParams(ctx sdk.Context, ps types.Params) { } func (k Keeper) create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ AuthorizationPolicy) (codeID uint64, err error) { - if creator == "" { + if creator == nil { return 0, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "cannot be empty") } @@ -316,15 +316,14 @@ 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, sdkerrors.Wrap(types.ErrAccountExists, existingAcct.GetAddress().String()) + return nil, 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, err + return nil, nil, err } - } else { // create an empty account (so we don't have issues later) // TODO: can we remove this? @@ -336,13 +335,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, sdkerrors.Wrap(types.ErrNotFound, "code") + return nil, nil, sdkerrors.Wrap(types.ErrNotFound, "code") } var codeInfo types.CodeInfo k.cdc.MustUnmarshal(bz, &codeInfo) if !authZ.CanInstantiateContract(codeInfo.InstantiateConfig, creator) { - return "", nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") + return nil, nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") } // prepare params for contract instantiate call @@ -362,9 +361,8 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A gas := k.runtimeGasForContract(ctx) res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, wasmStore, k.cosmwasmAPI(ctx), querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) - if err != nil { - return "", nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) + return nil, nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) } // persist instance first @@ -374,13 +372,13 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A // check for IBC flag report, err := k.wasmVM.AnalyzeCode(codeInfo.CodeHash) if err != nil { - return "", nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) + return nil, nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) } if report.HasIBCEntryPoints { // register IBC port ibcPort, err := k.ensureIbcPort(ctx, contractAddress) if err != nil { - return "", nil, err + return nil, nil, err } contractInfo.IBCPortID = ibcPort } @@ -399,7 +397,7 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) if err != nil { - return "", nil, sdkerrors.Wrap(err, "dispatch") + return nil, nil, sdkerrors.Wrap(err, "dispatch") } return contractAddress, data, nil @@ -435,7 +433,6 @@ func (k Keeper) execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller wasmStore := types.NewWasmStore(prefixStore) res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, wasmStore, k.cosmwasmAPI(ctx), querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) } @@ -501,7 +498,6 @@ func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller wasmStore := types.NewWasmStore(prefixStore) res, gasUsed, err := k.wasmVM.Migrate(newCodeInfo.CodeHash, env, msg, &wasmStore, k.cosmwasmAPI(ctx), &querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) - if err != nil { return nil, sdkerrors.Wrap(types.ErrMigrationFailed, err.Error()) } @@ -585,7 +581,6 @@ func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply was wasmStore := types.NewWasmStore(prefixStore) res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, wasmStore, k.cosmwasmAPI(ctx), querier, k.gasMeter(ctx), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) } @@ -622,7 +617,7 @@ func (k Keeper) IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(a for ; iter.Valid(); iter.Next() { key := iter.Key() - if cb(sdk.AccAddress(string(key[types.AbsoluteTxPositionLen:]))) { + if cb(key[types.AbsoluteTxPositionLen:]) { return } } @@ -664,7 +659,6 @@ func (k Keeper) setContractAdmin(ctx sdk.Context, contractAddress, caller, newAd } contractInfo.Admin = newAdmin.String() k.storeContractInfo(ctx, contractAddress, contractInfo) - return nil } @@ -741,7 +735,6 @@ func (k Keeper) QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []b wasmStore := types.NewWasmStore(prefixStore) queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, wasmStore, k.cosmwasmAPI(ctx), querier, k.gasMeter(ctx), k.runtimeGasForContract(ctx), costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) - if qErr != nil { return nil, sdkerrors.Wrap(types.ErrQueryFailed, qErr.Error()) } @@ -835,7 +828,7 @@ func (k Keeper) IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, typ var contract types.ContractInfo k.cdc.MustUnmarshal(iter.Value(), &contract) // cb returns true to stop early - if cb(sdk.AccAddress(string(iter.Key())), contract) { + if cb(iter.Key(), contract) { break } } @@ -1065,7 +1058,7 @@ func BuildContractAddress(codeID, instanceID uint64) sdk.AccAddress { contractID := make([]byte, 16) binary.BigEndian.PutUint64(contractID[:8], codeID) binary.BigEndian.PutUint64(contractID[8:], instanceID) - return sdk.BytesToAccAddress(address.Module(types.ModuleName, contractID)[:types.ContractAddrLen]) + return address.Module(types.ModuleName, contractID)[:types.ContractAddrLen] } func (k Keeper) autoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 { diff --git a/x/wasm/keeper/keeper_test.go b/x/wasm/keeper/keeper_test.go index 5d2511c532..ea8396286c 100644 --- a/x/wasm/keeper/keeper_test.go +++ b/x/wasm/keeper/keeper_test.go @@ -2,7 +2,6 @@ package keeper import ( "bytes" - "encoding/binary" "encoding/json" "errors" "io/ioutil" @@ -10,7 +9,6 @@ import ( "testing" "time" - "github.com/line/ostracon/crypto" ocproto "github.com/line/ostracon/proto/ostracon/types" wasmvm "github.com/line/wasmvm" wasmvmtypes "github.com/line/wasmvm/types" @@ -27,13 +25,6 @@ import ( "github.com/line/lbm-sdk/x/wasm/types" ) -func addrFromUint64(id uint64) sdk.AccAddress { - addr := make([]byte, 20) - addr[0] = 'C' - binary.PutUvarint(addr[1:], id) - return sdk.BytesToAccAddress(crypto.AddressHash(addr)) -} - // When migrated to go 1.16, embed package should be used instead. func init() { b, err := ioutil.ReadFile("./testdata/hackatom.wasm") @@ -75,7 +66,7 @@ func TestCreateSuccess(t *testing.T) { func TestCreateNilCreatorAddress(t *testing.T) { ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) - _, err := keepers.ContractKeeper.Create(ctx, "", hackatomWasm, nil) + _, err := keepers.ContractKeeper.Create(ctx, nil, hackatomWasm, nil) require.Error(t, err, "nil creator is not allowed") } @@ -100,7 +91,7 @@ func TestCreateInvalidWasmCode(t *testing.T) { func TestCreateStoresInstantiatePermission(t *testing.T) { var ( deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr sdk.AccAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, types.SDKAddrLen)) + myAddr sdk.AccAddress = bytes.Repeat([]byte{1}, types.SDKAddrLen) ) specs := map[string]struct { @@ -344,7 +335,7 @@ func TestIsSimulationMode(t *testing.T) { } for msg := range specs { t.Run(msg, func(t *testing.T) { - //assert.Equal(t, spec.exp, isSimulationMode(spec.ctx)) + // assert.Equal(t, spec.exp, isSimulationMode(spec.ctx)) }) } } @@ -392,13 +383,13 @@ func TestInstantiate(t *testing.T) { em := sdk.NewEventManager() // create with no balance is also legal - gotContractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), codeID, creator, "", initMsgBz, "demo contract 1", nil) + gotContractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), codeID, creator, nil, initMsgBz, "demo contract 1", nil) require.NoError(t, err) require.Equal(t, "link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8", gotContractAddr.String()) gasAfter := ctx.GasMeter().GasConsumed() if types.EnableGasVerification { - require.Equal(t, uint64(106175), gasAfter-gasBefore) + require.Equal(t, uint64(0x18c38), gasAfter-gasBefore) } // ensure it is stored properly @@ -429,8 +420,8 @@ func TestInstantiate(t *testing.T) { func TestInstantiateWithDeposit(t *testing.T) { var ( - bob = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, types.SDKAddrLen)) - fred = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, types.SDKAddrLen)) + bob = bytes.Repeat([]byte{1}, types.SDKAddrLen) + fred = bytes.Repeat([]byte{2}, types.SDKAddrLen) deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) initMsg = HackatomExampleInitMsg{Verifier: fred, Beneficiary: bob} @@ -470,7 +461,7 @@ func TestInstantiateWithDeposit(t *testing.T) { require.NoError(t, err) // when - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, "", initMsgBz, "my label", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsgBz, "my label", deposit) // then if spec.expError { require.Error(t, err) @@ -486,9 +477,9 @@ func TestInstantiateWithDeposit(t *testing.T) { func TestInstantiateWithPermissions(t *testing.T) { var ( deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, types.SDKAddrLen)) - otherAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, types.SDKAddrLen)) - anyAddr = sdk.BytesToAccAddress(bytes.Repeat([]byte{3}, types.SDKAddrLen)) + myAddr = bytes.Repeat([]byte{1}, types.SDKAddrLen) + otherAddr = bytes.Repeat([]byte{2}, types.SDKAddrLen) + anyAddr = bytes.Repeat([]byte{3}, types.SDKAddrLen) ) initMsg := HackatomExampleInitMsg{ @@ -534,7 +525,7 @@ func TestInstantiateWithPermissions(t *testing.T) { contractID, err := keeper.Create(ctx, myAddr, hackatomWasm, &spec.srcPermission) require.NoError(t, err) - _, _, err = keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, "", initMsgBz, "demo contract 1", nil) + _, _, err = keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsgBz, "demo contract 1", nil) assert.True(t, spec.expError.Is(err), "got %+v", err) }) } @@ -551,9 +542,9 @@ func TestInstantiateWithNonExistingCodeID(t *testing.T) { require.NoError(t, err) const nonExistingCodeID = 9999 - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, nonExistingCodeID, creator, "", initMsgBz, "demo contract 2", nil) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, nonExistingCodeID, creator, nil, initMsgBz, "demo contract 2", nil) require.True(t, types.ErrNotFound.Is(err), err) - require.Equal(t, addr.String(), "") + require.Nil(t, addr) } func TestInstantiateWithContractDataResponse(t *testing.T) { @@ -568,7 +559,7 @@ func TestInstantiateWithContractDataResponse(t *testing.T) { } example := StoreRandomContract(t, ctx, keepers, wasmerMock) - _, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, "", nil, "test", nil) + _, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil) require.NoError(t, err) assert.Equal(t, []byte("my-response-data"), data) } @@ -593,7 +584,7 @@ func TestExecute(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 3", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) require.NoError(t, err) require.Equal(t, "link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8", addr.String()) @@ -632,7 +623,7 @@ func TestExecute(t *testing.T) { // make sure gas is properly deducted from ctx gasAfter := ctx.GasMeter().GasConsumed() if types.EnableGasVerification { - require.Equal(t, uint64(96282), gasAfter-gasBefore) + require.Equal(t, uint64(0x16bba), gasAfter-gasBefore) } // ensure bob now exists and got both payments released bobAcct = accKeeper.GetAccount(ctx, bob) @@ -656,8 +647,8 @@ func TestExecute(t *testing.T) { func TestExecuteWithDeposit(t *testing.T) { var ( - bob = sdk.BytesToAccAddress(bytes.Repeat([]byte{1}, types.SDKAddrLen)) - fred = sdk.BytesToAccAddress(bytes.Repeat([]byte{2}, types.SDKAddrLen)) + bob = bytes.Repeat([]byte{1}, types.SDKAddrLen) + fred = bytes.Repeat([]byte{2}, types.SDKAddrLen) blockedAddr = authtypes.NewModuleAddress(distributiontypes.ModuleName) deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) ) @@ -726,7 +717,7 @@ func TestExecuteWithDeposit(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, spec.srcActor, "", initMsgBz, "my label", nil) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, spec.srcActor, nil, initMsgBz, "my label", nil) require.NoError(t, err) // when @@ -777,7 +768,7 @@ func TestExecuteWithPanic(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 4", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 4", deposit) require.NoError(t, err) // let's make sure we get a reasonable error, no panic/crash @@ -808,7 +799,7 @@ func TestExecuteWithCpuLoop(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 5", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 5", deposit) require.NoError(t, err) // make sure we set a limit before calling @@ -827,7 +818,6 @@ func TestExecuteWithCpuLoop(t *testing.T) { // this should throw out of gas exception (panic) _, err = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"cpu_loop":{}}`), nil) require.True(t, false, "We must panic before this line") - } func TestExecuteWithStorageLoop(t *testing.T) { @@ -850,7 +840,7 @@ func TestExecuteWithStorageLoop(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 6", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 6", deposit) require.NoError(t, err) // make sure we set a limit before calling @@ -1013,7 +1003,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 != "" { + if spec.overrideContractAddr != nil { contractAddr = spec.overrideContractAddr } // when @@ -1182,7 +1172,7 @@ func TestIterateContractsByCode(t *testing.T) { Verifier: RandomAccountAddress(t), Beneficiary: RandomAccountAddress(t), }.GetBytes(t) - contractAddr3, _, err := c.Instantiate(ctx, example1.CodeID, example1.CreatorAddr, "", initMsg, "foo", nil) + contractAddr3, _, err := c.Instantiate(ctx, example1.CodeID, example1.CreatorAddr, nil, initMsg, "foo", nil) require.NoError(t, err) specs := map[string]struct { codeID uint64 @@ -1274,8 +1264,7 @@ func TestSudo(t *testing.T) { } initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 3", deposit) - + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) require.NoError(t, err) require.Equal(t, "link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8", addr.String()) @@ -1313,7 +1302,6 @@ func TestSudo(t *testing.T) { expEvt := sdk.NewEvent("sudo", sdk.NewAttribute("_contract_address", addr.String())) assert.Equal(t, expEvt, em.Events()[0]) - } func prettyEvents(t *testing.T, events sdk.Events) string { @@ -1395,7 +1383,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 != "" { + if spec.overrideContractAddr != nil { addr = spec.overrideContractAddr } err = keeper.UpdateContractAdmin(ctx, addr, spec.caller, spec.newAdmin) @@ -1458,7 +1446,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 != "" { + if spec.overrideContractAddr != nil { addr = spec.overrideContractAddr } err = keeper.ClearContractAdmin(ctx, addr, spec.caller) @@ -1495,7 +1483,7 @@ func TestExecuteManualInactiveContractFailure(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - addr, _, err := keeper.Instantiate(ctx, contractID, creator, "", initMsgBz, "demo contract 3", deposit) + addr, _, err := keeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) require.NoError(t, err) require.Equal(t, "link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8", addr.String()) @@ -1674,7 +1662,8 @@ func TestUnpinCode(t *testing.T) { UnpinFn: func(checksum wasmvm.Checksum) error { capturedChecksums = append(capturedChecksums, checksum) return nil - }} + }, + } wasmtesting.MakeInstantiable(&mock) myCodeID := StoreRandomContract(t, ctx, keepers, &mock).CodeID require.Equal(t, uint64(1), myCodeID) @@ -1762,14 +1751,13 @@ func TestPinnedContractLoops(t *testing.T) { }, }, 0, nil } - ctx = ctx.WithGasMeter(sdk.NewGasMeter(10000)) + ctx = ctx.WithGasMeter(sdk.NewGasMeter(20000)) require.PanicsWithValue(t, sdk.ErrorOutOfGas{Descriptor: "ReadFlat"}, func() { _, err := k.execute(ctx, example.Contract, RandomAccountAddress(t), anyMsg, nil) require.NoError(t, err) }) assert.True(t, ctx.GasMeter().IsOutOfGas()) - assert.Greater(t, loops, 1) - + assert.Greater(t, loops, 2) } func TestNewDefaultWasmVMContractResponseHandler(t *testing.T) { @@ -1993,7 +1981,7 @@ func TestBuildContractAddress(t *testing.T) { t.Run(name, func(t *testing.T) { gotAddr := BuildContractAddress(spec.srcCodeID, spec.srcInstanceID) require.NotNil(t, gotAddr) - assert.Nil(t, sdk.ValidateAccAddress(gotAddr.String())) + assert.Nil(t, sdk.VerifyAddressFormat(gotAddr)) if len(spec.expectedAddr) > 0 { require.Equal(t, spec.expectedAddr, gotAddr.String()) } diff --git a/x/wasm/keeper/legacy_querier.go b/x/wasm/keeper/legacy_querier.go index bc1fba7c8f..ced616fec5 100644 --- a/x/wasm/keeper/legacy_querier.go +++ b/x/wasm/keeper/legacy_querier.go @@ -36,32 +36,28 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { ) switch path[0] { case QueryGetContract: - err := sdk.ValidateAccAddress(path[1]) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + addr, addrErr := sdk.AccAddressFromBech32(path[1]) + if addrErr != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, addrErr.Error()) } //nolint:staticcheck - rsp, err = queryContractInfo(ctx, sdk.AccAddress(path[1]), keeper) + rsp, err = queryContractInfo(ctx, addr, keeper) case QueryListContractByCode: - codeID, err := strconv.ParseUint(path[1], 10, 64) - if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", err.Error()) + codeID, parseErr := strconv.ParseUint(path[1], 10, 64) + if parseErr != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", parseErr.Error()) } //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") } return queryContractState(ctx, path[1], path[2], req.Data, gasLimit, keeper) case QueryGetCode: - codeID, err := strconv.ParseUint(path[1], 10, 64) - if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", err.Error()) + codeID, parseErr := strconv.ParseUint(path[1], 10, 64) + if parseErr != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", parseErr.Error()) } //nolint:staticcheck rsp, err = queryCode(ctx, codeID, keeper) @@ -69,12 +65,12 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { //nolint:staticcheck rsp, err = queryCodeList(ctx, keeper) case QueryContractHistory: - err := sdk.ValidateAccAddress(path[1]) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + contractAddr, addrErr := sdk.AccAddressFromBech32(path[1]) + if addrErr != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, addrErr.Error()) } //nolint:staticcheck - rsp, err = queryContractHistory(ctx, sdk.AccAddress(path[1]), keeper) + rsp, err = queryContractHistory(ctx, contractAddr, keeper) default: return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") } @@ -93,11 +89,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) { - err := sdk.ValidateAccAddress(bech) + contractAddr, err := sdk.AccAddressFromBech32(bech) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, bech) } - contractAddr := sdk.AccAddress(bech) + switch queryMethod { case QueryMethodContractStateAll: resultData := make([]types.Model, 0) @@ -122,7 +118,8 @@ func queryContractState(ctx sdk.Context, bech, queryMethod string, data []byte, return nil, sdkerrors.Wrap(err, "json msg") } // this returns raw bytes (must be base64-encoded) - return keeper.QuerySmart(ctx, contractAddr, msg) + bz, err := keeper.QuerySmart(ctx, contractAddr, msg) + return bz, err default: return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, queryMethod) } diff --git a/x/wasm/keeper/legacy_querier_test.go b/x/wasm/keeper/legacy_querier_test.go index 53527f4400..5fd3bae62a 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, "", initMsgBz, "demo contract to query", deposit) + addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract to query", deposit) require.NoError(t, err) contractModel := []types.Model{ @@ -193,7 +193,7 @@ func TestLegacyQueryContractListByCodeOrdering(t *testing.T) { ctx = setBlock(ctx, h) h++ } - _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", initMsgBz, fmt.Sprintf("contract %d", i), topUp) + _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) require.NoError(t, err) } @@ -221,9 +221,7 @@ func TestLegacyQueryContractHistory(t *testing.T) { ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) keeper := keepers.WasmKeeper - var ( - otherAddr sdk.AccAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, types.ContractAddrLen)) - ) + var otherAddr sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) specs := map[string]struct { srcQueryAddr sdk.AccAddress @@ -293,7 +291,7 @@ func TestLegacyQueryContractHistory(t *testing.T) { var defaultQueryGasLimit sdk.Gas = 3000000 q := NewLegacyQuerier(keeper, defaultQueryGasLimit) queryContractAddr := spec.srcQueryAddr - if queryContractAddr.Empty() { + if queryContractAddr == nil { queryContractAddr = myContractAddr } diff --git a/x/wasm/keeper/msg_server.go b/x/wasm/keeper/msg_server.go index a7d3ffb1e7..d39f098c03 100644 --- a/x/wasm/keeper/msg_server.go +++ b/x/wasm/keeper/msg_server.go @@ -5,6 +5,7 @@ import ( sdk "github.com/line/lbm-sdk/types" sdkerrors "github.com/line/lbm-sdk/types/errors" + "github.com/line/lbm-sdk/x/wasm/types" ) @@ -20,7 +21,7 @@ func NewMsgServerImpl(k types.ContractOpsKeeper) types.MsgServer { func (m msgServer) StoreCode(goCtx context.Context, msg *types.MsgStoreCode) (*types.MsgStoreCodeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } @@ -31,7 +32,7 @@ func (m msgServer) StoreCode(goCtx context.Context, msg *types.MsgStoreCode) (*t sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), )) - codeID, err := m.keeper.Create(ctx, sdk.AccAddress(msg.Sender), msg.WASMByteCode, msg.InstantiatePermission) + codeID, err := m.keeper.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission) if err != nil { return nil, err } @@ -44,16 +45,15 @@ 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) - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } var adminAddr sdk.AccAddress if msg.Admin != "" { - if err = sdk.ValidateAccAddress(msg.Admin); err != nil { + if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { return nil, sdkerrors.Wrap(err, "admin") } - adminAddr = sdk.AccAddress(msg.Admin) } ctx.EventManager().EmitEvent(sdk.NewEvent( @@ -62,7 +62,7 @@ func (m msgServer) InstantiateContract(goCtx context.Context, msg *types.MsgInst sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), )) - contractAddr, data, err := m.keeper.Instantiate(ctx, msg.CodeID, sdk.AccAddress(msg.Sender), adminAddr, msg.Msg, msg.Label, msg.Funds) + contractAddr, data, err := m.keeper.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds) if err != nil { return nil, err } @@ -76,11 +76,11 @@ func (m msgServer) InstantiateContract(goCtx context.Context, msg *types.MsgInst func (m msgServer) StoreCodeAndInstantiateContract(goCtx context.Context, msg *types.MsgStoreCodeAndInstantiateContract) (*types.MsgStoreCodeAndInstantiateContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - codeID, err := m.keeper.Create(ctx, sdk.AccAddress(msg.Sender), msg.WASMByteCode, msg.InstantiatePermission) + codeID, err := m.keeper.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission) if err != nil { return nil, err } @@ -93,13 +93,13 @@ func (m msgServer) StoreCodeAndInstantiateContract(goCtx context.Context, var adminAddr sdk.AccAddress if msg.Admin != "" { - if err = sdk.ValidateAccAddress(msg.Admin); err != nil { + adminAddr, err = sdk.AccAddressFromBech32(msg.Admin) + if err != nil { return nil, sdkerrors.Wrap(err, "admin") } - adminAddr = sdk.AccAddress(msg.Admin) } - contractAddr, data, err := m.keeper.Instantiate(ctx, codeID, sdk.AccAddress(msg.Sender), adminAddr, msg.Msg, + contractAddr, data, err := m.keeper.Instantiate(ctx, codeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds) if err != nil { return nil, err @@ -114,11 +114,11 @@ func (m msgServer) StoreCodeAndInstantiateContract(goCtx context.Context, func (m msgServer) ExecuteContract(goCtx context.Context, msg *types.MsgExecuteContract) (*types.MsgExecuteContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - err = sdk.ValidateAccAddress(msg.Contract) + contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } @@ -129,7 +129,7 @@ func (m msgServer) ExecuteContract(goCtx context.Context, msg *types.MsgExecuteC sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), )) - data, err := m.keeper.Execute(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), msg.Msg, msg.Funds) + data, err := m.keeper.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) if err != nil { return nil, err } @@ -141,11 +141,11 @@ 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) - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - err = sdk.ValidateAccAddress(msg.Contract) + contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } @@ -156,7 +156,7 @@ func (m msgServer) MigrateContract(goCtx context.Context, msg *types.MsgMigrateC sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), )) - data, err := m.keeper.Migrate(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), msg.CodeID, msg.Msg) + data, err := m.keeper.Migrate(ctx, contractAddr, senderAddr, msg.CodeID, msg.Msg) if err != nil { return nil, err } @@ -168,15 +168,15 @@ 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) - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - err = sdk.ValidateAccAddress(msg.Contract) + contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } - err = sdk.ValidateAccAddress(msg.NewAdmin) + newAdminAddr, err := sdk.AccAddressFromBech32(msg.NewAdmin) if err != nil { return nil, sdkerrors.Wrap(err, "new admin") } @@ -187,8 +187,7 @@ func (m msgServer) UpdateAdmin(goCtx context.Context, msg *types.MsgUpdateAdmin) sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), )) - if err := m.keeper.UpdateContractAdmin(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), - sdk.AccAddress(msg.NewAdmin)); err != nil { + if err := m.keeper.UpdateContractAdmin(ctx, contractAddr, senderAddr, newAdminAddr); err != nil { return nil, err } @@ -197,11 +196,11 @@ 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) - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - err = sdk.ValidateAccAddress(msg.Contract) + contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "contract") } @@ -216,7 +215,7 @@ func (m msgServer) ClearAdmin(goCtx context.Context, msg *types.MsgClearAdmin) ( sdk.NewAttribute(types.AttributeKeyContractAddr, msg.Contract), )) - if err := m.keeper.ClearContractAdmin(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender)); err != nil { + if err := m.keeper.ClearContractAdmin(ctx, contractAddr, senderAddr); err != nil { return nil, err } diff --git a/x/wasm/keeper/proposal_handler.go b/x/wasm/keeper/proposal_handler.go index af4111729f..73c3b1c6b4 100644 --- a/x/wasm/keeper/proposal_handler.go +++ b/x/wasm/keeper/proposal_handler.go @@ -63,11 +63,11 @@ func handleStoreCodeProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types return err } - err := sdk.ValidateAccAddress(p.RunAs) + runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) if err != nil { return sdkerrors.Wrap(err, "run as address") } - codeID, err := k.Create(ctx, sdk.AccAddress(p.RunAs), p.WASMByteCode, p.InstantiatePermission) + codeID, err := k.Create(ctx, runAsAddr, p.WASMByteCode, p.InstantiatePermission) if err != nil { return err } @@ -78,18 +78,18 @@ func handleInstantiateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p typ if err := p.ValidateBasic(); err != nil { return err } - err := sdk.ValidateAccAddress(p.RunAs) + runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) if err != nil { return sdkerrors.Wrap(err, "run as address") } + var adminAddr sdk.AccAddress if p.Admin != "" { - err = sdk.ValidateAccAddress(p.Admin) - if err != nil { + if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { return sdkerrors.Wrap(err, "admin") } } - _, data, err := k.Instantiate(ctx, p.CodeID, sdk.AccAddress(p.RunAs), sdk.AccAddress(p.Admin), p.Msg, p.Label, p.Funds) + _, data, err := k.Instantiate(ctx, p.CodeID, runAsAddr, adminAddr, p.Msg, p.Label, p.Funds) if err != nil { return err } @@ -106,15 +106,16 @@ func handleMigrateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.M return err } - err := sdk.ValidateAccAddress(p.Contract) + contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } // runAs is not used if this is permissioned, so just put any valid address there (second contractAddr) - data, err := k.Migrate(ctx, sdk.AccAddress(p.Contract), sdk.AccAddress(p.Contract), p.CodeID, p.Msg) + data, err := k.Migrate(ctx, contractAddr, contractAddr, p.CodeID, p.Msg) if err != nil { return err } + ctx.EventManager().EmitEvent(sdk.NewEvent( types.EventTypeGovContractResult, sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), @@ -126,11 +127,12 @@ func handleSudoProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.Sudo if err := p.ValidateBasic(); err != nil { return err } - err := sdk.ValidateAccAddress(p.Contract) + + contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - data, err := k.Sudo(ctx, sdk.AccAddress(p.Contract), p.Msg) + data, err := k.Sudo(ctx, contractAddr, p.Msg) if err != nil { return err } @@ -147,15 +149,15 @@ func handleExecuteProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.E return err } - err := sdk.ValidateAccAddress(p.Contract) + contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - err = sdk.ValidateAccAddress(p.RunAs) + runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) if err != nil { return sdkerrors.Wrap(err, "run as address") } - data, err := k.Execute(ctx, sdk.AccAddress(p.Contract), sdk.AccAddress(p.RunAs), p.Msg, p.Funds) + data, err := k.Execute(ctx, contractAddr, runAsAddr, p.Msg, p.Funds) if err != nil { return err } @@ -171,16 +173,16 @@ func handleUpdateAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p typ if err := p.ValidateBasic(); err != nil { return err } - err := sdk.ValidateAccAddress(p.Contract) + contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - err = sdk.ValidateAccAddress(p.NewAdmin) + newAdminAddr, err := sdk.AccAddressFromBech32(p.NewAdmin) if err != nil { return sdkerrors.Wrap(err, "run as address") } - if err := k.UpdateContractAdmin(ctx, sdk.AccAddress(p.Contract), "", sdk.AccAddress(p.NewAdmin)); err != nil { + if err := k.UpdateContractAdmin(ctx, contractAddr, nil, newAdminAddr); err != nil { return err } @@ -198,11 +200,11 @@ func handleClearAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p type return err } - err := sdk.ValidateAccAddress(p.Contract) + contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - if err := k.ClearContractAdmin(ctx, sdk.AccAddress(p.Contract), ""); err != nil { + if err := k.ClearContractAdmin(ctx, contractAddr, nil); err != nil { return err } @@ -275,11 +277,11 @@ func handleUpdateContractStatusProposal(ctx sdk.Context, k types.ContractOpsKeep if err := p.ValidateBasic(); err != nil { return err } - err := sdk.ValidateAccAddress(p.Contract) + contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { return sdkerrors.Wrap(err, "contract") } - if err = k.UpdateContractStatus(ctx, sdk.AccAddress(p.Contract), "", p.Status); err != nil { + if err = k.UpdateContractStatus(ctx, contractAddr, nil, 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 45fbcc4593..3bcbce89ad 100644 --- a/x/wasm/keeper/proposal_integration_test.go +++ b/x/wasm/keeper/proposal_integration_test.go @@ -80,8 +80,8 @@ func TestInstantiateProposal(t *testing.T) { ) var ( - oneAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, types.ContractAddrLen)) - otherAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, types.ContractAddrLen)) + oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) + otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) ) src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { p.CodeID = firstCodeID @@ -101,11 +101,10 @@ func TestInstantiateProposal(t *testing.T) { require.NoError(t, err) // then - contractAddr := "link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8" - err = sdk.ValidateAccAddress(contractAddr) + contractAddr, err := sdk.AccAddressFromBech32("link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8") require.NoError(t, err) - cInfo := wasmKeeper.GetContractInfo(ctx, sdk.AccAddress(contractAddr)) + cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) require.NotNil(t, cInfo) assert.Equal(t, uint64(1), cInfo.CodeID) assert.Equal(t, oneAddress.String(), cInfo.Creator) @@ -117,7 +116,7 @@ func TestInstantiateProposal(t *testing.T) { Updated: types.NewAbsoluteTxPosition(ctx), Msg: src.Msg, }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, sdk.AccAddress(contractAddr))) + assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) // and event require.Len(t, em.Events(), 3, "%#v", em.Events()) require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) @@ -148,9 +147,7 @@ func TestInstantiateProposal_NoAdmin(t *testing.T) { wasmCode), ) - var ( - oneAddress sdk.AccAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, types.ContractAddrLen)) - ) + var oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) // test invalid admin address src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { @@ -181,11 +178,10 @@ func TestInstantiateProposal_NoAdmin(t *testing.T) { require.NoError(t, err) // then - contractAddr := "link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8" - err = sdk.ValidateAccAddress(contractAddr) + contractAddr, err := sdk.AccAddressFromBech32("link14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sgf2vn8") require.NoError(t, err) - cInfo := wasmKeeper.GetContractInfo(ctx, sdk.AccAddress(contractAddr)) + cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) require.NotNil(t, cInfo) assert.Equal(t, uint64(1), cInfo.CodeID) assert.Equal(t, oneAddress.String(), cInfo.Creator) @@ -197,7 +193,7 @@ func TestInstantiateProposal_NoAdmin(t *testing.T) { Updated: types.NewAbsoluteTxPosition(ctx), Msg: src.Msg, }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, sdk.AccAddress(contractAddr))) + assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) // and event require.Len(t, em.Events(), 3, "%#v", em.Events()) require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) @@ -226,8 +222,8 @@ func TestMigrateProposal(t *testing.T) { require.NoError(t, wasmKeeper.importCode(ctx, 2, codeInfoFixture, wasmCode)) var ( - anyAddress sdk.AccAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, types.ContractAddrLen)) - otherAddress sdk.AccAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, types.ContractAddrLen)) + anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) + otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) contractAddr = BuildContractAddress(1, 1) ) @@ -406,7 +402,7 @@ func TestSudoProposal(t *testing.T) { func TestAdminProposals(t *testing.T) { var ( - otherAddress sdk.AccAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, types.ContractAddrLen)) + otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) contractAddr = BuildContractAddress(1, 1) ) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") @@ -446,7 +442,7 @@ func TestAdminProposals(t *testing.T) { Description: "Bar", Contract: contractAddr.String(), }, - expAdmin: "", + expAdmin: nil, }, "clear with old admin empty": { state: types.ContractInfoFixture(func(info *types.ContractInfo) { @@ -457,7 +453,7 @@ func TestAdminProposals(t *testing.T) { Description: "Bar", Contract: contractAddr.String(), }, - expAdmin: "", + expAdmin: nil, }, } for msg, spec := range specs { @@ -499,7 +495,7 @@ func TestUpdateParamsProposal(t *testing.T) { var ( legacyAmino = keepers.EncodingConfig.Amino - myAddress sdk.AccAddress = sdk.BytesToAccAddress(make([]byte, types.ContractAddrLen)) + myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) oneAddressAccessConfig = types.AccessTypeOnlyAddress.With(myAddress) ) @@ -838,7 +834,8 @@ func TestUpdateInstantiateConfigProposal(t *testing.T) { CreateFn: wasmtesting.NoOpCreateFn, AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, } - anyAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, types.ContractAddrLen)) + anyAddress, err := sdk.AccAddressFromBech32("link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23") + require.NoError(t, err) withAddressAccessConfig := types.AccessTypeOnlyAddress.With(anyAddress) var ( @@ -885,7 +882,6 @@ func TestUpdateInstantiateConfigProposal(t *testing.T) { parentCtx := ctx for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() updates := make([]types.AccessConfigUpdate, 0) diff --git a/x/wasm/keeper/querier.go b/x/wasm/keeper/querier.go index 481f18bcbc..ca21e6d943 100644 --- a/x/wasm/keeper/querier.go +++ b/x/wasm/keeper/querier.go @@ -35,11 +35,11 @@ func (q GrpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInf if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - err := sdk.ValidateAccAddress(req.Address) + contractAddr, err := sdk.AccAddressFromBech32(req.Address) if err != nil { return nil, err } - rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), sdk.AccAddress(req.Address), q.keeper) + rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), contractAddr, q.keeper) switch { case err != nil: return nil, err @@ -53,7 +53,7 @@ func (q GrpcQuerier) ContractHistory(c context.Context, req *types.QueryContract if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - err := sdk.ValidateAccAddress(req.Address) + contractAddr, err := sdk.AccAddressFromBech32(req.Address) if err != nil { return nil, err } @@ -61,7 +61,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(sdk.AccAddress(req.Address))) + prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { if accumulate { var e types.ContractCodeHistoryEntry @@ -96,7 +96,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(string(key[types.AbsoluteTxPositionLen:])) + var contractAddr sdk.AccAddress = key[types.AbsoluteTxPositionLen:] r = append(r, contractAddr.String()) } return true, nil @@ -114,17 +114,17 @@ func (q GrpcQuerier) AllContractState(c context.Context, req *types.QueryAllCont if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } - err := sdk.ValidateAccAddress(req.Address) + contractAddr, err := sdk.AccAddressFromBech32(req.Address) if err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) - if !q.keeper.HasContractInfo(ctx, sdk.AccAddress(req.Address)) { + if !q.keeper.HasContractInfo(ctx, contractAddr) { return nil, types.ErrNotFound } r := make([]types.Model, 0) - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractStorePrefix(sdk.AccAddress(req.Address))) + prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractStorePrefix(contractAddr)) pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { if accumulate { r = append(r, types.Model{ @@ -149,15 +149,15 @@ func (q GrpcQuerier) RawContractState(c context.Context, req *types.QueryRawCont } ctx := sdk.UnwrapSDKContext(c) - err := sdk.ValidateAccAddress(req.Address) + contractAddr, err := sdk.AccAddressFromBech32(req.Address) if err != nil { return nil, err } - if !q.keeper.HasContractInfo(ctx, sdk.AccAddress(req.Address)) { + if !q.keeper.HasContractInfo(ctx, contractAddr) { return nil, types.ErrNotFound } - rsp := q.keeper.QueryRaw(ctx, sdk.AccAddress(req.Address), req.QueryData) + rsp := q.keeper.QueryRaw(ctx, contractAddr, req.QueryData) return &types.QueryRawContractStateResponse{Data: rsp}, nil } @@ -168,7 +168,7 @@ func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart if err := req.QueryData.ValidateBasic(); err != nil { return nil, status.Error(codes.InvalidArgument, "invalid query data") } - err = sdk.ValidateAccAddress(req.Address) + contractAddr, err := sdk.AccAddressFromBech32(req.Address) if err != nil { return nil, err } @@ -194,7 +194,7 @@ func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart } }() - bz, err := q.keeper.QuerySmart(ctx, sdk.AccAddress(req.Address), req.QueryData) + bz, err := q.keeper.QuerySmart(ctx, contractAddr, req.QueryData) switch { case err != nil: return nil, err @@ -202,7 +202,6 @@ func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart return nil, types.ErrNotFound } return &types.QuerySmartContractStateResponse{Data: bz}, nil - } func (q GrpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*types.QueryCodeResponse, error) { @@ -300,7 +299,6 @@ func (q GrpcQuerier) PinnedCodes(c context.Context, req *types.QueryPinnedCodesR prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.PinnedCodeIndexPrefix) pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, _ []byte, accumulate bool) (bool, error) { if accumulate { - r = append(r, sdk.BigEndianToUint64(key)) } return true, nil @@ -312,5 +310,4 @@ func (q GrpcQuerier) PinnedCodes(c context.Context, req *types.QueryPinnedCodesR CodeIDs: r, Pagination: pageRes, }, nil - } diff --git a/x/wasm/keeper/querier_test.go b/x/wasm/keeper/querier_test.go index 5fe09fdedb..38183ab1a8 100644 --- a/x/wasm/keeper/querier_test.go +++ b/x/wasm/keeper/querier_test.go @@ -297,7 +297,7 @@ func TestQueryContractListByCodeOrdering(t *testing.T) { ctx = setBlock(ctx, h) h++ } - _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, "", initMsgBz, fmt.Sprintf("contract %d", i), topUp) + _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) require.NoError(t, err) } @@ -436,7 +436,7 @@ func TestQueryContractHistory(t *testing.T) { t.Run(msg, func(t *testing.T) { xCtx, _ := ctx.CacheContext() - cAddr := sdk.AccAddress(myContractBech32Addr) + cAddr, _ := sdk.AccAddressFromBech32(myContractBech32Addr) keeper.appendToContractHistory(xCtx, cAddr, spec.srcHistory...) // when @@ -725,17 +725,13 @@ func TestQueryPinnedCodes(t *testing.T) { } func TestQueryCodeInfo(t *testing.T) { - wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) keeper := keepers.WasmKeeper - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" - err = sdk.ValidateAccAddress(anyAddress) - require.NoError(t, err) - + anyAddress, err := sdk.AccAddressFromBech32("link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5") require.NoError(t, err) specs := map[string]struct { codeId uint64 @@ -751,7 +747,7 @@ func TestQueryCodeInfo(t *testing.T) { }, "with_address": { codeId: 20, - accessConfig: types.AccessTypeOnlyAddress.With(sdk.AccAddress(anyAddress)), + accessConfig: types.AccessTypeOnlyAddress.With(anyAddress), }, } for msg, spec := range specs { @@ -791,9 +787,7 @@ func TestQueryCodeInfoList(t *testing.T) { ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) keeper := keepers.WasmKeeper - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" - err = sdk.ValidateAccAddress(anyAddress) - require.NoError(t, err) + anyAddress, err := sdk.AccAddressFromBech32("link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5") require.NoError(t, err) codeInfoWithConfig := func(accessConfig types.AccessConfig) types.CodeInfo { codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) @@ -819,7 +813,7 @@ func TestQueryCodeInfoList(t *testing.T) { { name: "with_address", codeId: 20, - codeInfo: codeInfoWithConfig(types.AccessTypeOnlyAddress.With(sdk.AccAddress(anyAddress))), + codeInfo: codeInfoWithConfig(types.AccessTypeOnlyAddress.With(anyAddress)), }, } @@ -848,7 +842,6 @@ func TestQueryCodeInfoList(t *testing.T) { require.NoError(t, err) require.Len(t, got.CodeInfos, 3) require.EqualValues(t, allCodesResponse, got.CodeInfos) - } func fromBase64(s string) []byte { diff --git a/x/wasm/keeper/query_plugins.go b/x/wasm/keeper/query_plugins.go index 31f5e23aee..76b4c56995 100644 --- a/x/wasm/keeper/query_plugins.go +++ b/x/wasm/keeper/query_plugins.go @@ -166,22 +166,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 { - err := sdk.ValidateAccAddress(request.AllBalances.Address) + addr, err := sdk.AccAddressFromBech32(request.AllBalances.Address) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address) } - coins := bankKeeper.GetAllBalances(ctx, sdk.AccAddress(request.AllBalances.Address)) + coins := bankKeeper.GetAllBalances(ctx, addr) res := wasmvmtypes.AllBalancesResponse{ Amount: ConvertSdkCoinsToWasmCoins(coins), } return json.Marshal(res) } if request.Balance != nil { - err := sdk.ValidateAccAddress(request.Balance.Address) + addr, err := sdk.AccAddressFromBech32(request.Balance.Address) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address) } - coin := bankKeeper.GetBalance(ctx, sdk.AccAddress(request.Balance.Address), request.Balance.Denom) + coin := bankKeeper.GetBalance(ctx, addr, request.Balance.Denom) res := wasmvmtypes.BalanceResponse{ Amount: wasmvmtypes.Coin{ Denom: coin.Denom, @@ -321,11 +321,11 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee return json.Marshal(res) } if request.Validator != nil { - err := sdk.ValidateValAddress(request.Validator.Address) + valAddr, err := sdk.ValAddressFromBech32(request.Validator.Address) if err != nil { return nil, err } - v, found := keeper.GetValidator(ctx, sdk.ValAddress(request.Validator.Address)) + v, found := keeper.GetValidator(ctx, valAddr) res := wasmvmtypes.ValidatorResponse{} if found { res.Validator = &wasmvmtypes.Validator{ @@ -338,11 +338,11 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee return json.Marshal(res) } if request.AllDelegations != nil { - err := sdk.ValidateAccAddress(request.AllDelegations.Delegator) + delegator, err := sdk.AccAddressFromBech32(request.AllDelegations.Delegator) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllDelegations.Delegator) } - sdkDels := keeper.GetAllDelegatorDelegations(ctx, sdk.AccAddress(request.AllDelegations.Delegator)) + sdkDels := keeper.GetAllDelegatorDelegations(ctx, delegator) delegations, err := sdkToDelegations(ctx, keeper, sdkDels) if err != nil { return nil, err @@ -353,18 +353,17 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee return json.Marshal(res) } if request.Delegation != nil { - err := sdk.ValidateAccAddress(request.Delegation.Delegator) + delegator, err := sdk.AccAddressFromBech32(request.Delegation.Delegator) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Delegator) } - err = sdk.ValidateValAddress(request.Delegation.Validator) + validator, err := sdk.ValAddressFromBech32(request.Delegation.Validator) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator) } var res wasmvmtypes.DelegationResponse - d, found := keeper.GetDelegation(ctx, sdk.AccAddress(request.Delegation.Delegator), - sdk.ValAddress(request.Delegation.Validator)) + d, found := keeper.GetDelegation(ctx, delegator, validator) if found { res.Delegation, err = sdkToFullDelegation(ctx, keeper, distKeeper, d) if err != nil { @@ -382,11 +381,11 @@ func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations [ bondDenom := keeper.BondDenom(ctx) for i, d := range delegations { - err := sdk.ValidateAccAddress(d.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "delegator address") } - err = sdk.ValidateValAddress(d.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "validator address") } @@ -394,15 +393,15 @@ func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations [ // shares to amount logic comes from here: // x/staking/keeper/querier.go DelegationToDelegationResponse /// https://github.com/cosmos/cosmos-sdk/blob/3ccf3913f53e2a9ccb4be8429bee32e67669e89a/x/staking/keeper/querier.go#L450 - val, found := keeper.GetValidator(ctx, sdk.ValAddress(d.ValidatorAddress)) + val, found := keeper.GetValidator(ctx, valAddr) 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: sdk.AccAddress(d.DelegatorAddress).String(), - Validator: sdk.ValAddress(d.ValidatorAddress).String(), + Delegator: delAddr.String(), + Validator: valAddr.String(), Amount: ConvertSdkCoinToWasmCoin(amount), } } @@ -410,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) { - err := sdk.ValidateAccAddress(delegation.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "delegator address") } - err = sdk.ValidateValAddress(delegation.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "validator address") } - val, found := keeper.GetValidator(ctx, sdk.ValAddress(delegation.ValidatorAddress)) + val, found := keeper.GetValidator(ctx, valAddr) if !found { return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") } @@ -433,8 +432,7 @@ 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, sdk.AccAddress(delegation.DelegatorAddress), - sdk.ValAddress(delegation.ValidatorAddress)) { + if !keeper.HasReceivingRedelegation(ctx, delAddr, valAddr) { redelegateCoins = delegationCoins } @@ -448,8 +446,8 @@ func sdkToFullDelegation(ctx sdk.Context, keeper types.StakingKeeper, distKeeper } return &wasmvmtypes.FullDelegation{ - Delegator: sdk.AccAddress(delegation.DelegatorAddress).String(), - Validator: sdk.ValAddress(delegation.ValidatorAddress).String(), + Delegator: delAddr.String(), + Validator: valAddr.String(), Amount: delegationCoins, AccumulatedRewards: accRewards, CanRedelegate: redelegateCoins, @@ -485,7 +483,7 @@ func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.W return func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { switch { case request.Smart != nil: - err := sdk.ValidateAccAddress(request.Smart.ContractAddr) + addr, err := sdk.AccAddressFromBech32(request.Smart.ContractAddr) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Smart.ContractAddr) } @@ -493,19 +491,19 @@ func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.W if err := msg.ValidateBasic(); err != nil { return nil, sdkerrors.Wrap(err, "json msg") } - return k.QuerySmart(ctx, sdk.AccAddress(request.Smart.ContractAddr), msg) + return k.QuerySmart(ctx, addr, msg) case request.Raw != nil: - err := sdk.ValidateAccAddress(request.Raw.ContractAddr) + addr, err := sdk.AccAddressFromBech32(request.Raw.ContractAddr) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Raw.ContractAddr) } - return k.QueryRaw(ctx, sdk.AccAddress(request.Raw.ContractAddr), request.Raw.Key), nil + return k.QueryRaw(ctx, addr, request.Raw.Key), nil case request.ContractInfo != nil: - err := sdk.ValidateAccAddress(request.ContractInfo.ContractAddr) + addr, err := sdk.AccAddressFromBech32(request.ContractInfo.ContractAddr) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.ContractInfo.ContractAddr) } - info := k.GetContractInfo(ctx, sdk.AccAddress(request.ContractInfo.ContractAddr)) + info := k.GetContractInfo(ctx, addr) if info == nil { return nil, &types.ErrNoSuchContract{Addr: request.ContractInfo.ContractAddr} } diff --git a/x/wasm/keeper/query_plugins_test.go b/x/wasm/keeper/query_plugins_test.go index 05085bf798..588637e7d0 100644 --- a/x/wasm/keeper/query_plugins_test.go +++ b/x/wasm/keeper/query_plugins_test.go @@ -344,9 +344,9 @@ func TestBankQuerierBalance(t *testing.T) { } func TestContractInfoWasmQuerier(t *testing.T) { - var myValidContractAddr = RandomBech32AccountAddress(t) - var myCreatorAddr = RandomBech32AccountAddress(t) - var myAdminAddr = RandomBech32AccountAddress(t) + myValidContractAddr := RandomBech32AccountAddress(t) + myCreatorAddr := RandomBech32AccountAddress(t) + myAdminAddr := RandomBech32AccountAddress(t) var ctx sdk.Context specs := map[string]struct { @@ -465,7 +465,7 @@ func TestQueryErrors(t *testing.T) { return nil, spec.src }) ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter()).WithMultiStore(store.NewCommitMultiStore(memdb.NewDB())) - q := NewQueryHandler(ctx, mock, sdk.AccAddress(""), NewGasMultiplier(types.DefaultGasMultiplier)) + q := NewQueryHandler(ctx, mock, sdk.AccAddress{}, NewGasMultiplier(types.DefaultGasMultiplier)) _, gotErr := q.Query(wasmvmtypes.QueryRequest{}, 1) assert.Equal(t, spec.expErr, gotErr) }) diff --git a/x/wasm/keeper/recurse_test.go b/x/wasm/keeper/recurse_test.go index a33406eccf..a568512580 100644 --- a/x/wasm/keeper/recurse_test.go +++ b/x/wasm/keeper/recurse_test.go @@ -54,9 +54,9 @@ func initRecurseContract(t *testing.T) (contract sdk.AccAddress, creator sdk.Acc func TestGasCostOnQuery(t *testing.T) { const ( - GasNoWork uint64 = 64_030 + GasNoWork uint64 = 63_937 // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork50 uint64 = 64_328 // this is a little shy of 50k gas - to keep an eye on the limit + GasWork50 uint64 = 64_235 // this is a little shy of 50k gas - to keep an eye on the limit GasReturnUnhashed uint64 = 29 GasReturnHashed uint64 = 24 @@ -217,7 +217,7 @@ func TestLimitRecursiveQueryGas(t *testing.T) { const ( // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork2k uint64 = 78_292 // = NewContractInstanceCosts + x // we have 6x gas used in cpu than in the instance + GasWork2k uint64 = 78_199 // = NewContractInstanceCosts + x // we have 6x gas used in cpu than in the instance // This is overhead for calling into a sub-contract GasReturnHashed uint64 = 21 ) diff --git a/x/wasm/keeper/reflect_test.go b/x/wasm/keeper/reflect_test.go index 3197f09519..a37490b4f9 100644 --- a/x/wasm/keeper/reflect_test.go +++ b/x/wasm/keeper/reflect_test.go @@ -109,7 +109,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, "", []byte("{}"), "reflect contract 2", reflectStart) + reflectAddr, _, err := keeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) require.NoError(t, err) require.NotEmpty(t, reflectAddr) @@ -121,7 +121,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, "", initMsgBz, "escrow contract 2", escrowStart) + escrowAddr, _, err := keeper.Instantiate(ctx, escrowID, creator, nil, initMsgBz, "escrow contract 2", escrowStart) require.NoError(t, err) require.NotEmpty(t, escrowAddr) @@ -163,7 +163,6 @@ func TestReflectContractSend(t *testing.T) { checkAccount(t, ctx, accKeeper, bankKeeper, reflectAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 26000))) // 40k - 14k (from send) checkAccount(t, ctx, accKeeper, bankKeeper, escrowAddr, sdk.Coins{}) // emptied reserved checkAccount(t, ctx, accKeeper, bankKeeper, bob, sdk.NewCoins(sdk.NewInt64Coin("denom", 39000))) // all escrow of 25k + 14k - } func TestReflectCustomMsg(t *testing.T) { @@ -185,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, "", []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -276,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, "", []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -327,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, "", []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -371,7 +370,7 @@ func TestReflectInvalidStargateQuery(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, sdk.AccAddress(""), []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -452,7 +451,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, "", []byte("{}"), "reflect contract 2", reflectStart) + reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) require.NoError(t, err) require.NotEmpty(t, reflectAddr) @@ -524,7 +523,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, "", []byte("{}"), "reflect contract 2", reflectStart) + reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) require.NoError(t, err) require.NotEmpty(t, reflectAddr) diff --git a/x/wasm/keeper/relay_test.go b/x/wasm/keeper/relay_test.go index 4dc328d358..d48a0f8103 100644 --- a/x/wasm/keeper/relay_test.go +++ b/x/wasm/keeper/relay_test.go @@ -34,12 +34,12 @@ func TestOnOpenChannel(t *testing.T) { "consume contract gas": { contractAddr: example.Contract, contractGas: myContractGas, - expGas: myContractGas, + expGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go }, "consume max gas": { contractAddr: example.Contract, contractGas: math.MaxUint64 / types.DefaultGasMultiplier, - expGas: math.MaxUint64 / types.DefaultGasMultiplier, + expGas: math.MaxUint64/types.DefaultGasMultiplier - 18, // FIXME remove x/ibc and use ibc-go }, "consume gas on error": { contractAddr: example.Contract, @@ -80,7 +80,7 @@ func TestOnOpenChannel(t *testing.T) { } require.NoError(t, err) // verify gas consumed - const storageCosts = sdk.Gas(0xba2) + const storageCosts = sdk.Gas(2903) assert.Equal(t, spec.expGas, ctx.GasMeter().GasConsumed()-before-storageCosts) }) } @@ -105,7 +105,7 @@ func TestOnConnectChannel(t *testing.T) { }{ "consume contract gas": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go, contractResp: &wasmvmtypes.IBCBasicResponse{}, }, "consume gas on error, ignore events + messages": { @@ -120,14 +120,14 @@ func TestOnConnectChannel(t *testing.T) { }, "dispatch contract messages on success": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, }, }, "emit contract events on success": { contractAddr: example.Contract, - expContractGas: myContractGas + 10, + expContractGas: myContractGas + 10 - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, }, @@ -186,7 +186,7 @@ func TestOnConnectChannel(t *testing.T) { require.NoError(t, err) // verify gas consumed - const storageCosts = sdk.Gas(0xba2) + const storageCosts = sdk.Gas(2903) assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) // verify msgs dispatched @@ -218,7 +218,7 @@ func TestOnCloseChannel(t *testing.T) { }{ "consume contract gas": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{}, }, "consume gas on error, ignore events + messages": { @@ -233,14 +233,14 @@ func TestOnCloseChannel(t *testing.T) { }, "dispatch contract messages on success": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, }, }, "emit contract events on success": { contractAddr: example.Contract, - expContractGas: myContractGas + 10, + expContractGas: myContractGas + 10 - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, }, @@ -297,7 +297,7 @@ func TestOnCloseChannel(t *testing.T) { } require.NoError(t, err) // verify gas consumed - const storageCosts = sdk.Gas(0xba2) + const storageCosts = sdk.Gas(2903) assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) // verify msgs dispatched @@ -332,7 +332,7 @@ func TestOnRecvPacket(t *testing.T) { }{ "consume contract gas": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCReceiveResponse{ Acknowledgement: []byte("myAck"), }, @@ -340,7 +340,7 @@ func TestOnRecvPacket(t *testing.T) { }, "can return empty ack": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCReceiveResponse{}, }, "consume gas on error, ignore events + messages": { @@ -356,7 +356,7 @@ func TestOnRecvPacket(t *testing.T) { }, "dispatch contract messages on success": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCReceiveResponse{ Acknowledgement: []byte("myAck"), Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, @@ -365,7 +365,7 @@ func TestOnRecvPacket(t *testing.T) { }, "emit contract attributes on success": { contractAddr: example.Contract, - expContractGas: myContractGas + 10, + expContractGas: myContractGas + 10 - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCReceiveResponse{ Acknowledgement: []byte("myAck"), Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, @@ -375,7 +375,7 @@ func TestOnRecvPacket(t *testing.T) { }, "emit contract events on success": { contractAddr: example.Contract, - expContractGas: myContractGas + 46, // charge or custom event as well + expContractGas: myContractGas + 46 - 18, // charge or custom event as well // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCReceiveResponse{ Acknowledgement: []byte("myAck"), Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, @@ -404,7 +404,7 @@ func TestOnRecvPacket(t *testing.T) { }, "submessage reply can overwrite ack data": { contractAddr: example.Contract, - expContractGas: myContractGas + 10 + 2968, + expContractGas: myContractGas + storageCosts - 18*2, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCReceiveResponse{ Acknowledgement: []byte("myAck"), Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyAlways, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, @@ -460,7 +460,7 @@ func TestOnRecvPacket(t *testing.T) { require.Equal(t, spec.expAck, gotAck) // verify gas consumed - const storageCosts = sdk.Gas(0xba2) + const storageCosts = sdk.Gas(2903) assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) // verify msgs dispatched @@ -492,7 +492,7 @@ func TestOnAckPacket(t *testing.T) { }{ "consume contract gas": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{}, }, "consume gas on error, ignore events + messages": { @@ -507,14 +507,14 @@ func TestOnAckPacket(t *testing.T) { }, "dispatch contract messages on success": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, }, }, "emit contract events on success": { contractAddr: example.Contract, - expContractGas: myContractGas + 10, + expContractGas: myContractGas + 10 - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, }, @@ -568,7 +568,7 @@ func TestOnAckPacket(t *testing.T) { require.NoError(t, err) // verify gas consumed - const storageCosts = sdk.Gas(0xba2) + const storageCosts = sdk.Gas(2903) assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) // verify msgs dispatched @@ -600,7 +600,7 @@ func TestOnTimeoutPacket(t *testing.T) { }{ "consume contract gas": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{}, }, "consume gas on error, ignore events + messages": { @@ -615,7 +615,7 @@ func TestOnTimeoutPacket(t *testing.T) { }, "dispatch contract messages on success": { contractAddr: example.Contract, - expContractGas: myContractGas, + expContractGas: myContractGas - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, @@ -623,7 +623,7 @@ func TestOnTimeoutPacket(t *testing.T) { }, "emit contract attributes on success": { contractAddr: example.Contract, - expContractGas: myContractGas + 10, + expContractGas: myContractGas + 10 - 18, // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, }, @@ -631,7 +631,7 @@ func TestOnTimeoutPacket(t *testing.T) { }, "emit contract events on success": { contractAddr: example.Contract, - expContractGas: myContractGas + 46, // cost for custom events + expContractGas: myContractGas + 46 - 18, // cost for custom events // FIXME remove x/ibc and use ibc-go contractResp: &wasmvmtypes.IBCBasicResponse{ Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, Events: []wasmvmtypes.Event{{ @@ -690,7 +690,7 @@ func TestOnTimeoutPacket(t *testing.T) { } require.NoError(t, err) // verify gas consumed - const storageCosts = sdk.Gas(0xba2) + const storageCosts = sdk.Gas(2903) assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) // verify msgs dispatched diff --git a/x/wasm/keeper/staking_test.go b/x/wasm/keeper/staking_test.go index 8a63987fdf..40c72650d8 100644 --- a/x/wasm/keeper/staking_test.go +++ b/x/wasm/keeper/staking_test.go @@ -124,7 +124,7 @@ func TestInitializeStaking(t *testing.T) { initBz, err := json.Marshal(&initMsg) require.NoError(t, err) - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, "", initBz, "staking derivates - DRV", nil) + stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) require.NoError(t, err) require.NotEmpty(t, stakingAddr) @@ -137,14 +137,14 @@ func TestInitializeStaking(t *testing.T) { Name: "Missing Validator", Symbol: "MISS", Decimals: 0, - Validator: bob.ToValAddress(), + Validator: sdk.ValAddress(bob), ExitTax: sdk.MustNewDecFromStr("0.10"), MinWithdrawl: "100", } badBz, err := json.Marshal(&badInitMsg) require.NoError(t, err) - _, _, err = k.ContractKeeper.Instantiate(ctx, stakingID, creator, "", badBz, "missing validator", nil) + _, _, err = k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, badBz, "missing validator", nil) require.Error(t, err) // no changes to bonding shares @@ -207,7 +207,7 @@ func initializeStaking(t *testing.T) initInfo { initBz, err := json.Marshal(&initMsg) require.NoError(t, err) - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, "", initBz, "staking derivates - DRV", nil) + stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) require.NoError(t, err) require.NotEmpty(t, stakingAddr) @@ -454,7 +454,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, "", []byte("{}"), "mask contract 2", nil) + maskAddr, _, err := initInfo.contractKeeper.Instantiate(ctx, maskID, creator, nil, []byte("{}"), "mask contract 2", nil) require.NoError(t, err) require.NotEmpty(t, maskAddr) @@ -514,7 +514,7 @@ func TestQueryStakingInfo(t *testing.T) { require.Contains(t, valInfo.MaxChangeRate, "0.010") // missing validator - noVal := sdk.BytesToValAddress(secp256k1.GenPrivKey().PubKey().Address()) + noVal := sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()) reflectNoValidatorQuery := ReflectQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ Validator: &wasmvmtypes.ValidatorQuery{ Address: noVal.String(), @@ -658,7 +658,7 @@ func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper stakingkeeper.Kee privKey := secp256k1.GenPrivKey() pubKey := privKey.PubKey() - addr := sdk.BytesToValAddress(pubKey.Address()) + addr := sdk.ValAddress(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 38981a9939..abbe67bcbe 100644 --- a/x/wasm/keeper/submsg_test.go +++ b/x/wasm/keeper/submsg_test.go @@ -38,7 +38,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, "", []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -140,7 +140,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { } initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - hackatomAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, hackatomID, uploader, "", initMsgBz, "hackatom demo", contractStart) + hackatomAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, hackatomID, uploader, nil, initMsgBz, "hackatom demo", contractStart) require.NoError(t, err) validBankSend := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { @@ -247,14 +247,14 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { "send tokens": { submsgID: 5, msg: validBankSend, - resultAssertions: []assertion{assertReturnedEvents(3), assertGasUsed(113000, 114147)}, + resultAssertions: []assertion{assertReturnedEvents(3), assertGasUsed(110300, 110400)}, }, "not enough tokens": { submsgID: 6, msg: invalidBankSend, subMsgError: true, // uses less gas than the send tokens (cost of bank transfer) - resultAssertions: []assertion{assertGasUsed(76900, 77113), assertErrorString("codespace: sdk, code: 5")}, + resultAssertions: []assertion{assertGasUsed(75600, 75700), assertErrorString("codespace: sdk, code: 5")}, }, "out of gas panic with no gas limit": { submsgID: 7, @@ -267,7 +267,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { msg: validBankSend, gasLimit: &subGasLimit, // uses same gas as call without limit (note we do not charge the 40k on reply) - resultAssertions: []assertion{assertReturnedEvents(3), assertGasUsed(113100, 114249)}, + resultAssertions: []assertion{assertReturnedEvents(3), assertGasUsed(110400, 110500)}, }, "not enough tokens with limit": { submsgID: 16, @@ -275,7 +275,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { subMsgError: true, gasLimit: &subGasLimit, // uses same gas as call without limit (note we do not charge the 40k on reply) - resultAssertions: []assertion{assertGasUsed(77000, 77113), assertErrorString("codespace: sdk, code: 5")}, + resultAssertions: []assertion{assertGasUsed(75700, 75800), assertErrorString("codespace: sdk, code: 5")}, }, "out of gas caught with gas limit": { submsgID: 17, @@ -283,7 +283,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { subMsgError: true, gasLimit: &subGasLimit, // uses all the subGasLimit, plus the 52k or so for the main contract - resultAssertions: []assertion{assertGasUsed(subGasLimit+74000, subGasLimit+75000), assertErrorString("codespace: sdk, code: 11")}, + resultAssertions: []assertion{assertGasUsed(subGasLimit+73000, subGasLimit+74000), assertErrorString("codespace: sdk, code: 11")}, }, "instantiate contract gets address in data and events": { submsgID: 21, @@ -296,7 +296,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { creator := keepers.Faucet.NewFundedAccount(ctx, contractStart...) _, _, empty := keyPubAddr() - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, "", []byte("{}"), fmt.Sprintf("contract %s", name), contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), fmt.Sprintf("contract %s", name), contractStart) require.NoError(t, err) msg := tc.msg(contractAddr.String(), empty.String()) @@ -387,7 +387,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, "", []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) require.NoError(t, err) require.NotEmpty(t, contractAddr) @@ -455,7 +455,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, "", []byte("{}"), "reflect contract 1", contractStart) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []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 26d20d8ac4..18356d3781 100644 --- a/x/wasm/keeper/test_common.go +++ b/x/wasm/keeper/test_common.go @@ -249,7 +249,8 @@ func createTestInput( keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey], ) - for _, m := range []string{authtypes.ModuleName, + for _, m := range []string{ + authtypes.ModuleName, banktypes.ModuleName, stakingtypes.ModuleName, minttypes.ModuleName, @@ -260,7 +261,8 @@ func createTestInput( capabilitytypes.ModuleName, ibchost.ModuleName, govtypes.ModuleName, - types.ModuleName} { + types.ModuleName, + } { paramsKeeper.Subspace(m) } subspace := func(m string) paramstypes.Subspace { @@ -465,11 +467,11 @@ func TestHandler(k types.ContractOpsKeeper) sdk.Handler { } func handleStoreCode(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgStoreCode) (*sdk.Result, error) { - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - codeID, err := k.Create(ctx, sdk.AccAddress(msg.Sender), msg.WASMByteCode, msg.InstantiatePermission) + codeID, err := k.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission) if err != nil { return nil, err } @@ -481,38 +483,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) { - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } + var adminAddr sdk.AccAddress if msg.Admin != "" { - if err = sdk.ValidateAccAddress(msg.Admin); err != nil { + if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { return nil, sdkerrors.Wrap(err, "admin") } } - contractAddr, _, err := k.Instantiate(ctx, msg.CodeID, sdk.AccAddress(msg.Sender), sdk.AccAddress(msg.Admin), - msg.Msg, msg.Label, msg.Funds) + contractAddr, _, err := k.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds) if err != nil { return nil, err } return &sdk.Result{ - Data: contractAddr.Bytes(), + Data: contractAddr, Events: ctx.EventManager().Events().ToABCIEvents(), }, nil } func handleExecute(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgExecuteContract) (*sdk.Result, error) { - err := sdk.ValidateAccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { return nil, sdkerrors.Wrap(err, "sender") } - err = sdk.ValidateAccAddress(msg.Contract) + contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { return nil, sdkerrors.Wrap(err, "admin") } - data, err := k.Execute(ctx, sdk.AccAddress(msg.Contract), sdk.AccAddress(msg.Sender), msg.Msg, msg.Funds) + data, err := k.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) if err != nil { return nil, err } @@ -602,7 +604,8 @@ func StoreRandomContractWithAccessConfig( t testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine, - cfg *types.AccessConfig) ExampleContract { + cfg *types.AccessConfig, +) ExampleContract { t.Helper() anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) creator, _, creatorAddr := keyPubAddr() @@ -613,7 +616,6 @@ func StoreRandomContractWithAccessConfig( require.NoError(t, err) exampleContract := ExampleContract{InitialAmount: anyAmount, Creator: creator, CreatorAddr: creatorAddr, CodeID: codeID} return exampleContract - } type HackatomExampleInstance struct { @@ -731,6 +733,6 @@ func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { key := ed25519.GenPrivKeyFromSecret(seed) pub := key.PubKey() - addr := sdk.BytesToAccAddress(pub.Address()) + addr := sdk.AccAddress(pub.Address()) return key, pub, addr } diff --git a/x/wasm/keeper/test_fuzz.go b/x/wasm/keeper/test_fuzz.go index 4003ac7e42..4e31a3899c 100644 --- a/x/wasm/keeper/test_fuzz.go +++ b/x/wasm/keeper/test_fuzz.go @@ -13,9 +13,8 @@ import ( var ModelFuzzers = []interface{}{FuzzAddr, FuzzAddrString, FuzzAbsoluteTxPosition, FuzzContractInfo, FuzzStateModel, FuzzAccessType, FuzzAccessConfig, FuzzContractCodeHistory} func FuzzAddr(m *sdk.AccAddress, c fuzz.Continue) { - addrBytes := make([]byte, 20) - c.Read(addrBytes) - *m = sdk.BytesToAccAddress(addrBytes) + *m = make([]byte, 20) + c.Read(*m) } func FuzzAddrString(m *string, c fuzz.Continue) { @@ -68,6 +67,7 @@ func FuzzAccessType(m *types.AccessType, c fuzz.Continue) { pos-- } } + func FuzzAccessConfig(m *types.AccessConfig, c fuzz.Continue) { FuzzAccessType(&m.Permission, c) var add sdk.AccAddress diff --git a/x/wasm/module_test.go b/x/wasm/module_test.go index c1851aefb7..f8d7a2544e 100644 --- a/x/wasm/module_test.go +++ b/x/wasm/module_test.go @@ -50,7 +50,7 @@ func setupTest(t *testing.T) testData { func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { key := ed25519.GenPrivKey() pub := key.PubKey() - addr := sdk.BytesToAccAddress(pub.Address()) + addr := sdk.AccAddress(pub.Address()) return key, pub, addr } @@ -436,7 +436,7 @@ func TestHandleExecute(t *testing.T) { assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, creatorAcct.GetAddress())) // ensure contract has updated balance - contractAddr := sdk.AccAddress(contractBech32Addr) + contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) require.NotNil(t, contractAcct) assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) @@ -577,7 +577,7 @@ func TestHandleExecuteEscrow(t *testing.T) { assert.Equal(t, deposit.Add(topUp...), balance) // ensure contract has updated balance - contractAddr := sdk.AccAddress(contractBech32Addr) + contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) require.NotNil(t, contractAcct) assert.Equal(t, sdk.Coins{}, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) @@ -723,7 +723,7 @@ func assertContractList(t *testing.T, q sdk.Querier, ctx sdk.Context, codeID uin err := json.Unmarshal(bz, &res) require.NoError(t, err) - var hasAddrs = make([]string, len(res)) + hasAddrs := make([]string, len(res)) for i, r := range res { hasAddrs[i] = r } diff --git a/x/wasm/types/genesis.go b/x/wasm/types/genesis.go index 5496bed95a..810dfe51dc 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.ValidateAccAddress(c.ContractAddress); err != nil { + if _, err := sdk.AccAddressFromBech32(c.ContractAddress); err != nil { return sdkerrors.Wrap(err, "contract address") } if err := c.ContractInfo.ValidateBasic(); err != nil { diff --git a/x/wasm/types/genesis_test.go b/x/wasm/types/genesis_test.go index d0c8dd0be3..22d0ea6752 100644 --- a/x/wasm/types/genesis_test.go +++ b/x/wasm/types/genesis_test.go @@ -180,9 +180,9 @@ func TestContractValidateBasic(t *testing.T) { } func TestGenesisContractInfoMarshalUnmarshal(t *testing.T) { - var myAddr sdk.AccAddress = sdk.BytesToAccAddress(rand.Bytes(ContractAddrLen)) - var myOtherAddr sdk.AccAddress = sdk.BytesToAccAddress(rand.Bytes(ContractAddrLen)) - var anyPos = AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} + var myAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) + var myOtherAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) + anyPos := AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} anyTime := time.Now().UTC() // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking diff --git a/x/wasm/types/keys_test.go b/x/wasm/types/keys_test.go index 60664636eb..340f8041cf 100644 --- a/x/wasm/types/keys_test.go +++ b/x/wasm/types/keys_test.go @@ -5,8 +5,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - - sdk "github.com/line/lbm-sdk/types" ) func TestGetContractByCodeIDSecondaryIndexPrefix(t *testing.T) { @@ -14,10 +12,12 @@ func TestGetContractByCodeIDSecondaryIndexPrefix(t *testing.T) { src uint64 exp []byte }{ - "small number": {src: 1, + "small number": { + src: 1, exp: []byte{6, 0, 0, 0, 0, 0, 0, 0, 1}, }, - "big number": {src: 1 << (8 * 7), + "big number": { + src: 1 << (8 * 7), exp: []byte{6, 1, 0, 0, 0, 0, 0, 0, 0}, }, } @@ -32,27 +32,21 @@ func TestGetContractByCodeIDSecondaryIndexPrefix(t *testing.T) { func TestGetContractCodeHistoryElementPrefix(t *testing.T) { // test that contract addresses of 20 length are still supported - addr := sdk.BytesToAccAddress(bytes.Repeat([]byte{4}, 20)) + addr := bytes.Repeat([]byte{4}, 20) got := GetContractCodeHistoryElementPrefix(addr) exp := []byte{5, // prefix - 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, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 20 bytes + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, } assert.Equal(t, exp, got) - addr = sdk.BytesToAccAddress(bytes.Repeat([]byte{4}, ContractAddrLen)) + addr = bytes.Repeat([]byte{4}, ContractAddrLen) got = GetContractCodeHistoryElementPrefix(addr) exp = []byte{5, // prefix - 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, 0x71, 0x73, 0x7a, - 0x71, 0x67, 0x70, 0x71, 0x79, 0x71, 0x73, 0x7a, 0x71, 0x67, - 0x70, 0x71, 0x79, 0x71, 0x73, 0x7a, 0x71, 0x77, 0x64, 0x6d, - 0x7a, 0x64, 0x75, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, } assert.Equal(t, exp, got) } @@ -64,13 +58,15 @@ func TestGetContractByCreatedSecondaryIndexKey(t *testing.T) { } // test that contract addresses of 20 length are still supported - addr := sdk.BytesToAccAddress(bytes.Repeat([]byte{4}, 20)) + addr := bytes.Repeat([]byte{4}, 20) got := GetContractByCreatedSecondaryIndexKey(addr, e) - exp := []byte{6, // prefix + 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 - 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, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, } assert.Equal(t, exp, got) } diff --git a/x/wasm/types/params.go b/x/wasm/types/params.go index 3abe823c6e..8365b020aa 100644 --- a/x/wasm/types/params.go +++ b/x/wasm/types/params.go @@ -57,8 +57,7 @@ func (a AccessType) With(addr sdk.AccAddress) AccessConfig { case AccessTypeNobody: return AllowNobody case AccessTypeOnlyAddress: - addrBytes, _ := sdk.AccAddressToBytes(addr.String()) - if err := sdk.VerifyAddressFormat(addrBytes); err != nil { + if err := sdk.VerifyAddressFormat(addr); err != nil { panic(err) } return AccessConfig{Permission: AccessTypeOnlyAddress, Address: addr.String()} @@ -90,6 +89,7 @@ func (a *AccessType) UnmarshalText(text []byte) error { *a = AccessTypeUnspecified return nil } + func (a AccessType) MarshalText() ([]byte, error) { return []byte(a.String()), nil } @@ -234,7 +234,7 @@ func (a AccessConfig) ValidateBasic() error { } return nil case AccessTypeOnlyAddress: - err := sdk.ValidateAccAddress(a.Address) + _, err := sdk.AccAddressFromBech32(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 9b0861c66e..ab2ccfb726 100644 --- a/x/wasm/types/params_test.go +++ b/x/wasm/types/params_test.go @@ -14,8 +14,8 @@ import ( func TestValidateParams(t *testing.T) { var ( - anyAddress = sdk.BytesToAccAddress(make([]byte, ContractAddrLen)) - invalidAddress = "invalid address" + anyAddress sdk.AccAddress = make([]byte, ContractAddrLen) + invalidAddress = "invalid address" ) specs := map[string]struct { @@ -200,12 +200,12 @@ func TestAccessTypeUnmarshalJson(t *testing.T) { }) } } + func TestParamsUnmarshalJson(t *testing.T) { specs := map[string]struct { src string exp Params }{ - "defaults": { src: `{"code_upload_access": {"permission": "Everybody"}, "instantiate_default_permission": "Everybody", diff --git a/x/wasm/types/proposal.go b/x/wasm/types/proposal.go index 1e6e1eb60b..f4e55b89dc 100644 --- a/x/wasm/types/proposal.go +++ b/x/wasm/types/proposal.go @@ -103,7 +103,7 @@ func (p StoreCodeProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if err := sdk.ValidateAccAddress(p.RunAs); err != nil { + if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { return sdkerrors.Wrap(err, "run as") } @@ -165,7 +165,7 @@ func (p InstantiateContractProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if err := sdk.ValidateAccAddress(p.RunAs); err != nil { + if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "run as") } @@ -182,7 +182,7 @@ func (p InstantiateContractProposal) ValidateBasic() error { } if len(p.Admin) != 0 { - if err := sdk.ValidateAccAddress(p.Admin); err != nil { + if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { return err } } @@ -249,7 +249,7 @@ func (p MigrateContractProposal) ValidateBasic() error { if p.CodeID == 0 { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code_id is required") } - if err := sdk.ValidateAccAddress(p.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } if err := p.Msg.ValidateBasic(); err != nil { @@ -303,7 +303,7 @@ func (p SudoContractProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if err := sdk.ValidateAccAddress(p.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } if err := p.Msg.ValidateBasic(); err != nil { @@ -354,10 +354,10 @@ func (p ExecuteContractProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if err := sdk.ValidateAccAddress(p.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } - if err := sdk.ValidateAccAddress(p.RunAs); err != nil { + if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { return sdkerrors.Wrap(err, "run as") } if !p.Funds.IsValid() { @@ -417,10 +417,10 @@ func (p UpdateAdminProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if err := sdk.ValidateAccAddress(p.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } - if err := sdk.ValidateAccAddress(p.NewAdmin); err != nil { + if _, err := sdk.AccAddressFromBech32(p.NewAdmin); err != nil { return sdkerrors.Wrap(err, "new admin") } return nil @@ -453,7 +453,7 @@ func (p ClearAdminProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if err := sdk.ValidateAccAddress(p.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } return nil @@ -549,7 +549,7 @@ func (p UpdateContractStatusProposal) ValidateBasic() error { if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } - if err := sdk.ValidateAccAddress(p.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(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 d6795931f4..74dfcc3007 100644 --- a/x/wasm/types/proposal_test.go +++ b/x/wasm/types/proposal_test.go @@ -96,8 +96,8 @@ func TestValidateProposalCommons(t *testing.T) { func TestValidateStoreCodeProposal(t *testing.T) { var ( - anyAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x0}, ContractAddrLen)) - invalidAddress = "invalid address" + anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) + invalidAddress = "invalid address" ) specs := map[string]struct { @@ -599,7 +599,7 @@ func TestProposalStrings(t *testing.T) { exp: `Store Code Proposal: Title: Foo Description: Bar - Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 + Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 WasmCode: 0102030405060708090A `, }, @@ -610,11 +610,11 @@ func TestProposalStrings(t *testing.T) { exp: `Instantiate Code Proposal: Title: Foo Description: Bar - Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 - Admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 + Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 + Admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 Code id: 1 Label: testing - Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5\",\"beneficiary\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5\"}" + Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23\",\"beneficiary\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23\"}" Funds: 1foo,2bar `, }, @@ -623,11 +623,11 @@ func TestProposalStrings(t *testing.T) { exp: `Instantiate Code Proposal: Title: Foo Description: Bar - Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 - Admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 + Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 + Admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 Code id: 1 Label: testing - Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5\",\"beneficiary\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5\"}" + Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23\",\"beneficiary\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23\"}" Funds: `, }, @@ -636,11 +636,11 @@ func TestProposalStrings(t *testing.T) { exp: `Instantiate Code Proposal: Title: Foo Description: Bar - Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 + Run as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 Admin: Code id: 1 Label: testing - Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5\",\"beneficiary\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5\"}" + Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23\",\"beneficiary\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23\"}" Funds: `, }, @@ -651,7 +651,7 @@ func TestProposalStrings(t *testing.T) { Description: Bar Contract: link1hcttwju93d5m39467gjcq63p5kc4fdcn30dgd8 Code id: 1 - Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5\"}" + Msg: "{\"verifier\":\"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23\"}" `, }, "update admin": { @@ -660,7 +660,7 @@ func TestProposalStrings(t *testing.T) { Title: Foo Description: Bar Contract: link1hcttwju93d5m39467gjcq63p5kc4fdcn30dgd8 - New Admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 + New Admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 `, }, "clear admin": { @@ -714,7 +714,7 @@ func TestProposalYaml(t *testing.T) { }), exp: `title: Foo description: Bar -run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 +run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 wasm_byte_code: AQIDBAUGBwgJCg== instantiate_permission: null `, @@ -725,11 +725,11 @@ instantiate_permission: null }), exp: `title: Foo description: Bar -run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 -admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 +run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 +admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 code_id: 1 label: testing -msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5","beneficiary":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5"}' +msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23","beneficiary":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23"}' funds: - denom: foo amount: "1" @@ -741,11 +741,11 @@ funds: src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Funds = nil }), exp: `title: Foo description: Bar -run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 -admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 +run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 +admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 code_id: 1 label: testing -msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5","beneficiary":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5"}' +msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23","beneficiary":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23"}' funds: [] `, }, @@ -753,11 +753,11 @@ funds: [] src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Admin = "" }), exp: `title: Foo description: Bar -run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 +run_as: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 admin: "" code_id: 1 label: testing -msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5","beneficiary":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5"}' +msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23","beneficiary":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23"}' funds: [] `, }, @@ -767,14 +767,14 @@ funds: [] description: Bar contract: link1hcttwju93d5m39467gjcq63p5kc4fdcn30dgd8 code_id: 1 -msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5"}' +msg: '{"verifier":"link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23"}' `, }, "update admin": { src: UpdateAdminProposalFixture(), exp: `title: Foo description: Bar -new_admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5 +new_admin: link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23 contract: link1hcttwju93d5m39467gjcq63p5kc4fdcn30dgd8 `, }, @@ -930,7 +930,7 @@ func TestProposalJsonSignBytes(t *testing.T) { } for name, spec := range specs { t.Run(name, func(t *testing.T) { - msg, err := govtypes.NewMsgSubmitProposal(spec.src, sdk.NewCoins(), sdk.AccAddress([]byte{})) + msg, err := govtypes.NewMsgSubmitProposal(spec.src, sdk.NewCoins(), []byte{}) require.NoError(t, err) bz := msg.GetSignBytes() diff --git a/x/wasm/types/test_fixtures.go b/x/wasm/types/test_fixtures.go index 432c16e2d5..8178c29e24 100644 --- a/x/wasm/types/test_fixtures.go +++ b/x/wasm/types/test_fixtures.go @@ -70,7 +70,7 @@ func CodeFixture(mutators ...func(*Code)) Code { func CodeInfoFixture(mutators ...func(*CodeInfo)) CodeInfo { wasmCode := bytes.Repeat([]byte{0x1}, 10) codeHash := sha256.Sum256(wasmCode) - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" fixture := CodeInfo{ CodeHash: codeHash[:], Creator: anyAddress, @@ -83,7 +83,7 @@ func CodeInfoFixture(mutators ...func(*CodeInfo)) CodeInfo { } func ContractFixture(mutators ...func(*Contract)) Contract { - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" fixture := Contract{ ContractAddress: anyAddress, @@ -102,7 +102,7 @@ func OnlyGenesisFields(info *ContractInfo) { } func ContractInfoFixture(mutators ...func(*ContractInfo)) ContractInfo { - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" fixture := ContractInfo{ CodeID: 1, @@ -127,7 +127,7 @@ func WithSHA256CodeHash(wasmCode []byte) func(info *CodeInfo) { func MsgStoreCodeFixture(mutators ...func(*MsgStoreCode)) *MsgStoreCode { var wasmIdent = []byte("\x00\x61\x73\x6D") - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" r := &MsgStoreCode{ Sender: anyAddress, WASMByteCode: wasmIdent, @@ -140,7 +140,7 @@ func MsgStoreCodeFixture(mutators ...func(*MsgStoreCode)) *MsgStoreCode { } func MsgInstantiateContractFixture(mutators ...func(*MsgInstantiateContract)) *MsgInstantiateContract { - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" r := &MsgInstantiateContract{ Sender: anyAddress, Admin: anyAddress, @@ -160,7 +160,7 @@ func MsgInstantiateContractFixture(mutators ...func(*MsgInstantiateContract)) *M func MsgExecuteContractFixture(mutators ...func(*MsgExecuteContract)) *MsgExecuteContract { const ( - anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" firstContractAddress = "link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt" ) r := &MsgExecuteContract{ @@ -179,7 +179,7 @@ func MsgExecuteContractFixture(mutators ...func(*MsgExecuteContract)) *MsgExecut } func StoreCodeProposalFixture(mutators ...func(*StoreCodeProposal)) *StoreCodeProposal { - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" p := &StoreCodeProposal{ Title: "Foo", Description: "Bar", @@ -194,7 +194,7 @@ func StoreCodeProposalFixture(mutators ...func(*StoreCodeProposal)) *StoreCodePr func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractProposal)) *InstantiateContractProposal { var ( - anyValidAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, sdk.BytesAddrLen)) + anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) initMsg = struct { Verifier sdk.AccAddress `json:"verifier"` @@ -204,7 +204,7 @@ func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractP Beneficiary: anyValidAddress, } ) - const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + const anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" initMsgBz, err := json.Marshal(initMsg) if err != nil { @@ -229,7 +229,7 @@ func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractP func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal)) *MigrateContractProposal { var ( - anyValidAddress = sdk.BytesToAccAddress(bytes.Repeat([]byte{0x1}, sdk.BytesAddrLen)) + anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) migMsg = struct { Verifier sdk.AccAddress `json:"verifier"` @@ -242,7 +242,7 @@ func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal) } const ( contractAddr = "link1hcttwju93d5m39467gjcq63p5kc4fdcn30dgd8" - anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" ) p := &MigrateContractProposal{ Title: "Foo", @@ -279,7 +279,7 @@ func SudoContractProposalFixture(mutators ...func(p *SudoContractProposal)) *Sud func ExecuteContractProposalFixture(mutators ...func(p *ExecuteContractProposal)) *ExecuteContractProposal { const ( contractAddr = "link1hcttwju93d5m39467gjcq63p5kc4fdcn30dgd8" - anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" ) p := &ExecuteContractProposal{ @@ -303,7 +303,7 @@ func ExecuteContractProposalFixture(mutators ...func(p *ExecuteContractProposal) func UpdateAdminProposalFixture(mutators ...func(p *UpdateAdminProposal)) *UpdateAdminProposal { const ( contractAddr = "link1hcttwju93d5m39467gjcq63p5kc4fdcn30dgd8" - anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgp8apuk5" + anyAddress = "link1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsh9tp23" ) p := &UpdateAdminProposal{ diff --git a/x/wasm/types/tx.go b/x/wasm/types/tx.go index 87c2feb9e2..1dd3094334 100644 --- a/x/wasm/types/tx.go +++ b/x/wasm/types/tx.go @@ -50,7 +50,7 @@ func (msg MsgStoreCode) Type() string { } func (msg MsgStoreCode) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { return err } @@ -68,11 +68,13 @@ func (msg MsgStoreCode) ValidateBasic() error { func (msg MsgStoreCode) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) - } func (msg MsgStoreCode) GetSigners() []sdk.AccAddress { - senderAddr := sdk.AccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { // should never happen as valid basic rejects invalid addresses + panic(err.Error()) + } return []sdk.AccAddress{senderAddr} } @@ -85,7 +87,7 @@ func (msg MsgInstantiateContract) Type() string { } func (msg MsgInstantiateContract) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } @@ -95,7 +97,6 @@ func (msg MsgInstantiateContract) ValidateBasic() error { if err := validateLabel(msg.Label); err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "label is required") - } if !msg.Funds.IsValid() { @@ -103,7 +104,7 @@ func (msg MsgInstantiateContract) ValidateBasic() error { } if len(msg.Admin) != 0 { - if err := sdk.ValidateAccAddress(msg.Admin); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { return sdkerrors.Wrap(err, "admin") } } @@ -119,7 +120,10 @@ func (msg MsgInstantiateContract) GetSignBytes() []byte { } func (msg MsgInstantiateContract) GetSigners() []sdk.AccAddress { - senderAddr := sdk.AccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { // should never happen as valid basic rejects invalid addresses + panic(err.Error()) + } return []sdk.AccAddress{senderAddr} } @@ -132,7 +136,7 @@ func (msg MsgStoreCodeAndInstantiateContract) Type() string { } func (msg MsgStoreCodeAndInstantiateContract) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { return err } @@ -146,10 +150,6 @@ func (msg MsgStoreCodeAndInstantiateContract) ValidateBasic() error { } } - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { - return sdkerrors.Wrap(err, "sender") - } - if err := validateLabel(msg.Label); err != nil { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "label is required") } @@ -159,7 +159,7 @@ func (msg MsgStoreCodeAndInstantiateContract) ValidateBasic() error { } if len(msg.Admin) != 0 { - if err := sdk.ValidateAccAddress(msg.Admin); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { return sdkerrors.Wrap(err, "admin") } } @@ -175,7 +175,10 @@ func (msg MsgStoreCodeAndInstantiateContract) GetSignBytes() []byte { } func (msg MsgStoreCodeAndInstantiateContract) GetSigners() []sdk.AccAddress { - senderAddr := sdk.AccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { // should never happen as valid basic rejects invalid addresses + panic(err.Error()) + } return []sdk.AccAddress{senderAddr} } @@ -188,10 +191,10 @@ func (msg MsgExecuteContract) Type() string { } func (msg MsgExecuteContract) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if err := sdk.ValidateAccAddress(msg.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } @@ -206,11 +209,13 @@ func (msg MsgExecuteContract) ValidateBasic() error { func (msg MsgExecuteContract) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) - } func (msg MsgExecuteContract) GetSigners() []sdk.AccAddress { - senderAddr := sdk.AccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { // should never happen as valid basic rejects invalid addresses + panic(err.Error()) + } return []sdk.AccAddress{senderAddr} } @@ -226,12 +231,13 @@ func (msg MsgMigrateContract) ValidateBasic() error { if msg.CodeID == 0 { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") } - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if err := sdk.ValidateAccAddress(msg.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } + if err := msg.Msg.ValidateBasic(); err != nil { return sdkerrors.Wrap(err, "payload msg") } @@ -241,13 +247,14 @@ func (msg MsgMigrateContract) ValidateBasic() error { func (msg MsgMigrateContract) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) - } func (msg MsgMigrateContract) GetSigners() []sdk.AccAddress { - senderAddr := sdk.AccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { // should never happen as valid basic rejects invalid addresses + panic(err.Error()) + } return []sdk.AccAddress{senderAddr} - } func (msg MsgUpdateAdmin) Route() string { @@ -259,13 +266,13 @@ func (msg MsgUpdateAdmin) Type() string { } func (msg MsgUpdateAdmin) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if err := sdk.ValidateAccAddress(msg.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } - if err := sdk.ValidateAccAddress(msg.NewAdmin); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.NewAdmin); err != nil { return sdkerrors.Wrap(err, "new admin") } if strings.EqualFold(msg.Sender, msg.NewAdmin) { @@ -276,11 +283,13 @@ func (msg MsgUpdateAdmin) ValidateBasic() error { func (msg MsgUpdateAdmin) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) - } func (msg MsgUpdateAdmin) GetSigners() []sdk.AccAddress { - senderAddr := sdk.AccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { // should never happen as valid basic rejects invalid addresses + panic(err.Error()) + } return []sdk.AccAddress{senderAddr} } @@ -293,10 +302,10 @@ func (msg MsgClearAdmin) Type() string { } func (msg MsgClearAdmin) ValidateBasic() error { - if err := sdk.ValidateAccAddress(msg.Sender); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { return sdkerrors.Wrap(err, "sender") } - if err := sdk.ValidateAccAddress(msg.Contract); err != nil { + if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { return sdkerrors.Wrap(err, "contract") } return nil @@ -304,11 +313,13 @@ func (msg MsgClearAdmin) ValidateBasic() error { func (msg MsgClearAdmin) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) - } func (msg MsgClearAdmin) GetSigners() []sdk.AccAddress { - senderAddr := sdk.AccAddress(msg.Sender) + senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { // should never happen as valid basic rejects invalid addresses + panic(err.Error()) + } return []sdk.AccAddress{senderAddr} } diff --git a/x/wasm/types/tx_test.go b/x/wasm/types/tx_test.go index ddae7c67fe..f1e2a944e0 100644 --- a/x/wasm/types/tx_test.go +++ b/x/wasm/types/tx_test.go @@ -19,7 +19,8 @@ func TestStoreCodeValidation(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.BytesToAccAddress(make([]byte, ContractAddrLen)).String() + goodAddress := sdk.AccAddress(make([]byte, ContractAddrLen)).String() + sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) cases := map[string]struct { msg MsgStoreCode valid bool @@ -46,7 +47,7 @@ func TestStoreCodeValidation(t *testing.T) { Sender: badAddress, WASMByteCode: []byte("foo"), }, - valid: true, + valid: false, }, "correct maximal": { msg: MsgStoreCode{ @@ -61,7 +62,7 @@ func TestStoreCodeValidation(t *testing.T) { WASMByteCode: []byte("foo"), InstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: badAddress}, }, - valid: true, + valid: false, }, } @@ -82,7 +83,7 @@ func TestInstantiateContractValidation(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() + goodAddress := sdk.AccAddress(make([]byte, 20)).String() cases := map[string]struct { msg MsgInstantiateContract @@ -130,7 +131,7 @@ func TestInstantiateContractValidation(t *testing.T) { Label: "foo", Msg: []byte("{}"), }, - valid: true, + valid: false, }, "correct maximal": { msg: MsgInstantiateContract{ @@ -190,7 +191,7 @@ func TestStoreCodeAndInstantiateContractValidation(t *testing.T) { badAddress := bad.String() require.NoError(t, err) // proper address size - goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() + goodAddress := sdk.AccAddress(make([]byte, ContractAddrLen)).String() cases := map[string]struct { msg MsgStoreCodeAndInstantiateContract @@ -252,7 +253,7 @@ func TestStoreCodeAndInstantiateContractValidation(t *testing.T) { Msg: []byte(`{"some": "data"}`), Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, }, - valid: true, + valid: false, }, "negative funds": { msg: MsgStoreCodeAndInstantiateContract{ @@ -280,7 +281,7 @@ func TestStoreCodeAndInstantiateContractValidation(t *testing.T) { Label: "foo", Msg: []byte("{}"), }, - valid: true, + valid: false, }, } @@ -301,7 +302,7 @@ func TestExecuteContractValidation(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() + goodAddress := sdk.AccAddress(make([]byte, 20)).String() cases := map[string]struct { msg MsgExecuteContract @@ -334,7 +335,7 @@ func TestExecuteContractValidation(t *testing.T) { Contract: goodAddress, Msg: []byte(`{"some": "data"}`), }, - valid: true, + valid: false, }, "empty sender": { msg: MsgExecuteContract{ @@ -349,7 +350,7 @@ func TestExecuteContractValidation(t *testing.T) { Contract: badAddress, Msg: []byte(`{"some": "data"}`), }, - valid: true, + valid: false, }, "empty contract": { msg: MsgExecuteContract{ @@ -410,9 +411,9 @@ func TestMsgUpdateAdministrator(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - 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() + 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() specs := map[string]struct { src MsgUpdateAdmin @@ -438,6 +439,7 @@ func TestMsgUpdateAdministrator(t *testing.T) { NewAdmin: otherGoodAddress, Contract: anotherGoodAddress, }, + expErr: true, }, "bad new admin": { src: MsgUpdateAdmin{ @@ -445,6 +447,7 @@ func TestMsgUpdateAdministrator(t *testing.T) { NewAdmin: badAddress, Contract: anotherGoodAddress, }, + expErr: true, }, "bad contract addr": { src: MsgUpdateAdmin{ @@ -452,6 +455,7 @@ func TestMsgUpdateAdministrator(t *testing.T) { NewAdmin: otherGoodAddress, Contract: badAddress, }, + expErr: true, }, "new admin same as old admin": { src: MsgUpdateAdmin{ @@ -479,8 +483,8 @@ func TestMsgClearAdministrator(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, 20)).String() + goodAddress := sdk.AccAddress(make([]byte, 20)).String() + anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() specs := map[string]struct { src MsgClearAdmin @@ -497,12 +501,14 @@ func TestMsgClearAdministrator(t *testing.T) { Sender: badAddress, Contract: anotherGoodAddress, }, + expErr: true, }, "bad contract addr": { src: MsgClearAdmin{ Sender: goodAddress, Contract: badAddress, }, + expErr: true, }, "contract missing": { src: MsgClearAdmin{ @@ -528,8 +534,8 @@ func TestMsgMigrateContract(t *testing.T) { require.NoError(t, err) badAddress := bad.String() // proper address size - goodAddress := sdk.BytesToAccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.BytesToAccAddress(bytes.Repeat([]byte{0x2}, 20)).String() + goodAddress := sdk.AccAddress(make([]byte, 20)).String() + anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() specs := map[string]struct { src MsgMigrateContract diff --git a/x/wasm/types/types.go b/x/wasm/types/types.go index 3668806686..53703df790 100644 --- a/x/wasm/types/types.go +++ b/x/wasm/types/types.go @@ -74,7 +74,7 @@ func (c CodeInfo) ValidateBasic() error { if len(c.CodeHash) == 0 { return sdkerrors.Wrap(ErrEmpty, "code hash") } - if err := sdk.ValidateAccAddress(c.Creator); err != nil { + if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { return sdkerrors.Wrap(err, "creator") } if err := c.InstantiateConfig.ValidateBasic(); err != nil { @@ -122,11 +122,11 @@ func (c *ContractInfo) ValidateBasic() error { if c.CodeID == 0 { return sdkerrors.Wrap(ErrEmpty, "code id") } - if err := sdk.ValidateAccAddress(c.Creator); err != nil { + if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { return sdkerrors.Wrap(err, "creator") } if len(c.Admin) != 0 { - if err := sdk.ValidateAccAddress(c.Admin); err != nil { + if _, err := sdk.AccAddressFromBech32(c.Admin); err != nil { return sdkerrors.Wrap(err, "admin") } } @@ -235,9 +235,12 @@ 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 "" + return nil + } + admin, err := sdk.AccAddressFromBech32(c.Admin) + if err != nil { // should never happen + panic(err.Error()) } - admin := sdk.AccAddress(c.Admin) return admin } diff --git a/x/wasm/types/types_test.go b/x/wasm/types/types_test.go index 267884704d..94adc18a4b 100644 --- a/x/wasm/types/types_test.go +++ b/x/wasm/types/types_test.go @@ -173,9 +173,9 @@ func TestContractInfoSetExtension(t *testing.T) { } func TestContractInfoMarshalUnmarshal(t *testing.T) { - var myAddr = sdk.BytesToAccAddress(rand.Bytes(ContractAddrLen)) - var myOtherAddr = sdk.BytesToAccAddress(rand.Bytes(ContractAddrLen)) - var anyPos = AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} + var myAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) + var myOtherAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) + anyPos := AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} anyTime := time.Now().UTC() // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking @@ -294,7 +294,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.BytesToAccAddress(randBytes(ContractAddrLen)) + var myContractAddr sdk.AccAddress = randBytes(ContractAddrLen) specs := map[string]struct { srcCtx sdk.Context exp wasmvmtypes.Env