diff --git a/PENDING.md b/PENDING.md index 14747be9d62e..832f25e8f42d 100644 --- a/PENDING.md +++ b/PENDING.md @@ -14,12 +14,18 @@ BREAKING CHANGES * [cli] \#2014 `gaiacli advanced` no longer exists - to access `ibc`, `rest-server`, and `validator-set` commands use `gaiacli ibc`, `gaiacli rest-server`, and `gaiacli tendermint`, respectively * [makefile] `get_vendor_deps` no longer updates lock file it just updates vendor directory. Use `update_vendor_deps` to update the lock file. [#2152](https://github.com/cosmos/cosmos-sdk/pull/2152) * [cli] \#2190 `gaiacli init --gen-txs` is now `gaiacli init --with-txs` to reduce confusion + * \#2040 All commands that utilize a validator's address must now use the new + bech32 prefix, `cosmosval`. A validator's Tendermint signing key and address + now use a new bech32 prefix, `cosmoscons`. * Gaia * Make the transient store key use a distinct store key. [#2013](https://github.com/cosmos/cosmos-sdk/pull/2013) * [x/stake] \#1901 Validator type's Owner field renamed to Operator; Validator's GetOwner() renamed accordingly to comply with the SDK's Validator interface. * [docs] [#2001](https://github.com/cosmos/cosmos-sdk/pull/2001) Update slashing spec for slashing period * [x/stake, x/slashing] [#1305](https://github.com/cosmos/cosmos-sdk/issues/1305) - Rename "revoked" to "jailed" + * [x/stake] \#2040 Validator operator type has now changed to `sdk.ValAddress` + * A new bech32 prefix has been introduced for Tendermint signing keys and + addresses, `cosmosconspub` and `cosmoscons` respectively. * SDK * [core] \#1807 Switch from use of rational to decimal @@ -38,6 +44,8 @@ FEATURES * Gaia CLI (`gaiacli`) * [cli] Cmds to query staking pool and params * [gov][cli] #2062 added `--proposal` flag to `submit-proposal` that allows a JSON file containing a proposal to be passed in + * \#2040 Add `--bech` to `gaiacli keys show` and respective REST endpoint to + provide desired Bech32 prefix encoding * [cli] \#2047 Setting the --gas flag value to 0 triggers a simulation of the tx before the actual execution. The gas estimate obtained via the simulation will be used as gas limit in the actual execution. * [cli] \#2047 The --gas-adjustment flag can be used to adjust the estimate obtained via the simulation triggered by --gas=0. diff --git a/client/keys/add.go b/client/keys/add.go index d462db1c0697..c4217281968e 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -128,7 +128,8 @@ func printCreate(info keys.Info, seed string) { output := viper.Get(cli.OutputFlag) switch output { case "text": - printInfo(info) + printKeyInfo(info, Bech32KeyOutput) + // print seed unless requested not to. if !viper.GetBool(client.FlagUseLedger) && !viper.GetBool(flagNoBackup) { fmt.Println("**Important** write this seed phrase in a safe place.") diff --git a/client/keys/root.go b/client/keys/root.go index c8f6aea693af..f2a27dc0c865 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -21,7 +21,7 @@ func Commands() *cobra.Command { cmd.AddCommand( addKeyCommand(), listKeysCmd, - showKeysCmd, + showKeysCmd(), client.LineBreak, deleteKeyCommand(), updateKeyCommand(), diff --git a/client/keys/show.go b/client/keys/show.go index e9d692ece579..9710cac11e72 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -2,6 +2,7 @@ package keys import ( "encoding/json" + "fmt" "net/http" "github.com/cosmos/cosmos-sdk/crypto/keys" @@ -18,46 +19,69 @@ const ( FlagAddress = "address" // FlagPublicKey represents the user's public key on the command line. FlagPublicKey = "pubkey" + // FlagBechPrefix defines a desired Bech32 prefix encoding for a key + FlagBechPrefix = "bech" ) -var showKeysCmd = &cobra.Command{ - Use: "show ", - Short: "Show key info for the given name", - Long: `Return public details of one local key.`, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - name := args[0] - info, err := getKey(name) - if err != nil { - return err - } - - showAddress := viper.GetBool(FlagAddress) - showPublicKey := viper.GetBool(FlagPublicKey) - outputSet := cmd.Flag(cli.OutputFlag).Changed - if showAddress && showPublicKey { - return errors.New("cannot use both --address and --pubkey at once") - } - if outputSet && (showAddress || showPublicKey) { - return errors.New("cannot use --output with --address or --pubkey") - } - if showAddress { - printKeyAddress(info) - return nil - } - if showPublicKey { - printPubKey(info) +func showKeysCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "show [name]", + Short: "Show key info for the given name", + Long: `Return public details of one local key.`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + info, err := getKey(name) + if err != nil { + return err + } + + showAddress := viper.GetBool(FlagAddress) + showPublicKey := viper.GetBool(FlagPublicKey) + outputSet := cmd.Flag(cli.OutputFlag).Changed + + if showAddress && showPublicKey { + return errors.New("cannot use both --address and --pubkey at once") + } + if outputSet && (showAddress || showPublicKey) { + return errors.New("cannot use --output with --address or --pubkey") + } + + bechKeyOut, err := getBechKeyOut(viper.GetString(FlagBechPrefix)) + if err != nil { + return err + } + + switch { + case showAddress: + printKeyAddress(info, bechKeyOut) + case showPublicKey: + printPubKey(info, bechKeyOut) + default: + printKeyInfo(info, bechKeyOut) + } return nil - } + }, + } + + cmd.Flags().String(FlagBechPrefix, "acc", "The Bech32 prefix encoding for a key (acc|val|cons)") + cmd.Flags().Bool(FlagAddress, false, "output the address only (overrides --output)") + cmd.Flags().Bool(FlagPublicKey, false, "output the public key only (overrides --output)") - printInfo(info) - return nil - }, + return cmd } -func init() { - showKeysCmd.Flags().Bool(FlagAddress, false, "output the address only (overrides --output)") - showKeysCmd.Flags().Bool(FlagPublicKey, false, "output the public key only (overrides --output)") +func getBechKeyOut(bechPrefix string) (bechKeyOutFn, error) { + switch bechPrefix { + case "acc": + return Bech32KeyOutput, nil + case "val": + return Bech32ValKeyOutput, nil + case "cons": + return Bech32ConsKeyOutput, nil + } + + return nil, fmt.Errorf("invalid Bech32 prefix encoding provided: %s", bechPrefix) } func getKey(name string) (keys.Info, error) { @@ -76,21 +100,35 @@ func getKey(name string) (keys.Info, error) { func GetKeyRequestHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] + bechPrefix := r.URL.Query().Get(FlagBechPrefix) + + if bechPrefix == "" { + bechPrefix = "acc" + } + + bechKeyOut, err := getBechKeyOut(bechPrefix) + if err != nil { + w.WriteHeader(400) + w.Write([]byte(err.Error())) + return + } info, err := getKey(name) - // TODO check for the error if key actually does not exist, instead of assuming this as the reason + // TODO: check for the error if key actually does not exist, instead of + // assuming this as the reason if err != nil { w.WriteHeader(404) w.Write([]byte(err.Error())) return } - keyOutput, err := Bech32KeyOutput(info) + keyOutput, err := bechKeyOut(info) if err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) return } + output, err := json.MarshalIndent(keyOutput, "", " ") if err != nil { w.WriteHeader(500) diff --git a/client/keys/utils.go b/client/keys/utils.go index aa1b4bed9c07..95fc83ed65a5 100644 --- a/client/keys/utils.go +++ b/client/keys/utils.go @@ -21,6 +21,8 @@ const KeyDBName = "keys" // keybase is used to make GetKeyBase a singleton var keybase keys.Keybase +type bechKeyOutFn func(keyInfo keys.Info) (KeyOutput, error) + // TODO make keybase take a database not load from the directory // initialize a keybase based on the configuration @@ -97,11 +99,11 @@ func SetKeyBase(kb keys.Keybase) { // used for outputting keys.Info over REST type KeyOutput struct { - Name string `json:"name"` - Type string `json:"type"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` - Seed string `json:"seed,omitempty"` + Name string `json:"name"` + Type string `json:"type"` + Address string `json:"address"` + PubKey string `json:"pub_key"` + Seed string `json:"seed,omitempty"` } // create a list of KeyOutput in bech32 format @@ -119,24 +121,61 @@ func Bech32KeysOutput(infos []keys.Info) ([]KeyOutput, error) { // create a KeyOutput in bech32 format func Bech32KeyOutput(info keys.Info) (KeyOutput, error) { - account := sdk.AccAddress(info.GetPubKey().Address().Bytes()) + accAddr := sdk.AccAddress(info.GetPubKey().Address().Bytes()) bechPubKey, err := sdk.Bech32ifyAccPub(info.GetPubKey()) if err != nil { return KeyOutput{}, err } + return KeyOutput{ Name: info.GetName(), Type: info.GetType().String(), - Address: account, + Address: accAddr.String(), + PubKey: bechPubKey, + }, nil +} + +// Bech32ConsKeyOutput returns key output for a consensus node's key +// information. +func Bech32ConsKeyOutput(keyInfo keys.Info) (KeyOutput, error) { + consAddr := sdk.ConsAddress(keyInfo.GetPubKey().Address().Bytes()) + + bechPubKey, err := sdk.Bech32ifyConsPub(keyInfo.GetPubKey()) + if err != nil { + return KeyOutput{}, err + } + + return KeyOutput{ + Name: keyInfo.GetName(), + Type: keyInfo.GetType().String(), + Address: consAddr.String(), + PubKey: bechPubKey, + }, nil +} + +// Bech32ValKeyOutput returns key output for a validator's key information. +func Bech32ValKeyOutput(keyInfo keys.Info) (KeyOutput, error) { + valAddr := sdk.ValAddress(keyInfo.GetPubKey().Address().Bytes()) + + bechPubKey, err := sdk.Bech32ifyValPub(keyInfo.GetPubKey()) + if err != nil { + return KeyOutput{}, err + } + + return KeyOutput{ + Name: keyInfo.GetName(), + Type: keyInfo.GetType().String(), + Address: valAddr.String(), PubKey: bechPubKey, }, nil } -func printInfo(info keys.Info) { - ko, err := Bech32KeyOutput(info) +func printKeyInfo(keyInfo keys.Info, bechKeyOut bechKeyOutFn) { + ko, err := bechKeyOut(keyInfo) if err != nil { panic(err) } + switch viper.Get(cli.OutputFlag) { case "text": fmt.Printf("NAME:\tTYPE:\tADDRESS:\t\t\t\t\t\tPUBKEY:\n") @@ -146,6 +185,7 @@ func printInfo(info keys.Info) { if err != nil { panic(err) } + fmt.Println(string(out)) } } @@ -174,18 +214,20 @@ func printKeyOutput(ko KeyOutput) { fmt.Printf("%s\t%s\t%s\t%s\n", ko.Name, ko.Type, ko.Address, ko.PubKey) } -func printKeyAddress(info keys.Info) { - ko, err := Bech32KeyOutput(info) +func printKeyAddress(info keys.Info, bechKeyOut bechKeyOutFn) { + ko, err := bechKeyOut(info) if err != nil { panic(err) } - fmt.Println(ko.Address.String()) + + fmt.Println(ko.Address) } -func printPubKey(info keys.Info) { - ko, err := Bech32KeyOutput(info) +func printPubKey(info keys.Info, bechKeyOut bechKeyOutFn) { + ko, err := bechKeyOut(info) if err != nil { panic(err) } + fmt.Println(ko.PubKey) } diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 298cf0027e47..d68ba278c13f 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -62,7 +62,7 @@ func TestKeys(t *testing.T) { err = wire.Cdc.UnmarshalJSON([]byte(body), &resp) require.Nil(t, err, body) - addr2Bech32 := resp.Address.String() + addr2Bech32 := resp.Address _, err = sdk.AccAddressFromBech32(addr2Bech32) require.NoError(t, err, "Failed to return a correct bech32 address") @@ -81,9 +81,9 @@ func TestKeys(t *testing.T) { addrBech32 := addr.String() require.Equal(t, name, m[0].Name, "Did not serve keys name correctly") - require.Equal(t, addrBech32, m[0].Address.String(), "Did not serve keys Address correctly") + require.Equal(t, addrBech32, m[0].Address, "Did not serve keys Address correctly") require.Equal(t, newName, m[1].Name, "Did not serve keys name correctly") - require.Equal(t, addr2Bech32, m[1].Address.String(), "Did not serve keys Address correctly") + require.Equal(t, addr2Bech32, m[1].Address, "Did not serve keys Address correctly") // select key keyEndpoint := fmt.Sprintf("/keys/%s", newName) @@ -94,7 +94,7 @@ func TestKeys(t *testing.T) { require.Nil(t, err) require.Equal(t, newName, m2.Name, "Did not serve keys name correctly") - require.Equal(t, addr2Bech32, m2.Address.String(), "Did not serve keys Address correctly") + require.Equal(t, addr2Bech32, m2.Address, "Did not serve keys Address correctly") // update key jsonStr = []byte(fmt.Sprintf(`{ @@ -204,8 +204,8 @@ func TestValidators(t *testing.T) { require.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals) - require.Contains(t, resultVals.Validators[0].Address.String(), "cosmosvaladdr") - require.Contains(t, resultVals.Validators[0].PubKey, "cosmosvalpub") + require.Contains(t, resultVals.Validators[0].Address.String(), "cosmosval") + require.Contains(t, resultVals.Validators[0].PubKey, "cosmosconspub") // -- @@ -313,7 +313,7 @@ func TestTxs(t *testing.T) { require.Equal(t, http.StatusBadRequest, res.StatusCode, body) // query empty - res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=sender_bech32='%s'", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) + res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=sender_bech32='%s'", "cosmos1jawd35d9aq4u76sr3fjalmcqc8hqygs90d0g0v"), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) require.Equal(t, "[]", body) @@ -407,7 +407,7 @@ func TestValidatorsQuery(t *testing.T) { // make sure all the validators were found (order unknown because sorted by operator addr) foundVal := false - pkBech := sdk.MustBech32ifyValPub(pks[0]) + pkBech := sdk.MustBech32ifyConsPub(pks[0]) if validators[0].PubKey == pkBech { foundVal = true } @@ -419,7 +419,7 @@ func TestValidatorQuery(t *testing.T) { defer cleanup() require.Equal(t, 1, len(pks)) - validator1Operator := sdk.AccAddress(pks[0].Address()) + validator1Operator := sdk.ValAddress(pks[0].Address()) validator := getValidator(t, port, validator1Operator) assert.Equal(t, validator.Operator, validator1Operator, "The returned validator does not hold the correct data") } @@ -430,7 +430,7 @@ func TestBonding(t *testing.T) { cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() - validator1Operator := sdk.AccAddress(pks[0].Address()) + validator1Operator := sdk.ValAddress(pks[0].Address()) validator := getValidator(t, port, validator1Operator) // create bond TX @@ -611,7 +611,7 @@ func TestUnjail(t *testing.T) { // XXX: any less than this and it fails tests.WaitForHeight(3, port) - pkString, _ := sdk.Bech32ifyValPub(pks[0]) + pkString, _ := sdk.Bech32ifyConsPub(pks[0]) signingInfo := getSigningInfo(t, port, pkString) tests.WaitForHeight(4, port) require.Equal(t, true, signingInfo.IndexOffset > 0) @@ -817,8 +817,8 @@ func getSigningInfo(t *testing.T, port string, validatorPubKey string) slashing. // ============= Stake Module ================ -func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) rest.DelegationWithoutRat { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) +func getDelegation(t *testing.T, port string, delAddr sdk.AccAddress, valAddr sdk.ValAddress) rest.DelegationWithoutRat { + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delAddr, valAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var bond rest.DelegationWithoutRat @@ -829,8 +829,8 @@ func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.A return bond } -func getUndelegations(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) []stake.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) +func getUndelegations(t *testing.T, port string, delAddr sdk.AccAddress, valAddr sdk.ValAddress) []stake.UnbondingDelegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delAddr, valAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var unbondings []stake.UnbondingDelegation @@ -884,8 +884,8 @@ func getDelegatorValidators(t *testing.T, port string, delegatorAddr sdk.AccAddr return bondedValidators } -func getDelegatorValidator(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) stake.BechValidator { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/validators/%s", delegatorAddr, validatorAddr), nil) +func getDelegatorValidator(t *testing.T, port string, delAddr sdk.AccAddress, valAddr sdk.ValAddress) stake.BechValidator { + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/validators/%s", delAddr, valAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var bondedValidator stake.BechValidator @@ -895,8 +895,10 @@ func getDelegatorValidator(t *testing.T, port string, delegatorAddr sdk.AccAddre return bondedValidator } -func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress, amount int64) (resultTx ctypes.ResultBroadcastTxCommit) { - acc := getAccount(t, port, delegatorAddr) +func doDelegate(t *testing.T, port, seed, name, password string, + delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount int64) (resultTx ctypes.ResultBroadcastTxCommit) { + + acc := getAccount(t, port, delAddr) accnum := acc.GetAccountNumber() sequence := acc.GetSequence() chainID := viper.GetString(client.FlagChainID) @@ -918,9 +920,9 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, "complete_unbondings": [], "begin_redelegates": [], "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak", amount)) + }`, name, password, accnum, sequence, chainID, delAddr, valAddr, "steak", amount)) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -931,9 +933,9 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, } func doBeginUnbonding(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorAddr sdk.AccAddress, amount int64) (resultTx ctypes.ResultBroadcastTxCommit) { + delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount int64) (resultTx ctypes.ResultBroadcastTxCommit) { - acc := getAccount(t, port, delegatorAddr) + acc := getAccount(t, port, delAddr) accnum := acc.GetAccountNumber() sequence := acc.GetSequence() chainID := viper.GetString(client.FlagChainID) @@ -955,9 +957,9 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, "complete_unbondings": [], "begin_redelegates": [], "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, amount)) + }`, name, password, accnum, sequence, chainID, delAddr, valAddr, amount)) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -968,9 +970,9 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, } func doBeginRedelegation(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { - acc := getAccount(t, port, delegatorAddr) + acc := getAccount(t, port, delAddr) accnum := acc.GetAccountNumber() sequence := acc.GetSequence() @@ -994,9 +996,9 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string, } ], "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr)) + }`, name, password, accnum, sequence, chainID, delAddr, valSrcAddr, valDstAddr)) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -1015,8 +1017,8 @@ func getValidators(t *testing.T, port string) []stake.BechValidator { return validators } -func getValidator(t *testing.T, port string, validatorAddr sdk.AccAddress) stake.BechValidator { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s", validatorAddr.String()), nil) +func getValidator(t *testing.T, port string, valAddr sdk.ValAddress) stake.BechValidator { + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s", valAddr.String()), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var validator stake.BechValidator err := cdc.UnmarshalJSON([]byte(body), &validator) diff --git a/client/rpc/validators.go b/client/rpc/validators.go index d2daa4ec5cab..cb002d3ea046 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -45,7 +45,7 @@ type ResultValidatorsOutput struct { } func bech32ValidatorOutput(validator *tmtypes.Validator) (ValidatorOutput, error) { - bechValPubkey, err := sdk.Bech32ifyValPub(validator.PubKey) + bechValPubkey, err := sdk.Bech32ifyConsPub(validator.PubKey) if err != nil { return ValidatorOutput{}, err } diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 0fbbc0603171..bfcaa92dde8a 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -142,7 +142,7 @@ func GaiaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name gaiaGenTx := GaiaGenTx{ Name: name, Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), + PubKey: sdk.MustBech32ifyConsPub(pk), } bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) if err != nil { @@ -192,8 +192,9 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // add the validator if len(genTx.Name) > 0 { desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, - sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) + validator := stake.NewValidator( + sdk.ValAddress(genTx.Address), sdk.MustGetConsPubKeyBech32(genTx.PubKey), desc, + ) stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewDec(freeFermionVal)) // increase the supply @@ -204,7 +205,7 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // create the self-delegation from the issuedDelShares delegation := stake.Delegation{ - DelegatorAddr: validator.Operator, + DelegatorAddr: sdk.AccAddress(validator.Operator), ValidatorAddr: validator.Operator, Shares: issuedDelShares, Height: 0, diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 0ca936bdbfc8..559b8b4b9a41 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -57,10 +57,10 @@ func appStateFn(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json // XXX Try different numbers of initially bonded validators numInitiallyBonded := int64(50) for i := 0; i < int(numInitiallyBonded); i++ { - validator := stake.NewValidator(accs[i], keys[i].PubKey(), stake.Description{}) + validator := stake.NewValidator(sdk.ValAddress(accs[i]), keys[i].PubKey(), stake.Description{}) validator.Tokens = sdk.NewDec(100) validator.DelegatorShares = sdk.NewDec(100) - delegation := stake.Delegation{accs[i], accs[i], sdk.NewDec(100), 0} + delegation := stake.Delegation{accs[i], sdk.ValAddress(accs[i]), sdk.NewDec(100), 0} validators = append(validators, validator) delegations = append(delegations, delegation) } diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index f794e5140df7..b91b5a45d632 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -124,7 +124,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome)) barAddr, barPubKey := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) - barCeshPubKey := sdk.MustBech32ifyValPub(barPubKey) + barCeshPubKey := sdk.MustBech32ifyConsPub(barPubKey) executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), app.DefaultKeyPass) tests.WaitForNextNBlocksTM(2, port) @@ -154,14 +154,14 @@ func TestGaiaCLICreateValidator(t *testing.T) { barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) require.Equal(t, int64(8), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) - validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags)) - require.Equal(t, validator.Operator, barAddr) + validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", sdk.ValAddress(barAddr), flags)) + require.Equal(t, validator.Operator, sdk.ValAddress(barAddr)) require.True(sdk.DecEq(t, sdk.NewDec(2), validator.Tokens)) // unbond a single share unbondStr := fmt.Sprintf("gaiacli stake unbond begin %v", flags) unbondStr += fmt.Sprintf(" --from=%s", "bar") - unbondStr += fmt.Sprintf(" --validator=%s", barAddr) + unbondStr += fmt.Sprintf(" --validator=%s", sdk.ValAddress(barAddr)) unbondStr += fmt.Sprintf(" --shares-amount=%v", "1") success := executeWrite(t, unbondStr, app.DefaultKeyPass) @@ -172,7 +172,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags)) require.Equal(t, int64(9), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) */ - validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags)) + validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", sdk.ValAddress(barAddr), flags)) require.Equal(t, "1.0000000000", validator.Tokens.String()) params := executeGetParams(t, fmt.Sprintf("gaiacli stake parameters --output=json %v", flags)) @@ -352,7 +352,10 @@ func executeGetAddrPK(t *testing.T, cmdStr string) (sdk.AccAddress, crypto.PubKe pk, err := sdk.GetAccPubKeyBech32(ko.PubKey) require.NoError(t, err) - return ko.Address, pk + accAddr, err := sdk.AccAddressFromBech32(ko.Address) + require.NoError(t, err) + + return accAddr, pk } func executeGetAccount(t *testing.T, cmdStr string) auth.BaseAccount { diff --git a/docs/clients/lcd-rest-api.yaml b/docs/clients/lcd-rest-api.yaml index 5be69302d50e..4f402089ad9c 100644 --- a/docs/clients/lcd-rest-api.yaml +++ b/docs/clients/lcd-rest-api.yaml @@ -710,15 +710,15 @@ definitions: Address: type: string description: bech32 encoded addres - example: cosmosaccaddr:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq + example: cosmos:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq ValidatorAddress: type: string description: bech32 encoded addres - example: cosmosvaladdr:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq + example: cosmosval:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq PubKey: type: string description: bech32 encoded public key - example: cosmosaccpub:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq + example: cosmospub:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq ValidatorPubKey: type: string description: bech32 encoded public key diff --git a/docs/clients/ledger.md b/docs/clients/ledger.md index 5ea1224eaea9..26b0215b3dd1 100644 --- a/docs/clients/ledger.md +++ b/docs/clients/ledger.md @@ -17,7 +17,7 @@ Once you have the Cosmos app installed on your Ledger, and the Ledger is accessi ```bash $ gaiacli keys add {{ .Key.Name }} --ledger NAME: TYPE: ADDRESS: PUBKEY: -{{ .Key.Name }} ledger cosmosaccaddr1aw64xxr80lwqqdk8u2xhlrkxqaxamkr3e2g943 cosmosaccpub1addwnpepqvhs678gh9aqrjc2tg2vezw86csnvgzqq530ujkunt5tkuc7lhjkz5mj629 +{{ .Key.Name }} ledger cosmos1aw64xxr80lwqqdk8u2xhlrkxqaxamkr3e2g943 cosmospub1addwnpepqvhs678gh9aqrjc2tg2vezw86csnvgzqq530ujkunt5tkuc7lhjkz5mj629 ``` This key will only be accessible while the Ledger is plugged in and unlocked. To send some coins with this key, run the following: diff --git a/docs/ics/ics-030-signed-messages.md b/docs/ics/ics-030-signed-messages.md index e73d9f5803ae..8f53238f7e23 100644 --- a/docs/ics/ics-030-signed-messages.md +++ b/docs/ics/ics-030-signed-messages.md @@ -186,7 +186,7 @@ data = { "text": "I hereby claim I am ABC on Keybase!" } -cosmosSignBytes(data, "cosmosaccaddr1pvsch6cddahhrn5e8ekw0us50dpnugwnlfngt3") +cosmosSignBytes(data, "cosmos1pvsch6cddahhrn5e8ekw0us50dpnugwnlfngt3") > "0x7fc4a495473045022100dec81a9820df0102381cdbf7e8b0f1e2cb64c58e0ecda1324543742e0388e41a02200df37905a6505c1b56a404e23b7473d2c0bc5bcda96771d2dda59df6ed2b98f8" ``` diff --git a/docs/light/api.md b/docs/light/api.md index 6c5e8aa5f02a..7168cf9d743d 100644 --- a/docs/light/api.md +++ b/docs/light/api.md @@ -71,13 +71,13 @@ This API exposes all functionality needed for key creation, signing and manageme "account":[ { "name":"monkey", - "address":"cosmosaccaddr1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", - "pub_key":"cosmosaccpub1zcjduc3q8s8ha96ry4xc5xvjp9tr9w9p0e5lk5y0rpjs5epsfxs4wmf72x3shvus0t" + "address":"cosmos1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", + "pub_key":"cosmospub1zcjduc3q8s8ha96ry4xc5xvjp9tr9w9p0e5lk5y0rpjs5epsfxs4wmf72x3shvus0t" }, { "name":"test", - "address":"cosmosaccaddr1thlqhjqw78zvcy0ua4ldj9gnazqzavyw4eske2", - "pub_key":"cosmosaccpub1zcjduc3qyx6hlf825jcnj39adpkaxjer95q7yvy25yhfj3dmqy2ctev0rxmse9cuak" + "address":"cosmos1thlqhjqw78zvcy0ua4ldj9gnazqzavyw4eske2", + "pub_key":"cosmospub1zcjduc3qyx6hlf825jcnj39adpkaxjer95q7yvy25yhfj3dmqy2ctev0rxmse9cuak" } ], "block_height":5241 @@ -125,8 +125,8 @@ Returns on success: "error":"", "result":{ "name":"test", - "address":"cosmosaccaddr1thlqhjqw78zvcy0ua4ldj9gnazqzavyw4eske2", - "pub_key":"cosmosaccpub1zcjduc3qyx6hlf825jcnj39adpkaxjer95q7yvy25yhfj3dmqy2ctev0rxmse9cuak" + "address":"cosmos1thlqhjqw78zvcy0ua4ldj9gnazqzavyw4eske2", + "pub_key":"cosmospub1zcjduc3qyx6hlf825jcnj39adpkaxjer95q7yvy25yhfj3dmqy2ctev0rxmse9cuak" } } ``` @@ -588,7 +588,7 @@ The GovernanceAPI exposes all functionality needed for casting votes on plain te "description": "string", // PlainTextProposal supported now. SoftwareUpgradeProposal and other types may be supported soon "proposal_type": "string", - // A cosmosaccaddr address + // A cosmos address "proposer": "string", "initial_deposit": [ { @@ -689,7 +689,7 @@ The GovernanceAPI exposes all functionality needed for casting votes on plain te "error":"", "result":{ "amount": {"atom": 150}, - "depositer": "cosmosaccaddr1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", + "depositer": "cosmos1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", "proposal-id": 16 } } @@ -731,12 +731,12 @@ The GovernanceAPI exposes all functionality needed for casting votes on plain te "result": [ { "proposal-id": 1, - "voter": "cosmosaccaddr1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", + "voter": "cosmos1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", "option": "no_with_veto" }, { "proposal-id": 1, - "voter": "cosmosaccaddr1849m9wncrqp6v4tkss6a3j8uzvuv0cp7f75lrq", + "voter": "cosmos1849m9wncrqp6v4tkss6a3j8uzvuv0cp7f75lrq", "option": "yes" }, ] @@ -761,7 +761,7 @@ The GovernanceAPI exposes all functionality needed for casting votes on plain te "sequence": 0, "gas": 0 }, - // A cosmosaccaddr address + // A cosmos address "voter": "string", // Value of the vote option `Yes`, `No` `Abstain`, `NoWithVeto` "option": "string", @@ -794,7 +794,7 @@ The GovernanceAPI exposes all functionality needed for casting votes on plain te "error":"", "result":{ "proposal-id": 1, - "voter": "cosmosaccaddr1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", + "voter": "cosmos1fedh326uxqlxs8ph9ej7cf854gz7fd5zlym5pd", "option": "no_with_veto" } } diff --git a/docs/sdk/clients.md b/docs/sdk/clients.md index 0a1c2a38d990..7a23ba28acd1 100644 --- a/docs/sdk/clients.md +++ b/docs/sdk/clients.md @@ -18,17 +18,21 @@ There are three types of key representations that are used: -- `cosmosaccaddr` +- `cosmos` - Derived from account keys generated by `gaiacli keys add` - Used to receive funds - - e.g. `cosmosaccaddr15h6vd5f0wqps26zjlwrc6chah08ryu4hzzdwhc` -- `cosmosaccpub` + - e.g. `cosmos15h6vd5f0wqps26zjlwrc6chah08ryu4hzzdwhc` +* `cosmosval` + * Used to associate a validator to it's operator + * Used to invoke staking commands + * e.g. `cosmosval1carzvgq3e6y3z5kz5y6gxp3wpy3qdrv928vyah` +- `cosmospub` - Derived from account keys generated by `gaiacli keys add` - - e.g. `cosmosaccpub1zcjduc3q7fu03jnlu2xpl75s2nkt7krm6grh4cc5aqth73v0zwmea25wj2hsqhlqzm` -- `cosmosvalpub` + - e.g. `cosmospub1zcjduc3q7fu03jnlu2xpl75s2nkt7krm6grh4cc5aqth73v0zwmea25wj2hsqhlqzm` +- `cosmosconspub` - Generated when the node is created with `gaiad init`. - Get this value with `gaiad tendermint show-validator` - - e.g. `cosmosvalpub1zcjduc3qcyj09qc03elte23zwshdx92jm6ce88fgc90rtqhjx8v0608qh5ssp0w94c` + - e.g. `cosmosconspub1zcjduepq0ms2738680y72v44tfyqm3c9ppduku8fs6sr73fx7m666sjztznqzp2emf` #### Generate Keys @@ -48,6 +52,12 @@ If you check your private keys, you'll now see ``: gaiacli keys show ``` +View the validator operator's address via: + +```shell +gaiacli keys show --bech=val +``` + You can see all your available keys by typing: ```bash @@ -68,18 +78,18 @@ We strongly recommend _NOT_ using the same passphrase for multiple keys. The Ten #### Get Tokens -The best way to get tokens is from the [Cosmos Testnet Faucet](https://faucetcosmos.network). If the faucet is not working for you, try asking [#cosmos-validators](https://riot.im/app/#/room/#cosmos-validators:matrix.org). The faucet needs the `cosmosaccaddr` from the account you wish to use for staking. +The best way to get tokens is from the [Cosmos Testnet Faucet](https://faucetcosmos.network). If the faucet is not working for you, try asking [#cosmos-validators](https://riot.im/app/#/room/#cosmos-validators:matrix.org). The faucet needs the `cosmos` from the account you wish to use for staking. #### Query Account balance After receiving tokens to your address, you can view your account's balance by typing: ```bash -gaiacli account +gaiacli account ``` ::: warning Note -When you query an account balance with zero tokens, you will get this error: `No account with address was found in the state.` This can also happen if you fund the account before your node has fully synced with the chain. These are both normal. +When you query an account balance with zero tokens, you will get this error: `No account with address was found in the state.` This can also happen if you fund the account before your node has fully synced with the chain. These are both normal. ::: @@ -90,7 +100,7 @@ gaiacli send \ --amount=10faucetToken \ --chain-id= \ --name= \ - --to= + --to= ``` ::: warning Note @@ -106,14 +116,14 @@ Gas estimate might be inaccurate as state changes could occur in between the end Now, view the updated balances of the origin and destination accounts: ```bash -gaiacli account -gaiacli account +gaiacli account +gaiacli account ``` You can also check your balance at a given block by using the `--block` flag: ```bash -gaiacli account --block= +gaiacli account --block= ``` ### Staking @@ -137,7 +147,7 @@ gaiacli stake validators If you want to get the information of a single validator you can check it with: ```bash -gaiacli stake validator +gaiacli stake validator ``` #### Bond Tokens @@ -164,14 +174,14 @@ Once submitted a delegation to a validator, you can see it's information by usin ```bash gaiacli stake delegation \ - --address-delegator= \ - --address-validator=$(gaiad tendermint show-validator) + --address-delegator= \ + --validator= ``` Or if you want to check all your current delegations with disctinct validators: ```bash -gaiacli stake delegations +gaiacli stake delegations ``` You can also get previous delegation(s) status by adding the `--height` flag. @@ -182,7 +192,7 @@ If for any reason the validator misbehaves, or you just want to unbond a certain ```bash gaiacli stake unbond begin \ - --address-validator=$(gaiad tendermint show-validator) \ + --validator= \ --shares-percent=100 \ --from= \ --chain-id= @@ -192,7 +202,7 @@ Later you must complete the unbonding process by using the `gaiacli stake unbond ```bash gaiacli stake unbond complete \ - --address-validator=$(gaiad tendermint show-validator) \ + --validator= \ --from= \ --chain-id= ``` @@ -203,14 +213,14 @@ Once you begin an unbonding-delegation, you can see it's information by using th ```bash gaiacli stake unbonding-delegation \ - --address-delegator= \ - --address-validator=$(gaiad tendermint show-validator) \ + --address-delegator= \ + --validator= \ ``` Or if you want to check all your current unbonding-delegations with disctinct validators: ```bash -gaiacli stake unbonding-delegations +gaiacli stake unbonding-delegations ``` You can also get previous unbonding-delegation(s) status by adding the `--height` flag. @@ -221,8 +231,8 @@ A redelegation is a type delegation that allows you to bond illiquid tokens from ```bash gaiacli stake redelegate begin \ - --address-validator-source=$(gaiad tendermint show-validator) \ - --address-validator-dest= \ + --address-validator-source= \ + --address-validator-dest= \ --shares-percent=50 \ --from= \ --chain-id= @@ -234,7 +244,7 @@ Later you must complete the redelegation process by using the `gaiacli stake red ```bash gaiacli stake unbond complete \ - --address-validator=$(gaiad tendermint show-validator) \ + --validator= \ --from= \ --chain-id= ``` @@ -245,15 +255,15 @@ Once you begin an redelegation, you can see it's information by using the follow ```bash gaiacli stake redelegation \ - --address-delegator= \ - --address-validator-source=$(gaiad tendermint show-validator) \ - --address-validator-dest= \ + --address-delegator= \ + --address-validator-source= \ + --address-validator-dest= \ ``` Or if you want to check all your current unbonding-delegations with disctinct validators: ```bash -gaiacli stake redelegations +gaiacli stake redelegations ``` You can also get previous redelegation(s) status by adding the `--height` flag. @@ -286,7 +296,7 @@ gaiacli gov submit-proposal \ --title= \ --description=<description> \ --type=<Text/ParameterChange/SoftwareUpgrade> \ - --proposer=<account_cosmosaccaddr> \ + --proposer=<account_cosmos> \ --deposit=<40steak> \ --from=<name> \ --chain-id=<chain_id> @@ -316,7 +326,7 @@ In order for a proposal to be broadcasted to the network, the amount deposited m ```bash gaiacli gov deposit \ --proposal-id=<proposal_id> \ - --depositer=<account_cosmosaccaddr> \ + --depositer=<account_cosmos> \ --deposit=<200steak> \ --from=<name> \ --chain-id=<chain_id> @@ -331,7 +341,7 @@ After a proposal's deposit reaches the `MinDeposit` value, the voting period ope ```bash gaiacli gov vote \ --proposal-id=<proposal_id> \ - --voter=<account_cosmosaccaddr> \ + --voter=<account_cosmos> \ --option=<Yes/No/NoWithVeto/Abstain> \ --from=<name> \ --chain-id=<chain_id> @@ -344,7 +354,7 @@ Check the vote with the option you just submitted: ```bash gaiacli gov query-vote \ --proposal-id=<proposal_id> \ - --voter=<account_cosmosaccaddr> + --voter=<account_cosmos> ``` #### Query Parameters diff --git a/docs/spec/other/bech32.md b/docs/spec/other/bech32.md index 1558c1ec37a6..911102a8a7eb 100644 --- a/docs/spec/other/bech32.md +++ b/docs/spec/other/bech32.md @@ -1,25 +1,24 @@ # Bech32 on Cosmos -The Cosmos network prefers to use the Bech32 address format whereever users must handle binary data. Bech32 encoding provides robust integrity checks on data and the human readable part(HRP) provides contextual hints that can assist UI developers with providing informative error messages. +The Cosmos network prefers to use the Bech32 address format wherever users must handle binary data. Bech32 encoding provides robust integrity checks on data and the human readable part(HRP) provides contextual hints that can assist UI developers with providing informative error messages. In the Cosmos network, keys and addresses may refer to a number of different roles in the network like accounts, validators etc. +## HRP table -## HRP table - -| HRP | Definition | -| ------------- |:-------------:| -| `cosmos` | Cosmos Account Address | -| `cosmospub` | Cosmos Account Public Key | -| `cosmosval` | Cosmos Validator Consensus Address | -| `cosmosvalpub`| Cosmos Validator Consensus Public Key| +| HRP | Definition | +|---------------|--------------------------------------| +| cosmos | Cosmos Account Address | +| cosmospub | Cosmos Account Public Key | +| cosmoscons | Cosmos Consensus Address | +| cosmosconspub | Cosmos Consensus Public Key | +| cosmosval | Cosmos Validator Operator Address | +| cosmosvalpub | Cosmos Validator Operator Public Key | ## Encoding -While all user facing interfaces to Cosmos software should exposed bech32 interfaces, many internal interfaces encode binary value in hex or base64 encoded form. - -To covert between other binary reprsentation of addresses and keys, it is important to first apply the Amino enocoding process before bech32 encoding. +While all user facing interfaces to Cosmos software should exposed Bech32 interfaces, many internal interfaces encode binary value in hex or base64 encoded form. -A complete implementation of the Amino serialization format is unncessary in most cases. Simply prepending bytes from this [table](https://github.com/tendermint/tendermint/blob/master/docs/spec/blockchain/encoding.md#public-key-cryptography) to the bytestring payload before bech32 encoding will sufficient for compatible representation. +To covert between other binary representation of addresses and keys, it is important to first apply the Amino encoding process before bech32 encoding. -  +A complete implementation of the Amino serialization format is unnecessary in most cases. Simply prepending bytes from this [table](https://github.com/tendermint/tendermint/blob/master/docs/spec/blockchain/encoding.md#public-key-cryptography) to the byte string payload before bech32 encoding will sufficient for compatible representation. diff --git a/docs/validators/validator-faq.md b/docs/validators/validator-faq.md index 6018ac3233ce..470f139d43e5 100644 --- a/docs/validators/validator-faq.md +++ b/docs/validators/validator-faq.md @@ -77,13 +77,14 @@ We view testnet participation as a great way to signal to the community that you In short, there are two types of keys: -- **Tendermint Key**: This is a unique key used to sign block hashes. It is associated with a public key `cosmosvalpub`. - + Generated when the node is created with gaiad init. - + Get this value with gaiad tendermint show_validator - +M e.g. cosmosvalpub1zcjduc3qcyj09qc03elte23zwshdx92jm6ce88fgc90rtqhjx8v0608qh5ssp0w94c - -- **Application keys**: These keys are created from the application and used to sign transactions. As a validator, you will probably use one key to sign staking-related transactions, and another key to sign governance-related transactions. Application keys are associated with a public key `cosmosaccpub` and an address `cosmosaccaddr`. Both are derived from account keys generated by `gaiacli keys add`. - +* **Tendermint Key**: This is a unique key used to sign block hashes. It is associated with a public key `cosmosconspub`. + * Generated when the node is created with gaiad init. + * Get this value with `gaiad tendermint show-validator` + e.g. `cosmosconspub1zcjduc3qcyj09qc03elte23zwshdx92jm6ce88fgc90rtqhjx8v0608qh5ssp0w94c` + +* **Application keys**: These keys are created from the application and used to sign transactions. As a validator, you will probably use one key to sign staking-related transactions, and another key to sign governance-related transactions. Application keys are associated with a public key `cosmospub` and an address `cosmos`. Both are derived from account keys generated by `gaiacli keys add`. + * Note: A validator's operator key is directly tied to an application key, but + uses reserved prefixes solely for this purpose: `cosmosval` and `cosmosvalpub` ### What are the different states a validator can be in? diff --git a/docs/validators/validator-setup.md b/docs/validators/validator-setup.md index 6fa4fefd21bc..8bf3e951ded4 100644 --- a/docs/validators/validator-setup.md +++ b/docs/validators/validator-setup.md @@ -16,7 +16,7 @@ If you want to become a validator for the Hub's `mainnet`, you should [research ### Create Your Validator -Your `cosmosvalpub` can be used to create a new validator by staking tokens. You can find your validator pubkey by running: +Your `cosmosconspub` can be used to create a new validator by staking tokens. You can find your validator pubkey by running: ```bash gaiad tendermint show-validator @@ -32,7 +32,7 @@ Don't use more `steak` thank you have! You can always get more by using the [Fau gaiacli stake create-validator \ --amount=5steak \ --pubkey=$(gaiad tendermint show-validator) \ - --address-validator=<account_cosmosaccaddr> + --address-validator=<account_cosmosval> --moniker="choose a moniker" \ --chain-id=<chain_id> \ --name=<key_name> @@ -46,7 +46,7 @@ The `--identity` can be used as to verify identity with systems like Keybase or ```bash gaiacli stake edit-validator - --validator=<account_cosmosaccaddr> + --validator=<account_cosmos> --moniker="choose a moniker" \ --website="https://cosmos.network" \ --identity=6A0D65E29A4CBC8E @@ -60,7 +60,7 @@ gaiacli stake edit-validator View the validator's information with this command: ```bash -gaiacli stake validator <account_cosmosaccaddr> +gaiacli stake validator <account_cosmos> ``` ### Track Validator Signing Information @@ -80,7 +80,7 @@ When a validator is "jailed" for downtime, you must submit an `Unjail` transacti gaiacli stake unjail \ --from=<key_name> \ --chain-id=<chain_id> - --validator=<account_cosmosaccaddr> \ + --validator=<account_cosmosval> \ --chain-id=gaia-6002 ``` @@ -110,10 +110,10 @@ Here's how you can return the voting power back to your validator. First, if `ga gaiad start ``` -Wait for your full node to catch up to the latest block. Next, run the following command. Note that `<cosmosaccaddr>` is the address of your validator account, and `<name>` is the name of the validator account. You can find this info by running `gaiacli keys list`. +Wait for your full node to catch up to the latest block. Next, run the following command. Note that `<cosmos>` is the address of your validator account, and `<name>` is the name of the validator account. You can find this info by running `gaiacli keys list`. ```bash -gaiacli stake unjail <cosmosaccaddr> --chain-id=<chain_id> --name=<name> +gaiacli stake unjail <cosmos> --chain-id=<chain_id> --name=<name> ``` ::: danger Warning diff --git a/examples/README.md b/examples/README.md index d12e3d3fccdf..11aef9d280fd 100644 --- a/examples/README.md +++ b/examples/README.md @@ -103,10 +103,10 @@ basecli keys list You should now see alice, bob and charlie's account all show up. ``` -NAME: ADDRESS: PUBKEY: -alice cosmosaccaddr1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f cosmosaccpub1addwnpepq0w037u5g7y7lvdvsred2dehg90j84k0weyss5ynysf0nnnax74agrsxns6 -bob cosmosaccaddr18se8tz6kwwfga6k2yjsu7n64e9z52nen29rhzz cosmosaccpub1addwnpepqwe97n8lryxrzvamrvjfj24jys3uzf8wndfvqa2l7mh5nsv4jrvdznvyeg6 -charlie cosmosaccaddr13wq5mklhn03ljpd4dkph5rflk5a3ssma2ag07q cosmosaccpub1addwnpepqdmtxv35rrmv2dvcr3yhfyxj7dzrd4z4rnhmclksq4g55a4wpl54clvx33l +NAME: ADDRESS: PUBKEY: +alice cosmos1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f cosmospub1addwnpepq0w037u5g7y7lvdvsred2dehg90j84k0weyss5ynysf0nnnax74agrsxns6 +bob cosmos18se8tz6kwwfga6k2yjsu7n64e9z52nen29rhzz cosmospub1addwnpepqwe97n8lryxrzvamrvjfj24jys3uzf8wndfvqa2l7mh5nsv4jrvdznvyeg6 +charlie cosmos13wq5mklhn03ljpd4dkph5rflk5a3ssma2ag07q cosmospub1addwnpepqdmtxv35rrmv2dvcr3yhfyxj7dzrd4z4rnhmclksq4g55a4wpl54clvx33l ``` @@ -115,15 +115,15 @@ charlie cosmosaccaddr13wq5mklhn03ljpd4dkph5rflk5a3ssma2ag07q cosmosaccpub1addwnp Lets send bob and charlie some tokens. First, lets query alice's account so we can see what kind of tokens she has: ``` -basecli account cosmosaccaddr1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f +basecli account cosmos1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f ``` -Where `cosmosaccaddr1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f` is alice's address we got from running `basecli keys list`. You should see a large amount of "mycoin" there. If you search for bob's or charlie's address, the command will fail, because they haven't been added into the blockchain database yet since they have no coins. We need to send them some! +Where `cosmos1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f` is alice's address we got from running `basecli keys list`. You should see a large amount of "mycoin" there. If you search for bob's or charlie's address, the command will fail, because they haven't been added into the blockchain database yet since they have no coins. We need to send them some! The following command will send coins from alice, to bob: ``` -basecli send --from=alice --amount=10000mycoin --to=cosmosaccaddr18se8tz6kwwfga6k2yjsu7n64e9z52nen29rhzz +basecli send --from=alice --amount=10000mycoin --to=cosmos18se8tz6kwwfga6k2yjsu7n64e9z52nen29rhzz --sequence=0 --chain-id=test-chain-AE4XQo ``` @@ -136,13 +136,13 @@ Flag Descriptions: Now if we check bobs account, it should have `10000 mycoin`. You can do so by running : ``` -basecli account cosmosaccaddr18se8tz6kwwfga6k2yjsu7n64e9z52nen29rhzz +basecli account cosmos18se8tz6kwwfga6k2yjsu7n64e9z52nen29rhzz ``` Now lets send some from bob to charlie. Make sure you send less than bob has, otherwise the transaction will fail: ``` -basecli send --from=bob --amount=5000mycoin --to=cosmosaccaddr13wq5mklhn03ljpd4dkph5rflk5a3ssma2ag07q +basecli send --from=bob --amount=5000mycoin --to=cosmos13wq5mklhn03ljpd4dkph5rflk5a3ssma2ag07q --sequence=0 --chain-id=test-chain-AE4XQo ``` @@ -151,7 +151,7 @@ Note how we use the ``--from`` flag to select a different account to send from. Lets now try to send from bob back to alice: ``` -basecli send --from=bob --amount=3000mycoin --to=cosmosaccaddr1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f +basecli send --from=bob --amount=3000mycoin --to=cosmos1khygs0qh7gz3p4m39u00mjhvgvc2dcpxhsuh5f --sequence=1 --chain-id=test-chain-AE4XQo ``` diff --git a/examples/democoin/mock/validator.go b/examples/democoin/mock/validator.go index bb936097ccb4..f937e45dcc71 100644 --- a/examples/democoin/mock/validator.go +++ b/examples/democoin/mock/validator.go @@ -9,7 +9,7 @@ import ( // Validator implements sdk.Validator type Validator struct { - Address sdk.AccAddress + Address sdk.ValAddress Power sdk.Dec } @@ -19,7 +19,7 @@ func (v Validator) GetStatus() sdk.BondStatus { } // Implements sdk.Validator -func (v Validator) GetOperator() sdk.AccAddress { +func (v Validator) GetOperator() sdk.ValAddress { return v.Address } @@ -78,9 +78,9 @@ func (vs *ValidatorSet) IterateValidatorsBonded(ctx sdk.Context, fn func(index i } // Validator implements sdk.ValidatorSet -func (vs *ValidatorSet) Validator(ctx sdk.Context, addr sdk.AccAddress) sdk.Validator { +func (vs *ValidatorSet) Validator(ctx sdk.Context, addr sdk.ValAddress) sdk.Validator { for _, val := range vs.Validators { - if bytes.Equal(val.Address, addr) { + if bytes.Equal(val.Address.Bytes(), addr.Bytes()) { return val } } diff --git a/examples/democoin/x/assoc/validator_set.go b/examples/democoin/x/assoc/validator_set.go index ad89aab19281..8a954c72037c 100644 --- a/examples/democoin/x/assoc/validator_set.go +++ b/examples/democoin/x/assoc/validator_set.go @@ -37,7 +37,7 @@ func NewValidatorSet(cdc *wire.Codec, store sdk.KVStore, valset sdk.ValidatorSet } // Implements sdk.ValidatorSet -func (valset ValidatorSet) Validator(ctx sdk.Context, addr sdk.AccAddress) (res sdk.Validator) { +func (valset ValidatorSet) Validator(ctx sdk.Context, addr sdk.ValAddress) (res sdk.Validator) { base := valset.store.Get(GetBaseKey(addr)) res = valset.ValidatorSet.Validator(ctx, base) if res == nil { @@ -46,23 +46,23 @@ func (valset ValidatorSet) Validator(ctx sdk.Context, addr sdk.AccAddress) (res return } -// GetBaseKey :: sdk.AccAddress -> sdk.AccAddress -func GetBaseKey(addr sdk.AccAddress) []byte { +// GetBaseKey :: sdk.ValAddress -> sdk.ValAddress +func GetBaseKey(addr sdk.ValAddress) []byte { return append([]byte{0x00}, addr...) } -// GetAssocPrefix :: sdk.AccAddress -> (sdk.AccAddress -> byte) -func GetAssocPrefix(base sdk.AccAddress) []byte { +// GetAssocPrefix :: sdk.ValAddress -> (sdk.ValAddress -> byte) +func GetAssocPrefix(base sdk.ValAddress) []byte { return append([]byte{0x01}, base...) } -// GetAssocKey :: (sdk.AccAddress, sdk.AccAddress) -> byte -func GetAssocKey(base sdk.AccAddress, assoc sdk.AccAddress) []byte { +// GetAssocKey :: (sdk.ValAddress, sdk.ValAddress) -> byte +func GetAssocKey(base sdk.ValAddress, assoc sdk.ValAddress) []byte { return append(append([]byte{0x01}, base...), assoc...) } // Associate associates new address with validator address -func (valset ValidatorSet) Associate(ctx sdk.Context, base sdk.AccAddress, assoc sdk.AccAddress) bool { +func (valset ValidatorSet) Associate(ctx sdk.Context, base sdk.ValAddress, assoc sdk.ValAddress) bool { if len(base) != valset.addrLen || len(assoc) != valset.addrLen { return false } @@ -76,7 +76,7 @@ func (valset ValidatorSet) Associate(ctx sdk.Context, base sdk.AccAddress, assoc } // Dissociate removes association between addresses -func (valset ValidatorSet) Dissociate(ctx sdk.Context, base sdk.AccAddress, assoc sdk.AccAddress) bool { +func (valset ValidatorSet) Dissociate(ctx sdk.Context, base sdk.ValAddress, assoc sdk.ValAddress) bool { if len(base) != valset.addrLen || len(assoc) != valset.addrLen { return false } @@ -90,8 +90,8 @@ func (valset ValidatorSet) Dissociate(ctx sdk.Context, base sdk.AccAddress, asso } // Associations returns all associated addresses with a validator -func (valset ValidatorSet) Associations(ctx sdk.Context, base sdk.AccAddress) (res []sdk.AccAddress) { - res = make([]sdk.AccAddress, valset.maxAssoc) +func (valset ValidatorSet) Associations(ctx sdk.Context, base sdk.ValAddress) (res []sdk.ValAddress) { + res = make([]sdk.ValAddress, valset.maxAssoc) iter := sdk.KVStorePrefixIterator(valset.store, GetAssocPrefix(base)) defer iter.Close() i := 0 diff --git a/examples/democoin/x/oracle/handler.go b/examples/democoin/x/oracle/handler.go index 1aaefc7e1621..c525222c4c42 100644 --- a/examples/democoin/x/oracle/handler.go +++ b/examples/democoin/x/oracle/handler.go @@ -68,8 +68,8 @@ func (keeper Keeper) Handle(h Handler, ctx sdk.Context, o Msg, codespace sdk.Cod } info.LastSigned = ctx.BlockHeight() - // Check the signer is a validater - val := valset.Validator(ctx, signer) + // check the signer is a validator + val := valset.Validator(ctx, sdk.ValAddress(signer)) if val == nil { return ErrNotValidator(codespace, signer).Result() } diff --git a/examples/democoin/x/pow/types_test.go b/examples/democoin/x/pow/types_test.go index be848d94089a..dbe6ad35e953 100644 --- a/examples/democoin/x/pow/types_test.go +++ b/examples/democoin/x/pow/types_test.go @@ -55,14 +55,14 @@ func TestMsgMineString(t *testing.T) { addr := sdk.AccAddress([]byte("sender")) msg := MsgMine{addr, 0, 0, 0, []byte("abc")} res := msg.String() - require.Equal(t, res, "MsgMine{Sender: cosmosaccaddr1wdjkuer9wg4wml9c, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") + require.Equal(t, res, "MsgMine{Sender: cosmos1wdjkuer9wgh76ts6, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") } func TestMsgMineGetSignBytes(t *testing.T) { addr := sdk.AccAddress([]byte("sender")) msg := MsgMine{addr, 1, 1, 1, []byte("abc")} res := msg.GetSignBytes() - require.Equal(t, string(res), `{"count":1,"difficulty":1,"nonce":1,"proof":"YWJj","sender":"cosmosaccaddr1wdjkuer9wg4wml9c"}`) + require.Equal(t, string(res), `{"count":1,"difficulty":1,"nonce":1,"proof":"YWJj","sender":"cosmos1wdjkuer9wgh76ts6"}`) } func TestMsgMineGetSigners(t *testing.T) { diff --git a/server/tm_cmds.go b/server/tm_cmds.go index d84022183ae1..b6daf0775320 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -45,10 +45,12 @@ func ShowValidatorCmd(ctx *Context) *cobra.Command { if viper.GetBool(client.FlagJson) { return printlnJSON(valPubKey) } - pubkey, err := sdk.Bech32ifyValPub(valPubKey) + + pubkey, err := sdk.Bech32ifyConsPub(valPubKey) if err != nil { return err } + fmt.Println(pubkey) return nil }, diff --git a/types/account.go b/types/account.go index 00076b52997d..1df600c36e1a 100644 --- a/types/account.go +++ b/types/account.go @@ -13,251 +13,422 @@ import ( "github.com/tendermint/tendermint/libs/bech32" ) -// Bech32 prefixes const ( - // expected address length + // AddrLen defines a valid address length AddrLen = 20 - // Bech32 prefixes - Bech32PrefixAccAddr = "cosmosaccaddr" - Bech32PrefixAccPub = "cosmosaccpub" - Bech32PrefixValAddr = "cosmosvaladdr" - Bech32PrefixValPub = "cosmosvalpub" + // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address + Bech32PrefixAccAddr = "cosmos" + // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key + Bech32PrefixAccPub = "cosmospub" + // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address + Bech32PrefixValAddr = "cosmosval" + // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key + Bech32PrefixValPub = "cosmosvalpub" + // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address + Bech32PrefixConsAddr = "cosmoscons" + // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key + Bech32PrefixConsPub = "cosmosconspub" ) -//__________________________________________________________ +// ---------------------------------------------------------------------------- +// account +// ---------------------------------------------------------------------------- -// AccAddress a wrapper around bytes meant to represent an account address -// When marshaled to a string or json, it uses bech32 +// AccAddress a wrapper around bytes meant to represent an account address. +// When marshaled to a string or JSON, it uses Bech32. type AccAddress []byte -// create an AccAddress from a hex string +// AccAddressFromHex creates an AccAddress from a hex string. func AccAddressFromHex(address string) (addr AccAddress, err error) { if len(address) == 0 { - return addr, errors.New("decoding bech32 address failed: must provide an address") + return addr, errors.New("decoding Bech32 address failed: must provide an address") } + bz, err := hex.DecodeString(address) if err != nil { return nil, err } + return AccAddress(bz), nil } -// create an AccAddress from a bech32 string +// AccAddressFromBech32 creates an AccAddress from a Bech32 string. func AccAddressFromBech32(address string) (addr AccAddress, err error) { bz, err := GetFromBech32(address, Bech32PrefixAccAddr) if err != nil { return nil, err } + return AccAddress(bz), nil } -// Marshal needed for protobuf compatibility -func (bz AccAddress) Marshal() ([]byte, error) { - return bz, nil +// Returns boolean for whether two AccAddresses are Equal +func (aa AccAddress) Equals(aa2 AccAddress) bool { + if aa.Empty() && aa2.Empty() { + return true + } + + return bytes.Compare(aa.Bytes(), aa2.Bytes()) == 0 +} + +// Returns boolean for whether an AccAddress is empty +func (aa AccAddress) Empty() bool { + if aa == nil { + return true + } + + aa2 := AccAddress{} + return bytes.Compare(aa.Bytes(), aa2.Bytes()) == 0 } -// Unmarshal needed for protobuf compatibility -func (bz *AccAddress) Unmarshal(data []byte) error { - *bz = data +// Marshal returns the raw address bytes. It is needed for protobuf +// compatibility. +func (aa AccAddress) Marshal() ([]byte, error) { + 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 = data return nil } -// Marshals to JSON using Bech32 -func (bz AccAddress) MarshalJSON() ([]byte, error) { - return json.Marshal(bz.String()) +// MarshalJSON marshals to JSON using Bech32. +func (aa AccAddress) MarshalJSON() ([]byte, error) { + return json.Marshal(aa.String()) } -// Unmarshals from JSON assuming Bech32 encoding -func (bz *AccAddress) UnmarshalJSON(data []byte) error { +// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. +func (aa *AccAddress) UnmarshalJSON(data []byte) error { var s string err := json.Unmarshal(data, &s) if err != nil { return nil } - bz2, err := AccAddressFromBech32(s) + aa2, err := AccAddressFromBech32(s) if err != nil { return err } - *bz = bz2 + + *aa = aa2 return nil } -// Allow it to fulfill various interfaces in light-client, etc... -func (bz AccAddress) Bytes() []byte { - return bz +// Bytes returns the raw address bytes. +func (aa AccAddress) Bytes() []byte { + return aa } -func (bz AccAddress) String() string { - bech32Addr, err := bech32.ConvertAndEncode(Bech32PrefixAccAddr, bz.Bytes()) +// String implements the Stringer interface. +func (aa AccAddress) String() string { + bech32Addr, err := bech32.ConvertAndEncode(Bech32PrefixAccAddr, aa.Bytes()) if err != nil { panic(err) } + return bech32Addr } -// For Printf / Sprintf, returns bech32 when using %s -func (bz AccAddress) Format(s fmt.State, verb rune) { +// Format implements the fmt.Formatter interface. +func (aa AccAddress) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(fmt.Sprintf("%s", bz.String()))) + s.Write([]byte(fmt.Sprintf("%s", aa.String()))) case 'p': - s.Write([]byte(fmt.Sprintf("%p", bz))) + s.Write([]byte(fmt.Sprintf("%p", aa))) default: - s.Write([]byte(fmt.Sprintf("%X", []byte(bz)))) + s.Write([]byte(fmt.Sprintf("%X", []byte(aa)))) } } -// Returns boolean for whether two AccAddresses are Equal -func (bz AccAddress) Equals(bz2 AccAddress) bool { - if bz.Empty() && bz2.Empty() { - return true - } - return bytes.Compare(bz.Bytes(), bz2.Bytes()) == 0 -} - -// Returns boolean for whether an AccAddress is empty -func (bz AccAddress) Empty() bool { - if bz == nil { - return true - } - bz2 := AccAddress{} - return bytes.Compare(bz.Bytes(), bz2.Bytes()) == 0 -} +// ---------------------------------------------------------------------------- +// validator owner +// ---------------------------------------------------------------------------- -//__________________________________________________________ - -// AccAddress a wrapper around bytes meant to represent a validator address -// (from over ABCI). When marshaled to a string or json, it uses bech32 +// ValAddress defines a wrapper around bytes meant to present a validator's +// operator. When marshaled to a string or JSON, it uses Bech32. type ValAddress []byte -// create a ValAddress from a hex string +// ValAddressFromHex creates a ValAddress from a hex string. func ValAddressFromHex(address string) (addr ValAddress, err error) { if len(address) == 0 { - return addr, errors.New("decoding bech32 address failed: must provide an address") + return addr, errors.New("decoding Bech32 address failed: must provide an address") } + bz, err := hex.DecodeString(address) if err != nil { return nil, err } + return ValAddress(bz), nil } -// create a ValAddress from a bech32 string +// ValAddressFromBech32 creates a ValAddress from a Bech32 string. func ValAddressFromBech32(address string) (addr ValAddress, err error) { bz, err := GetFromBech32(address, Bech32PrefixValAddr) if err != nil { return nil, err } + return ValAddress(bz), nil } -// Marshal needed for protobuf compatibility -func (bz ValAddress) Marshal() ([]byte, error) { - return bz, nil +// Returns boolean for whether two ValAddresses are Equal +func (va ValAddress) Equals(va2 ValAddress) bool { + if va.Empty() && va2.Empty() { + return true + } + + return bytes.Compare(va.Bytes(), va2.Bytes()) == 0 +} + +// Returns boolean for whether an AccAddress is empty +func (va ValAddress) Empty() bool { + if va == nil { + return true + } + + va2 := ValAddress{} + return bytes.Compare(va.Bytes(), va2.Bytes()) == 0 +} + +// Marshal returns the raw address bytes. It is needed for protobuf +// compatibility. +func (va ValAddress) Marshal() ([]byte, error) { + return va, nil } -// Unmarshal needed for protobuf compatibility -func (bz *ValAddress) Unmarshal(data []byte) error { - *bz = data +// Unmarshal sets the address to the given data. It is needed for protobuf +// compatibility. +func (va *ValAddress) Unmarshal(data []byte) error { + *va = data return nil } -// Marshals to JSON using Bech32 -func (bz ValAddress) MarshalJSON() ([]byte, error) { - return json.Marshal(bz.String()) +// MarshalJSON marshals to JSON using Bech32. +func (va ValAddress) MarshalJSON() ([]byte, error) { + return json.Marshal(va.String()) } -// Unmarshals from JSON assuming Bech32 encoding -func (bz *ValAddress) UnmarshalJSON(data []byte) 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 nil } - bz2, err := ValAddressFromBech32(s) + va2, err := ValAddressFromBech32(s) if err != nil { return err } - *bz = bz2 + + *va = va2 return nil } -// Allow it to fulfill various interfaces in light-client, etc... -func (bz ValAddress) Bytes() []byte { - return bz +// Bytes returns the raw address bytes. +func (va ValAddress) Bytes() []byte { + return va } -func (bz ValAddress) String() string { - bech32Addr, err := bech32.ConvertAndEncode(Bech32PrefixValAddr, bz.Bytes()) +// String implements the Stringer interface. +func (va ValAddress) String() string { + bech32Addr, err := bech32.ConvertAndEncode(Bech32PrefixValAddr, va.Bytes()) if err != nil { panic(err) } + return bech32Addr } -// For Printf / Sprintf, returns bech32 when using %s -func (bz ValAddress) Format(s fmt.State, verb rune) { +// Format implements the fmt.Formatter interface. +func (va ValAddress) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(fmt.Sprintf("%s", bz.String()))) + s.Write([]byte(fmt.Sprintf("%s", va.String()))) case 'p': - s.Write([]byte(fmt.Sprintf("%p", bz))) + s.Write([]byte(fmt.Sprintf("%p", va))) default: - s.Write([]byte(fmt.Sprintf("%X", []byte(bz)))) + s.Write([]byte(fmt.Sprintf("%X", []byte(va)))) } } -// Returns boolean for whether two ValAddresses are Equal -func (bz ValAddress) Equals(bz2 ValAddress) bool { - if bz.Empty() && bz2.Empty() { +// ---------------------------------------------------------------------------- +// consensus node +// ---------------------------------------------------------------------------- + +// ConsAddress defines a wrapper around bytes meant to present a consensus node. +// When marshaled to a string or JSON, it uses Bech32. +type ConsAddress []byte + +// ConsAddressFromHex creates a ConsAddress from a hex string. +func ConsAddressFromHex(address string) (addr ConsAddress, err error) { + if len(address) == 0 { + return addr, errors.New("decoding Bech32 address failed: must provide an address") + } + + bz, err := hex.DecodeString(address) + if err != nil { + return nil, err + } + + return ConsAddress(bz), nil +} + +// ConsAddressFromBech32 creates a ConsAddress from a Bech32 string. +func ConsAddressFromBech32(address string) (addr ConsAddress, err error) { + bz, err := GetFromBech32(address, Bech32PrefixConsAddr) + if err != nil { + return nil, err + } + + return ConsAddress(bz), nil +} + +// Returns boolean for whether two ConsAddress are Equal +func (ca ConsAddress) Equals(ca2 ConsAddress) bool { + if ca.Empty() && ca2.Empty() { return true } - return bytes.Compare(bz.Bytes(), bz2.Bytes()) == 0 + + return bytes.Compare(ca.Bytes(), ca2.Bytes()) == 0 } -// Returns boolean for whether an AccAddress is empty -func (bz ValAddress) Empty() bool { - if bz == nil { +// Returns boolean for whether an ConsAddress is empty +func (ca ConsAddress) Empty() bool { + if ca == nil { return true } - bz2 := ValAddress{} - return bytes.Compare(bz.Bytes(), bz2.Bytes()) == 0 + + ca2 := ConsAddress{} + return bytes.Compare(ca.Bytes(), ca2.Bytes()) == 0 +} + +// Marshal returns the raw address bytes. It is needed for protobuf +// compatibility. +func (ca ConsAddress) Marshal() ([]byte, error) { + 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 = data + return nil +} + +// MarshalJSON marshals to JSON using Bech32. +func (ca ConsAddress) MarshalJSON() ([]byte, error) { + return json.Marshal(ca.String()) +} + +// 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 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 ca +} + +// String implements the Stringer interface. +func (ca ConsAddress) String() string { + bech32Addr, err := bech32.ConvertAndEncode(Bech32PrefixConsAddr, ca.Bytes()) + if err != nil { + panic(err) + } + + return bech32Addr +} + +// Format implements the fmt.Formatter interface. +func (ca ConsAddress) Format(s fmt.State, verb rune) { + switch verb { + case 's': + s.Write([]byte(fmt.Sprintf("%s", ca.String()))) + case 'p': + s.Write([]byte(fmt.Sprintf("%p", ca))) + default: + s.Write([]byte(fmt.Sprintf("%X", []byte(ca)))) + } } -// Bech32ifyAccPub takes AccountPubKey and returns the bech32 encoded string +// ---------------------------------------------------------------------------- +// auxiliary +// ---------------------------------------------------------------------------- + +// Bech32ifyAccPub returns a Bech32 encoded string containing the +// Bech32PrefixAccPub prefix for a given account PubKey. func Bech32ifyAccPub(pub crypto.PubKey) (string, error) { return bech32.ConvertAndEncode(Bech32PrefixAccPub, pub.Bytes()) } -// MustBech32ifyAccPub panics on bech32-encoding failure +// MustBech32ifyAccPub returns the result of Bech32ifyAccPub panicing on failure. func MustBech32ifyAccPub(pub crypto.PubKey) string { enc, err := Bech32ifyAccPub(pub) if err != nil { panic(err) } + return enc } -// Bech32ifyValPub returns the bech32 encoded string for a validator pubkey +// Bech32ifyValPub returns a Bech32 encoded string containing the +// Bech32PrefixValPub prefix for a given validator operator's PubKey. func Bech32ifyValPub(pub crypto.PubKey) (string, error) { return bech32.ConvertAndEncode(Bech32PrefixValPub, pub.Bytes()) } -// MustBech32ifyValPub panics on bech32-encoding failure +// MustBech32ifyValPub returns the result of Bech32ifyValPub panicing on failure. func MustBech32ifyValPub(pub crypto.PubKey) string { enc, err := Bech32ifyValPub(pub) if err != nil { panic(err) } + + return enc +} + +// Bech32ifyConsPub returns a Bech32 encoded string containing the +// Bech32PrefixConsPub prefixfor a given consensus node's PubKey. +func Bech32ifyConsPub(pub crypto.PubKey) (string, error) { + return bech32.ConvertAndEncode(Bech32PrefixConsPub, pub.Bytes()) +} + +// MustBech32ifyConsPub returns the result of Bech32ifyConsPub panicing on +// failure. +func MustBech32ifyConsPub(pub crypto.PubKey) string { + enc, err := Bech32ifyConsPub(pub) + if err != nil { + panic(err) + } + return enc } -// create a Pubkey from a string -func GetAccPubKeyBech32(address string) (pk crypto.PubKey, err error) { - bz, err := GetFromBech32(address, Bech32PrefixAccPub) +// GetAccPubKeyBech32 creates a PubKey for an account with a given public key +// string using the Bech32 Bech32PrefixAccPub prefix. +func GetAccPubKeyBech32(pubkey string) (pk crypto.PubKey, err error) { + bz, err := GetFromBech32(pubkey, Bech32PrefixAccPub) if err != nil { return nil, err } @@ -270,16 +441,19 @@ func GetAccPubKeyBech32(address string) (pk crypto.PubKey, err error) { return pk, nil } -// create an Pubkey from a string, panics on error -func MustGetAccPubKeyBech32(address string) (pk crypto.PubKey) { - pk, err := GetAccPubKeyBech32(address) +// MustGetAccPubKeyBech32 returns the result of GetAccPubKeyBech32 panicing on +// failure. +func MustGetAccPubKeyBech32(pubkey string) (pk crypto.PubKey) { + pk, err := GetAccPubKeyBech32(pubkey) if err != nil { panic(err) } + return pk } -// decode a validator public key into a PubKey +// GetValPubKeyBech32 creates a PubKey for a validator's operator with a given +// public key string using the Bech32 Bech32PrefixValPub prefix. func GetValPubKeyBech32(pubkey string) (pk crypto.PubKey, err error) { bz, err := GetFromBech32(pubkey, Bech32PrefixValPub) if err != nil { @@ -294,27 +468,57 @@ func GetValPubKeyBech32(pubkey string) (pk crypto.PubKey, err error) { return pk, nil } -// create an Pubkey from a string, panics on error -func MustGetValPubKeyBech32(address string) (pk crypto.PubKey) { - pk, err := GetValPubKeyBech32(address) +// MustGetValPubKeyBech32 returns the result of GetValPubKeyBech32 panicing on +// failure. +func MustGetValPubKeyBech32(pubkey string) (pk crypto.PubKey) { + pk, err := GetValPubKeyBech32(pubkey) if err != nil { panic(err) } + return pk } -// decode a bytestring from a bech32-encoded string +// GetConsPubKeyBech32 creates a PubKey for a consensus node with a given public +// key string using the Bech32 Bech32PrefixConsPub prefix. +func GetConsPubKeyBech32(pubkey string) (pk crypto.PubKey, err error) { + bz, err := GetFromBech32(pubkey, Bech32PrefixConsPub) + if err != nil { + return nil, err + } + + pk, err = cryptoAmino.PubKeyFromBytes(bz) + if err != nil { + return nil, err + } + + return pk, nil +} + +// MustGetConsPubKeyBech32 returns the result of GetConsPubKeyBech32 panicing on +// failure. +func MustGetConsPubKeyBech32(pubkey string) (pk crypto.PubKey) { + pk, err := GetConsPubKeyBech32(pubkey) + if err != nil { + panic(err) + } + + return pk +} + +// GetFromBech32 decodes a bytestring from a Bech32 encoded string. func GetFromBech32(bech32str, prefix string) ([]byte, error) { if len(bech32str) == 0 { - return nil, errors.New("decoding bech32 address failed: must provide an address") + return nil, errors.New("decoding Bech32 address failed: must provide an address") } + hrp, bz, err := bech32.DecodeAndConvert(bech32str) if err != nil { return nil, err } if hrp != prefix { - return nil, fmt.Errorf("invalid bech32 prefix. Expected %s, Got %s", prefix, hrp) + return nil, fmt.Errorf("invalid Bech32 prefix; expected %s, got %s", prefix, hrp) } return bz, nil diff --git a/types/account_test.go b/types/account_test.go index aa222ee7e991..e2ec36876cd5 100644 --- a/types/account_test.go +++ b/types/account_test.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/types" ) -var invalidstrs = []string{ +var invalidStrs = []string{ "", "hello, world!", "0xAA", @@ -21,6 +21,8 @@ var invalidstrs = []string{ types.Bech32PrefixAccPub + "1234", types.Bech32PrefixValAddr + "5678", types.Bech32PrefixValPub + "BBAB", + types.Bech32PrefixConsAddr + "FF04", + types.Bech32PrefixConsPub + "6789", } func testMarshal(t *testing.T, original interface{}, res interface{}, marshal func() ([]byte, error), unmarshal func([]byte) error) { @@ -37,27 +39,38 @@ func TestRandBech32PubkeyConsistency(t *testing.T) { for i := 0; i < 1000; i++ { rand.Read(pub[:]) - mustbech32accpub := types.MustBech32ifyAccPub(pub) - bech32accpub, err := types.Bech32ifyAccPub(pub) + mustBech32AccPub := types.MustBech32ifyAccPub(pub) + bech32AccPub, err := types.Bech32ifyAccPub(pub) require.Nil(t, err) - require.Equal(t, bech32accpub, mustbech32accpub) + require.Equal(t, bech32AccPub, mustBech32AccPub) - mustbech32valpub := types.MustBech32ifyValPub(pub) - bech32valpub, err := types.Bech32ifyValPub(pub) + mustBech32ValPub := types.MustBech32ifyValPub(pub) + bech32ValPub, err := types.Bech32ifyValPub(pub) require.Nil(t, err) - require.Equal(t, bech32valpub, mustbech32valpub) + require.Equal(t, bech32ValPub, mustBech32ValPub) - mustaccpub := types.MustGetAccPubKeyBech32(bech32accpub) - accpub, err := types.GetAccPubKeyBech32(bech32accpub) + mustBech32ConsPub := types.MustBech32ifyConsPub(pub) + bech32ConsPub, err := types.Bech32ifyConsPub(pub) require.Nil(t, err) - require.Equal(t, accpub, mustaccpub) + require.Equal(t, bech32ConsPub, mustBech32ConsPub) - mustvalpub := types.MustGetValPubKeyBech32(bech32valpub) - valpub, err := types.GetValPubKeyBech32(bech32valpub) + mustAccPub := types.MustGetAccPubKeyBech32(bech32AccPub) + accPub, err := types.GetAccPubKeyBech32(bech32AccPub) require.Nil(t, err) - require.Equal(t, valpub, mustvalpub) + require.Equal(t, accPub, mustAccPub) - require.Equal(t, valpub, accpub) + mustValPub := types.MustGetValPubKeyBech32(bech32ValPub) + valPub, err := types.GetValPubKeyBech32(bech32ValPub) + require.Nil(t, err) + require.Equal(t, valPub, mustValPub) + + mustConsPub := types.MustGetConsPubKeyBech32(bech32ConsPub) + consPub, err := types.GetConsPubKeyBech32(bech32ConsPub) + require.Nil(t, err) + require.Equal(t, consPub, mustConsPub) + + require.Equal(t, valPub, accPub) + require.Equal(t, valPub, consPub) } } @@ -84,7 +97,7 @@ func TestRandBech32AccAddrConsistency(t *testing.T) { require.Equal(t, acc, res) } - for _, str := range invalidstrs { + for _, str := range invalidStrs { _, err := types.AccAddressFromHex(str) require.NotNil(t, err) @@ -119,7 +132,7 @@ func TestValAddr(t *testing.T) { require.Equal(t, acc, res) } - for _, str := range invalidstrs { + for _, str := range invalidStrs { _, err := types.ValAddressFromHex(str) require.NotNil(t, err) @@ -130,3 +143,38 @@ func TestValAddr(t *testing.T) { require.NotNil(t, err) } } + +func TestConsAddress(t *testing.T) { + var pub ed25519.PubKeyEd25519 + + for i := 0; i < 20; i++ { + rand.Read(pub[:]) + + acc := types.ConsAddress(pub.Address()) + res := types.ConsAddress{} + + testMarshal(t, &acc, &res, acc.MarshalJSON, (&res).UnmarshalJSON) + testMarshal(t, &acc, &res, acc.Marshal, (&res).Unmarshal) + + str := acc.String() + res, err := types.ConsAddressFromBech32(str) + require.Nil(t, err) + require.Equal(t, acc, res) + + str = hex.EncodeToString(acc) + res, err = types.ConsAddressFromHex(str) + require.Nil(t, err) + require.Equal(t, acc, res) + } + + for _, str := range invalidStrs { + _, err := types.ConsAddressFromHex(str) + require.NotNil(t, err) + + _, err = types.ConsAddressFromBech32(str) + require.NotNil(t, err) + + err = (*types.ConsAddress)(nil).UnmarshalJSON([]byte("\"" + str + "\"")) + require.NotNil(t, err) + } +} diff --git a/types/stake.go b/types/stake.go index d872277256df..f41125177555 100644 --- a/types/stake.go +++ b/types/stake.go @@ -40,7 +40,7 @@ type Validator interface { GetJailed() bool // whether the validator is jailed GetMoniker() string // moniker of the validator GetStatus() BondStatus // status of the validator - GetOperator() AccAddress // owner AccAddress to receive/return validators coins + GetOperator() ValAddress // owner address to receive/return validators coins GetPubKey() crypto.PubKey // validation pubkey GetPower() Dec // validation power GetTokens() Dec // validation tokens @@ -67,7 +67,7 @@ type ValidatorSet interface { IterateValidatorsBonded(Context, func(index int64, validator Validator) (stop bool)) - Validator(Context, AccAddress) Validator // get a particular validator by owner AccAddress + Validator(Context, ValAddress) Validator // get a particular validator by operator ValidatorByPubKey(Context, crypto.PubKey) Validator // get a particular validator by signing PubKey TotalPower(Context) Dec // total power of the validator set @@ -82,7 +82,7 @@ type ValidatorSet interface { // delegation bond for a delegated proof of stake system type Delegation interface { GetDelegator() AccAddress // delegator AccAddress for the bond - GetValidator() AccAddress // validator owner AccAddress for the bond + GetValidator() ValAddress // validator operator address GetBondShares() Dec // amount of validator's shares } diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index ac16b1d0b1c7..e082bdac4227 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -187,7 +187,7 @@ func TestMsgSendGetSignBytes(t *testing.T) { } res := msg.GetSignBytes() - expected := `{"inputs":[{"address":"cosmosaccaddr1d9h8qat5e4ehc5","coins":[{"amount":"10","denom":"atom"}]}],"outputs":[{"address":"cosmosaccaddr1da6hgur4wse3jx32","coins":[{"amount":"10","denom":"atom"}]}]}` + expected := `{"inputs":[{"address":"cosmos1d9h8qat57ljhcm","coins":[{"amount":"10","denom":"atom"}]}],"outputs":[{"address":"cosmos1da6hgur4wsmpnjyg","coins":[{"amount":"10","denom":"atom"}]}]}` require.Equal(t, expected, string(res)) } @@ -257,7 +257,7 @@ func TestMsgIssueGetSignBytes(t *testing.T) { } res := msg.GetSignBytes() - expected := `{"banker":"cosmosaccaddr1d9h8qat5e4ehc5","outputs":[{"address":"cosmosaccaddr1d3hkzm3dveex7mfdvfsku6cwsauqd","coins":[{"amount":"10","denom":"atom"}]}]}` + expected := `{"banker":"cosmos1d9h8qat57ljhcm","outputs":[{"address":"cosmos1d3hkzm3dveex7mfdvfsku6cjngpcj","coins":[{"amount":"10","denom":"atom"}]}]}` require.Equal(t, expected, string(res)) } diff --git a/x/gov/endblocker_test.go b/x/gov/endblocker_test.go index 9dd241aabda4..710ecb1dba2a 100644 --- a/x/gov/endblocker_test.go +++ b/x/gov/endblocker_test.go @@ -178,12 +178,17 @@ func TestSlashing(t *testing.T) { govHandler := NewHandler(keeper) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{25, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{25, 6, 7}) initTotalPower := keeper.ds.GetValidatorSet().TotalPower(ctx) - val0Initial := keeper.ds.GetValidatorSet().Validator(ctx, addrs[0]).GetPower().Quo(initTotalPower) - val1Initial := keeper.ds.GetValidatorSet().Validator(ctx, addrs[1]).GetPower().Quo(initTotalPower) - val2Initial := keeper.ds.GetValidatorSet().Validator(ctx, addrs[2]).GetPower().Quo(initTotalPower) + val0Initial := keeper.ds.GetValidatorSet().Validator(ctx, sdk.ValAddress(addrs[0])).GetPower().Quo(initTotalPower) + val1Initial := keeper.ds.GetValidatorSet().Validator(ctx, sdk.ValAddress(addrs[1])).GetPower().Quo(initTotalPower) + val2Initial := keeper.ds.GetValidatorSet().Validator(ctx, sdk.ValAddress(addrs[2])).GetPower().Quo(initTotalPower) newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin("steak", 15)}) @@ -209,9 +214,9 @@ func TestSlashing(t *testing.T) { require.False(t, keeper.GetProposal(ctx, proposalID).GetTallyResult().Equals(EmptyTallyResult())) endTotalPower := keeper.ds.GetValidatorSet().TotalPower(ctx) - val0End := keeper.ds.GetValidatorSet().Validator(ctx, addrs[0]).GetPower().Quo(endTotalPower) - val1End := keeper.ds.GetValidatorSet().Validator(ctx, addrs[1]).GetPower().Quo(endTotalPower) - val2End := keeper.ds.GetValidatorSet().Validator(ctx, addrs[2]).GetPower().Quo(endTotalPower) + val0End := keeper.ds.GetValidatorSet().Validator(ctx, sdk.ValAddress(addrs[0])).GetPower().Quo(endTotalPower) + val1End := keeper.ds.GetValidatorSet().Validator(ctx, sdk.ValAddress(addrs[1])).GetPower().Quo(endTotalPower) + val2End := keeper.ds.GetValidatorSet().Validator(ctx, sdk.ValAddress(addrs[2])).GetPower().Quo(endTotalPower) require.True(t, val0End.GTE(val0Initial)) require.True(t, val1End.LT(val1Initial)) diff --git a/x/gov/handler.go b/x/gov/handler.go index 4fa3887296b9..6424bb0a1056 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -114,8 +114,8 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags) { resTags.AppendTag(tags.Action, tags.ActionProposalDropped) resTags.AppendTag(tags.ProposalID, proposalIDBytes) - logger.Info("Proposal %d - \"%s\" - didn't mean minimum deposit (had only %s), deleted", - inactiveProposal.GetProposalID(), inactiveProposal.GetTitle(), inactiveProposal.GetTotalDeposit()) + logger.Info(fmt.Sprintf("Proposal %d - \"%s\" - didn't mean minimum deposit (had only %s), deleted", + inactiveProposal.GetProposalID(), inactiveProposal.GetTitle(), inactiveProposal.GetTotalDeposit())) } // Check if earliest Active Proposal ended voting period yet @@ -143,8 +143,8 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags) { activeProposal.SetTallyResult(tallyResults) keeper.SetProposal(ctx, activeProposal) - logger.Info("Proposal %d - \"%s\" - tallied, passed: %v", - activeProposal.GetProposalID(), activeProposal.GetTitle(), passes) + logger.Info(fmt.Sprintf("Proposal %d - \"%s\" - tallied, passed: %v", + activeProposal.GetProposalID(), activeProposal.GetTitle(), passes)) for _, valAddr := range nonVotingVals { val := keeper.ds.GetValidatorSet().Validator(ctx, valAddr) diff --git a/x/gov/tally.go b/x/gov/tally.go index b6c9ee2a1409..a756eaf92645 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -6,14 +6,14 @@ import ( // validatorGovInfo used for tallying type validatorGovInfo struct { - Address sdk.AccAddress // sdk.AccAddress of the validator owner + Address sdk.ValAddress // address of the validator operator Power sdk.Dec // Power of a Validator DelegatorShares sdk.Dec // Total outstanding delegator shares Minus sdk.Dec // Minus of validator, used to compute validator's voting power Vote VoteOption // Vote of the validator } -func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tallyResults TallyResult, nonVoting []sdk.AccAddress) { +func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tallyResults TallyResult, nonVoting []sdk.ValAddress) { results := make(map[VoteOption]sdk.Dec) results[OptionYes] = sdk.ZeroDec() results[OptionAbstain] = sdk.ZeroDec() @@ -43,15 +43,18 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall // if validator, just record it in the map // if delegator tally voting power - if val, ok := currValidators[vote.Voter.String()]; ok { + valAddrStr := sdk.ValAddress(vote.Voter).String() + if val, ok := currValidators[valAddrStr]; ok { val.Vote = vote.Option - currValidators[vote.Voter.String()] = val + currValidators[valAddrStr] = val } else { keeper.ds.IterateDelegations(ctx, vote.Voter, func(index int64, delegation sdk.Delegation) (stop bool) { - if val, ok := currValidators[delegation.GetValidator().String()]; ok { + valAddrStr := delegation.GetValidator().String() + + if val, ok := currValidators[valAddrStr]; ok { val.Minus = val.Minus.Add(delegation.GetBondShares()) - currValidators[delegation.GetValidator().String()] = val + currValidators[valAddrStr] = val delegatorShare := delegation.GetBondShares().Quo(val.DelegatorShares) votingPower := val.Power.Mul(delegatorShare) @@ -59,6 +62,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall results[vote.Option] = results[vote.Option].Add(votingPower) totalVotingPower = totalVotingPower.Add(votingPower) } + return false }) } @@ -66,13 +70,15 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall keeper.deleteVote(ctx, vote.ProposalID, vote.Voter) } - // Iterate over the validators again to tally their voting power and see who didn't vote - nonVoting = []sdk.AccAddress{} + // iterate over the validators again to tally their voting power and see + // who didn't vote + nonVoting = []sdk.ValAddress{} for _, val := range currValidators { if val.Vote == OptionEmpty { nonVoting = append(nonVoting, val.Address) continue } + sharesAfterMinus := val.DelegatorShares.Sub(val.Minus) percentAfterMinus := sharesAfterMinus.Quo(val.DelegatorShares) votingPower := val.Power.Mul(percentAfterMinus) @@ -104,7 +110,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall } // If more than 1/2 of non-abstaining voters vote No, proposal fails - SortAddresses(nonVoting) + SortValAddresses(nonVoting) return false, tallyResults, nonVoting } diff --git a/x/gov/tally_test.go b/x/gov/tally_test.go index 157f594401fa..24740731f05d 100644 --- a/x/gov/tally_test.go +++ b/x/gov/tally_test.go @@ -17,7 +17,7 @@ var ( pubkeys = []crypto.PubKey{ed25519.GenPrivKey().PubKey(), ed25519.GenPrivKey().PubKey(), ed25519.GenPrivKey().PubKey()} ) -func createValidators(t *testing.T, stakeHandler sdk.Handler, ctx sdk.Context, addrs []sdk.AccAddress, coinAmt []int64) { +func createValidators(t *testing.T, stakeHandler sdk.Handler, ctx sdk.Context, addrs []sdk.ValAddress, coinAmt []int64) { require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") dummyDescription := stake.NewDescription("T", "E", "S", "T") for i := 0; i < len(addrs); i++ { @@ -33,7 +33,12 @@ func TestTallyNoOneVotes(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:2], []int64{5, 5}) + valAddrs := make([]sdk.ValAddress, len(addrs[:2])) + for i, addr := range addrs[:2] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 5}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -52,7 +57,12 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:2], []int64{5, 5}) + valAddrs := make([]sdk.ValAddress, len(addrs[:2])) + for i, addr := range addrs[:2] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 5}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -76,7 +86,12 @@ func TestTallyOnlyValidators51No(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:2], []int64{5, 6}) + valAddrs := make([]sdk.ValAddress, len(addrs[:2])) + for i, addr := range addrs[:2] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -99,7 +114,12 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{6, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -125,7 +145,12 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{6, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -151,7 +176,12 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{6, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -177,7 +207,12 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{6, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -203,7 +238,12 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{6, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -219,7 +259,7 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { require.False(t, passes) require.Equal(t, 1, len(nonVoting)) - require.Equal(t, addrs[0], nonVoting[0]) + require.Equal(t, sdk.ValAddress(addrs[0]), nonVoting[0]) require.False(t, tallyResults.Equals(EmptyTallyResult())) } @@ -229,9 +269,14 @@ func TestTallyDelgatorOverride(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{5, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6, 7}) - delegator1Msg := stake.NewMsgDelegate(addrs[3], addrs[2], sdk.NewInt64Coin("steak", 30)) + delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin("steak", 30)) stakeHandler(ctx, delegator1Msg) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -260,9 +305,14 @@ func TestTallyDelgatorInherit(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{5, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6, 7}) - delegator1Msg := stake.NewMsgDelegate(addrs[3], addrs[2], sdk.NewInt64Coin("steak", 30)) + delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin("steak", 30)) stakeHandler(ctx, delegator1Msg) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -290,11 +340,16 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{5, 6, 7}) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6, 7}) - delegator1Msg := stake.NewMsgDelegate(addrs[3], addrs[2], sdk.NewInt64Coin("steak", 10)) + delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin("steak", 10)) stakeHandler(ctx, delegator1Msg) - delegator1Msg2 := stake.NewMsgDelegate(addrs[3], addrs[1], sdk.NewInt64Coin("steak", 10)) + delegator1Msg2 := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin("steak", 10)) stakeHandler(ctx, delegator1Msg2) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -324,16 +379,26 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { stakeHandler := stake.NewHandler(sk) dummyDescription := stake.NewDescription("T", "E", "S", "T") - val1CreateMsg := stake.NewMsgCreateValidator(addrs[0], ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin("steak", 25), dummyDescription) + + val1CreateMsg := stake.NewMsgCreateValidator( + sdk.ValAddress(addrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin("steak", 25), dummyDescription, + ) stakeHandler(ctx, val1CreateMsg) - val2CreateMsg := stake.NewMsgCreateValidator(addrs[1], ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin("steak", 6), dummyDescription) + + val2CreateMsg := stake.NewMsgCreateValidator( + sdk.ValAddress(addrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin("steak", 6), dummyDescription, + ) stakeHandler(ctx, val2CreateMsg) - val3CreateMsg := stake.NewMsgCreateValidator(addrs[2], ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin("steak", 7), dummyDescription) + + val3CreateMsg := stake.NewMsgCreateValidator( + sdk.ValAddress(addrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin("steak", 7), dummyDescription, + ) stakeHandler(ctx, val3CreateMsg) - delegator1Msg := stake.NewMsgDelegate(addrs[3], addrs[2], sdk.NewInt64Coin("steak", 10)) + delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin("steak", 10)) stakeHandler(ctx, delegator1Msg) - delegator1Msg2 := stake.NewMsgDelegate(addrs[3], addrs[1], sdk.NewInt64Coin("steak", 10)) + + delegator1Msg2 := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin("steak", 10)) stakeHandler(ctx, delegator1Msg2) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -360,13 +425,20 @@ func TestTallyJailedValidator(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) stakeHandler := stake.NewHandler(sk) - createValidators(t, stakeHandler, ctx, addrs[:3], []int64{25, 6, 7}) - delegator1Msg := stake.NewMsgDelegate(addrs[3], addrs[2], sdk.NewInt64Coin("steak", 10)) + valAddrs := make([]sdk.ValAddress, len(addrs[:3])) + for i, addr := range addrs[:3] { + valAddrs[i] = sdk.ValAddress(addr) + } + + createValidators(t, stakeHandler, ctx, valAddrs, []int64{25, 6, 7}) + + delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin("steak", 10)) stakeHandler(ctx, delegator1Msg) - delegator1Msg2 := stake.NewMsgDelegate(addrs[3], addrs[1], sdk.NewInt64Coin("steak", 10)) + + delegator1Msg2 := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin("steak", 10)) stakeHandler(ctx, delegator1Msg2) - val2, found := sk.GetValidator(ctx, addrs[1]) + val2, found := sk.GetValidator(ctx, sdk.ValAddress(addrs[1])) require.True(t, found) sk.Jail(ctx, val2.PubKey) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 5e7977b50c34..502cfbbf0498 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -77,6 +77,20 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk } } +// TODO: Remove once address interface has been implemented (ref: #2186) +func SortValAddresses(addrs []sdk.ValAddress) { + var byteAddrs [][]byte + for _, addr := range addrs { + byteAddrs = append(byteAddrs, addr.Bytes()) + } + + SortByteArrays(byteAddrs) + + for i, byteAddr := range byteAddrs { + addrs[i] = byteAddr + } +} + // Sorts Addresses func SortAddresses(addrs []sdk.AccAddress) { var byteAddrs [][]byte diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 86d350a84b92..f9ec0833fa15 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -73,7 +73,7 @@ func getInitChainer(mapp *mock.App, keeper stake.Keeper) sdk.InitChainer { func checkValidator(t *testing.T, mapp *mock.App, keeper stake.Keeper, addr sdk.AccAddress, expFound bool) stake.Validator { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) - validator, found := keeper.GetValidator(ctxCheck, addr1) + validator, found := keeper.GetValidator(ctxCheck, sdk.ValAddress(addr1)) require.Equal(t, expFound, found) return validator } @@ -100,17 +100,17 @@ func TestSlashingMsgs(t *testing.T) { mock.SetGenesis(mapp, accs) description := stake.NewDescription("foo_moniker", "", "", "") createValidatorMsg := stake.NewMsgCreateValidator( - addr1, priv1.PubKey(), bondCoin, description, + sdk.ValAddress(addr1), priv1.PubKey(), bondCoin, description, ) mock.SignCheckDeliver(t, mapp.BaseApp, []sdk.Msg{createValidatorMsg}, []int64{0}, []int64{0}, true, priv1) mock.CheckBalance(t, mapp, addr1, sdk.Coins{genCoin.Minus(bondCoin)}) mapp.BeginBlock(abci.RequestBeginBlock{}) validator := checkValidator(t, mapp, stakeKeeper, addr1, true) - require.Equal(t, addr1, validator.Operator) + require.Equal(t, sdk.ValAddress(addr1), validator.Operator) require.Equal(t, sdk.Bonded, validator.Status) require.True(sdk.DecEq(t, sdk.NewDec(10), validator.BondedTokens())) - unjailMsg := MsgUnjail{ValidatorAddr: sdk.AccAddress(validator.PubKey.Address())} + unjailMsg := MsgUnjail{ValidatorAddr: sdk.ValAddress(validator.PubKey.Address())} // no signing info yet checkValidatorSigningInfo(t, mapp, keeper, sdk.ValAddress(addr1), false) diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index 0901eef97085..9f6d834dda06 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -20,7 +20,7 @@ func GetCmdQuerySigningInfo(storeName string, cdc *wire.Codec) *cobra.Command { Short: "Query a validator's signing information", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - pk, err := sdk.GetValPubKeyBech32(args[0]) + pk, err := sdk.GetConsPubKeyBech32(args[0]) if err != nil { return err } diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index 2fdd65c6c3ff..4234e52ce86c 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -27,12 +27,12 @@ func GetCmdUnjail(cdc *wire.Codec) *cobra.Command { WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - validatorAddr, err := cliCtx.GetFromAddress() + valAddr, err := cliCtx.GetFromAddress() if err != nil { return err } - msg := slashing.NewMsgUnjail(validatorAddr) + msg := slashing.NewMsgUnjail(sdk.ValAddress(valAddr)) return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) }, diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index 5509ed1a8d4e..291679375b06 100644 --- a/x/slashing/client/rest/query.go +++ b/x/slashing/client/rest/query.go @@ -23,7 +23,7 @@ func signingInfoHandlerFn(cliCtx context.CLIContext, storeName string, cdc *wire return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - pk, err := sdk.GetValPubKeyBech32(vars["validator"]) + pk, err := sdk.GetConsPubKeyBech32(vars["validator"]) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index 26412ebc0028..c7efdc97e95b 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -56,13 +56,13 @@ func unjailRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx context.CLI return } - validatorAddr, err := sdk.AccAddressFromBech32(m.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(m.ValidatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - if !bytes.Equal(info.GetPubKey().Address(), validatorAddr) { + if !bytes.Equal(info.GetPubKey().Address(), valAddr) { utils.WriteErrorResponse(&w, http.StatusUnauthorized, "Must use own validator address") return } @@ -75,7 +75,7 @@ func unjailRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx context.CLI Gas: m.Gas, } - msg := slashing.NewMsgUnjail(validatorAddr) + msg := slashing.NewMsgUnjail(valAddr) if m.Gas == 0 { newCtx, err := utils.EnrichCtxWithGas(txCtx, cliCtx, m.LocalAccountName, m.Password, []sdk.Msg{msg}) diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index 4408d3c09d36..8e3b719f4986 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -15,15 +15,15 @@ func TestCannotUnjailUnlessJailed(t *testing.T) { slh := NewHandler(keeper) amtInt := int64(100) addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) - msg := newTestMsgCreateValidator(addr, val, amt) + msg := newTestMsgCreateValidator(sdk.ValAddress(addr), val, amt) got := stake.NewHandler(sk)(ctx, msg) require.True(t, got.IsOK()) stake.EndBlocker(ctx, sk) require.Equal(t, ck.GetCoins(ctx, addr), sdk.Coins{{sk.GetParams(ctx).BondDenom, initCoins.Sub(amt)}}) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, sdk.ValAddress(addr)).GetPower())) // assert non-jailed validator can't be unjailed - got = slh(ctx, NewMsgUnjail(addr)) + got = slh(ctx, NewMsgUnjail(sdk.ValAddress(addr))) require.False(t, got.IsOK(), "allowed unjail of non-jailed validator") require.Equal(t, sdk.ToABCICode(DefaultCodespace, CodeValidatorNotJailed), got.Code) } diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index 808c82014e16..3bdb043a825f 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -26,12 +26,12 @@ func TestHandleDoubleSign(t *testing.T) { ctx, ck, sk, _, keeper := createTestInput(t) amtInt := int64(100) addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) - got := stake.NewHandler(sk)(ctx, newTestMsgCreateValidator(addr, val, amt)) + got := stake.NewHandler(sk)(ctx, newTestMsgCreateValidator(sdk.ValAddress(addr), val, amt)) require.True(t, got.IsOK()) validatorUpdates := stake.EndBlocker(ctx, sk) keeper.AddValidators(ctx, validatorUpdates) require.Equal(t, ck.GetCoins(ctx, addr), sdk.Coins{{sk.GetParams(ctx).BondDenom, initCoins.Sub(amt)}}) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, sdk.ValAddress(addr)).GetPower())) // handle a signature to set signing info keeper.handleValidatorSignature(ctx, val.Address(), amtInt, true) @@ -40,16 +40,22 @@ func TestHandleDoubleSign(t *testing.T) { keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), amtInt) // should be jailed - require.True(t, sk.Validator(ctx, addr).GetJailed()) + require.True(t, sk.Validator(ctx, sdk.ValAddress(addr)).GetJailed()) // unjail to measure power sk.Unjail(ctx, val) // power should be reduced - require.Equal(t, sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))), sk.Validator(ctx, addr).GetPower()) + require.Equal( + t, sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))), + sk.Validator(ctx, sdk.ValAddress(addr)).GetPower(), + ) ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.MaxEvidenceAge(ctx))}) // double sign past max age keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), amtInt) - require.Equal(t, sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))), sk.Validator(ctx, addr).GetPower()) + require.Equal( + t, sdk.NewDecFromInt(amt).Mul(sdk.NewDec(19).Quo(sdk.NewDec(20))), + sk.Validator(ctx, sdk.ValAddress(addr)).GetPower(), + ) } // Test a validator through uptime, downtime, revocation, @@ -62,12 +68,12 @@ func TestHandleAbsentValidator(t *testing.T) { addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) sh := stake.NewHandler(sk) slh := NewHandler(keeper) - got := sh(ctx, newTestMsgCreateValidator(addr, val, amt)) + got := sh(ctx, newTestMsgCreateValidator(sdk.ValAddress(addr), val, amt)) require.True(t, got.IsOK()) validatorUpdates := stake.EndBlocker(ctx, sk) keeper.AddValidators(ctx, validatorUpdates) require.Equal(t, ck.GetCoins(ctx, addr), sdk.Coins{{sk.GetParams(ctx).BondDenom, initCoins.Sub(amt)}}) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, sdk.ValAddress(addr)).GetPower())) info, found := keeper.getValidatorSigningInfo(ctx, sdk.ValAddress(val.Address())) require.False(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -117,12 +123,12 @@ func TestHandleAbsentValidator(t *testing.T) { require.Equal(t, sdk.Unbonded, validator.GetStatus()) // unrevocation should fail prior to jail expiration - got = slh(ctx, NewMsgUnjail(addr)) + got = slh(ctx, NewMsgUnjail(sdk.ValAddress(addr))) require.False(t, got.IsOK()) // unrevocation should succeed after jail expiration ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.DowntimeUnbondDuration(ctx))}) - got = slh(ctx, NewMsgUnjail(addr)) + got = slh(ctx, NewMsgUnjail(sdk.ValAddress(addr))) require.True(t, got.IsOK()) // validator should be rebonded now @@ -172,12 +178,12 @@ func TestHandleNewValidator(t *testing.T) { ctx, ck, sk, _, keeper := createTestInput(t) addr, val, amt := addrs[0], pks[0], int64(100) sh := stake.NewHandler(sk) - got := sh(ctx, newTestMsgCreateValidator(addr, val, sdk.NewInt(amt))) + got := sh(ctx, newTestMsgCreateValidator(sdk.ValAddress(addr), val, sdk.NewInt(amt))) require.True(t, got.IsOK()) validatorUpdates := stake.EndBlocker(ctx, sk) keeper.AddValidators(ctx, validatorUpdates) require.Equal(t, ck.GetCoins(ctx, addr), sdk.Coins{{sk.GetParams(ctx).BondDenom, initCoins.SubRaw(amt)}}) - require.Equal(t, sdk.NewDec(amt), sk.Validator(ctx, addr).GetPower()) + require.Equal(t, sdk.NewDec(amt), sk.Validator(ctx, sdk.ValAddress(addr)).GetPower()) // 1000 first blocks not a validator ctx = ctx.WithBlockHeight(keeper.SignedBlocksWindow(ctx) + 1) @@ -210,7 +216,7 @@ func TestHandleAlreadyJailed(t *testing.T) { amtInt := int64(100) addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) sh := stake.NewHandler(sk) - got := sh(ctx, newTestMsgCreateValidator(addr, val, amt)) + got := sh(ctx, newTestMsgCreateValidator(sdk.ValAddress(addr), val, amt)) require.True(t, got.IsOK()) validatorUpdates := stake.EndBlocker(ctx, sk) keeper.AddValidators(ctx, validatorUpdates) diff --git a/x/slashing/msg.go b/x/slashing/msg.go index e22eca7bdd9e..7791012185fd 100644 --- a/x/slashing/msg.go +++ b/x/slashing/msg.go @@ -15,18 +15,20 @@ var _ sdk.Msg = &MsgUnjail{} // MsgUnjail - struct for unjailing jailed validator type MsgUnjail struct { - ValidatorAddr sdk.AccAddress `json:"address"` // address of the validator owner + ValidatorAddr sdk.ValAddress `json:"address"` // address of the validator owner } -func NewMsgUnjail(validatorAddr sdk.AccAddress) MsgUnjail { +func NewMsgUnjail(validatorAddr sdk.ValAddress) MsgUnjail { return MsgUnjail{ ValidatorAddr: validatorAddr, } } //nolint -func (msg MsgUnjail) Type() string { return MsgType } -func (msg MsgUnjail) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.ValidatorAddr} } +func (msg MsgUnjail) Type() string { return MsgType } +func (msg MsgUnjail) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{sdk.AccAddress(msg.ValidatorAddr)} +} // get the bytes for the message signer to sign on func (msg MsgUnjail) GetSignBytes() []byte { diff --git a/x/slashing/msg_test.go b/x/slashing/msg_test.go index ef2e673c86c8..ff8619041e79 100644 --- a/x/slashing/msg_test.go +++ b/x/slashing/msg_test.go @@ -10,7 +10,7 @@ import ( func TestMsgUnjailGetSignBytes(t *testing.T) { addr := sdk.AccAddress("abcd") - msg := NewMsgUnjail(addr) + msg := NewMsgUnjail(sdk.ValAddress(addr)) bytes := msg.GetSignBytes() - require.Equal(t, string(bytes), `{"address":"cosmosaccaddr1v93xxeqhyqz5v"}`) + require.Equal(t, string(bytes), `{"address":"cosmosval1v93xxeq7xkcrf"}`) } diff --git a/x/slashing/simulation/msgs.go b/x/slashing/simulation/msgs.go index e4900889e3a0..dc7f63ba641c 100644 --- a/x/slashing/simulation/msgs.go +++ b/x/slashing/simulation/msgs.go @@ -19,7 +19,7 @@ import ( func SimulateMsgUnjail(k slashing.Keeper) simulation.Operation { return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, fOp []simulation.FutureOperation, err sdk.Error) { key := simulation.RandomKey(r, keys) - address := sdk.AccAddress(key.PubKey().Address()) + address := sdk.ValAddress(key.PubKey().Address()) msg := slashing.NewMsgUnjail(address) require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) ctx, write := ctx.CacheContext() diff --git a/x/slashing/test_common.go b/x/slashing/test_common.go index 50c501d7e3bd..1053823786c2 100644 --- a/x/slashing/test_common.go +++ b/x/slashing/test_common.go @@ -99,10 +99,10 @@ func testAddr(addr string) sdk.AccAddress { return res } -func newTestMsgCreateValidator(address sdk.AccAddress, pubKey crypto.PubKey, amt sdk.Int) stake.MsgCreateValidator { +func newTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) stake.MsgCreateValidator { return stake.MsgCreateValidator{ Description: stake.Description{}, - DelegatorAddr: address, + DelegatorAddr: sdk.AccAddress(address), ValidatorAddr: address, PubKey: pubKey, Delegation: sdk.Coin{"steak", amt}, diff --git a/x/slashing/tick_test.go b/x/slashing/tick_test.go index 78d269549462..9eb956e6710a 100644 --- a/x/slashing/tick_test.go +++ b/x/slashing/tick_test.go @@ -17,12 +17,12 @@ func TestBeginBlocker(t *testing.T) { addr, pk, amt := addrs[2], pks[2], sdk.NewInt(100) // bond the validator - got := stake.NewHandler(sk)(ctx, newTestMsgCreateValidator(addr, pk, amt)) + got := stake.NewHandler(sk)(ctx, newTestMsgCreateValidator(sdk.ValAddress(addr), pk, amt)) require.True(t, got.IsOK()) validatorUpdates := stake.EndBlocker(ctx, sk) keeper.AddValidators(ctx, validatorUpdates) require.Equal(t, ck.GetCoins(ctx, addr), sdk.Coins{{sk.GetParams(ctx).BondDenom, initCoins.Sub(amt)}}) - require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + require.True(t, sdk.NewDecFromInt(amt).Equal(sk.Validator(ctx, sdk.ValAddress(addr)).GetPower())) val := abci.Validator{ Address: pk.Address(), diff --git a/x/stake/app_test.go b/x/stake/app_test.go index 65c64fdef222..587e90b46595 100644 --- a/x/stake/app_test.go +++ b/x/stake/app_test.go @@ -79,7 +79,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper) sdk.InitChainer { //__________________________________________________________________________________________ func checkValidator(t *testing.T, mapp *mock.App, keeper Keeper, - addr sdk.AccAddress, expFound bool) Validator { + addr sdk.ValAddress, expFound bool) Validator { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) validator, found := keeper.GetValidator(ctxCheck, addr) @@ -89,8 +89,8 @@ func checkValidator(t *testing.T, mapp *mock.App, keeper Keeper, } func checkDelegation( - t *testing.T, mapp *mock.App, keeper Keeper, delegatorAddr, - validatorAddr sdk.AccAddress, expFound bool, expShares sdk.Dec, + t *testing.T, mapp *mock.App, keeper Keeper, delegatorAddr sdk.AccAddress, + validatorAddr sdk.ValAddress, expFound bool, expShares sdk.Dec, ) { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) @@ -128,55 +128,57 @@ func TestStakeMsgs(t *testing.T) { // create validator description := NewDescription("foo_moniker", "", "", "") createValidatorMsg := NewMsgCreateValidator( - addr1, priv1.PubKey(), bondCoin, description, + sdk.ValAddress(addr1), priv1.PubKey(), bondCoin, description, ) mock.SignCheckDeliver(t, mApp.BaseApp, []sdk.Msg{createValidatorMsg}, []int64{0}, []int64{0}, true, priv1) mock.CheckBalance(t, mApp, addr1, sdk.Coins{genCoin.Minus(bondCoin)}) mApp.BeginBlock(abci.RequestBeginBlock{}) - validator := checkValidator(t, mApp, keeper, addr1, true) - require.Equal(t, addr1, validator.Operator) + validator := checkValidator(t, mApp, keeper, sdk.ValAddress(addr1), true) + require.Equal(t, sdk.ValAddress(addr1), validator.Operator) require.Equal(t, sdk.Bonded, validator.Status) require.True(sdk.DecEq(t, sdk.NewDec(10), validator.BondedTokens())) // addr1 create validator on behalf of addr2 - createValidatorMsgOnBehalfOf := NewMsgCreateValidatorOnBehalfOf(addr1, addr2, priv2.PubKey(), bondCoin, description) + createValidatorMsgOnBehalfOf := NewMsgCreateValidatorOnBehalfOf( + addr1, sdk.ValAddress(addr2), priv2.PubKey(), bondCoin, description, + ) mock.SignCheckDeliver(t, mApp.BaseApp, []sdk.Msg{createValidatorMsgOnBehalfOf}, []int64{0, 1}, []int64{1, 0}, true, priv1, priv2) mock.CheckBalance(t, mApp, addr1, sdk.Coins{genCoin.Minus(bondCoin).Minus(bondCoin)}) mApp.BeginBlock(abci.RequestBeginBlock{}) - validator = checkValidator(t, mApp, keeper, addr2, true) - require.Equal(t, addr2, validator.Operator) + validator = checkValidator(t, mApp, keeper, sdk.ValAddress(addr2), true) + require.Equal(t, sdk.ValAddress(addr2), validator.Operator) require.Equal(t, sdk.Bonded, validator.Status) require.True(sdk.DecEq(t, sdk.NewDec(10), validator.Tokens)) // check the bond that should have been created as well - checkDelegation(t, mApp, keeper, addr1, addr1, true, sdk.NewDec(10)) + checkDelegation(t, mApp, keeper, addr1, sdk.ValAddress(addr1), true, sdk.NewDec(10)) // edit the validator description = NewDescription("bar_moniker", "", "", "") - editValidatorMsg := NewMsgEditValidator(addr1, description) + editValidatorMsg := NewMsgEditValidator(sdk.ValAddress(addr1), description) mock.SignCheckDeliver(t, mApp.BaseApp, []sdk.Msg{editValidatorMsg}, []int64{0}, []int64{2}, true, priv1) - validator = checkValidator(t, mApp, keeper, addr1, true) + validator = checkValidator(t, mApp, keeper, sdk.ValAddress(addr1), true) require.Equal(t, description, validator.Description) // delegate mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin}) - delegateMsg := NewMsgDelegate(addr2, addr1, bondCoin) + delegateMsg := NewMsgDelegate(addr2, sdk.ValAddress(addr1), bondCoin) mock.SignCheckDeliver(t, mApp.BaseApp, []sdk.Msg{delegateMsg}, []int64{1}, []int64{1}, true, priv2) mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin.Minus(bondCoin)}) - checkDelegation(t, mApp, keeper, addr2, addr1, true, sdk.NewDec(10)) + checkDelegation(t, mApp, keeper, addr2, sdk.ValAddress(addr1), true, sdk.NewDec(10)) // begin unbonding - beginUnbondingMsg := NewMsgBeginUnbonding(addr2, addr1, sdk.NewDec(10)) + beginUnbondingMsg := NewMsgBeginUnbonding(addr2, sdk.ValAddress(addr1), sdk.NewDec(10)) mock.SignCheckDeliver(t, mApp.BaseApp, []sdk.Msg{beginUnbondingMsg}, []int64{1}, []int64{2}, true, priv2) // delegation should exist anymore - checkDelegation(t, mApp, keeper, addr2, addr1, false, sdk.Dec{}) + checkDelegation(t, mApp, keeper, addr2, sdk.ValAddress(addr1), false, sdk.Dec{}) // balance should be the same because bonding not yet complete mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin.Minus(bondCoin)}) diff --git a/x/stake/client/cli/query.go b/x/stake/client/cli/query.go index d58ea3938105..9a017fb59081 100644 --- a/x/stake/client/cli/query.go +++ b/x/stake/client/cli/query.go @@ -17,11 +17,11 @@ import ( // GetCmdQueryValidator implements the validator query command. func GetCmdQueryValidator(storeName string, cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "validator [owner-addr]", + Use: "validator [operator-addr]", Short: "Query a validator", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - addr, err := sdk.AccAddressFromBech32(args[0]) + addr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } @@ -120,7 +120,7 @@ func GetCmdQueryDelegation(storeName string, cdc *wire.Codec) *cobra.Command { Use: "delegation", Short: "Query a delegation based on address and validator address", RunE: func(cmd *cobra.Command, args []string) error { - valAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } @@ -222,7 +222,7 @@ func GetCmdQueryUnbondingDelegation(storeName string, cdc *wire.Codec) *cobra.Co Use: "unbonding-delegation", Short: "Query an unbonding-delegation record based on delegator and validator address", RunE: func(cmd *cobra.Command, args []string) error { - valAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } @@ -321,12 +321,12 @@ func GetCmdQueryRedelegation(storeName string, cdc *wire.Codec) *cobra.Command { Use: "redelegation", Short: "Query a redelegation record based on delegator and a source and destination validator address", RunE: func(cmd *cobra.Command, args []string) error { - valSrcAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) + valSrcAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) if err != nil { return err } - valDstAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) + valDstAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) if err != nil { return err } diff --git a/x/stake/client/cli/tx.go b/x/stake/client/cli/tx.go index 9f04f2ed2d38..defc2b1e23c9 100644 --- a/x/stake/client/cli/tx.go +++ b/x/stake/client/cli/tx.go @@ -40,7 +40,7 @@ func GetCmdCreateValidator(cdc *wire.Codec) *cobra.Command { return err } - validatorAddr, err := cliCtx.GetFromAddress() + valAddr, err := cliCtx.GetFromAddress() if err != nil { return err } @@ -50,7 +50,7 @@ func GetCmdCreateValidator(cdc *wire.Codec) *cobra.Command { return fmt.Errorf("must use --pubkey flag") } - pk, err := sdk.GetValPubKeyBech32(pkStr) + pk, err := sdk.GetConsPubKeyBech32(pkStr) if err != nil { return err } @@ -68,14 +68,14 @@ func GetCmdCreateValidator(cdc *wire.Codec) *cobra.Command { var msg sdk.Msg if viper.GetString(FlagAddressDelegator) != "" { - delegatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressDelegator)) + delAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressDelegator)) if err != nil { return err } - msg = stake.NewMsgCreateValidatorOnBehalfOf(delegatorAddr, validatorAddr, pk, amount, description) + msg = stake.NewMsgCreateValidatorOnBehalfOf(delAddr, sdk.ValAddress(valAddr), pk, amount, description) } else { - msg = stake.NewMsgCreateValidator(validatorAddr, pk, amount, description) + msg = stake.NewMsgCreateValidator(sdk.ValAddress(valAddr), pk, amount, description) } // build and sign the transaction, then broadcast to Tendermint @@ -103,7 +103,7 @@ func GetCmdEditValidator(cdc *wire.Codec) *cobra.Command { WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - validatorAddr, err := cliCtx.GetFromAddress() + valAddr, err := cliCtx.GetFromAddress() if err != nil { return err } @@ -114,7 +114,8 @@ func GetCmdEditValidator(cdc *wire.Codec) *cobra.Command { Website: viper.GetString(FlagWebsite), Details: viper.GetString(FlagDetails), } - msg := stake.NewMsgEditValidator(validatorAddr, description) + + msg := stake.NewMsgEditValidator(sdk.ValAddress(valAddr), description) // build and sign the transaction, then broadcast to Tendermint return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) @@ -143,17 +144,17 @@ func GetCmdDelegate(cdc *wire.Codec) *cobra.Command { return err } - delegatorAddr, err := cliCtx.GetFromAddress() + delAddr, err := cliCtx.GetFromAddress() if err != nil { return err } - validatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } - msg := stake.NewMsgDelegate(delegatorAddr, validatorAddr, amount) + msg := stake.NewMsgDelegate(delAddr, valAddr, amount) // build and sign the transaction, then broadcast to Tendermint return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) @@ -195,17 +196,18 @@ func GetCmdBeginRedelegate(storeName string, cdc *wire.Codec) *cobra.Command { WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) var err error - delegatorAddr, err := cliCtx.GetFromAddress() + + delAddr, err := cliCtx.GetFromAddress() if err != nil { return err } - validatorSrcAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) + valSrcAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) if err != nil { return err } - validatorDstAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) + valDstAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) if err != nil { return err } @@ -215,13 +217,13 @@ func GetCmdBeginRedelegate(storeName string, cdc *wire.Codec) *cobra.Command { sharesPercentStr := viper.GetString(FlagSharesPercent) sharesAmount, err := getShares( storeName, cdc, sharesAmountStr, sharesPercentStr, - delegatorAddr, validatorSrcAddr, + delAddr, valSrcAddr, ) if err != nil { return err } - msg := stake.NewMsgBeginRedelegate(delegatorAddr, validatorSrcAddr, validatorDstAddr, sharesAmount) + msg := stake.NewMsgBeginRedelegate(delAddr, valSrcAddr, valDstAddr, sharesAmount) // build and sign the transaction, then broadcast to Tendermint return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) @@ -238,7 +240,7 @@ func GetCmdBeginRedelegate(storeName string, cdc *wire.Codec) *cobra.Command { // TODO: Make this pass gocyclo linting func getShares( storeName string, cdc *wire.Codec, sharesAmountStr, - sharesPercentStr string, delegatorAddr, validatorAddr sdk.AccAddress, + sharesPercentStr string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, ) (sharesAmount sdk.Dec, err error) { switch { case sharesAmountStr != "" && sharesPercentStr != "": @@ -264,7 +266,7 @@ func getShares( } // make a query to get the existing delegation shares - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) + key := stake.GetDelegationKey(delAddr, valAddr) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) @@ -294,22 +296,22 @@ func GetCmdCompleteRedelegate(cdc *wire.Codec) *cobra.Command { WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - delegatorAddr, err := cliCtx.GetFromAddress() + delAddr, err := cliCtx.GetFromAddress() if err != nil { return err } - validatorSrcAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) + valSrcAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) if err != nil { return err } - validatorDstAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) + valDstAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) if err != nil { return err } - msg := stake.NewMsgCompleteRedelegate(delegatorAddr, validatorSrcAddr, validatorDstAddr) + msg := stake.NewMsgCompleteRedelegate(delAddr, valSrcAddr, valDstAddr) // build and sign the transaction, then broadcast to Tendermint return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) @@ -349,12 +351,12 @@ func GetCmdBeginUnbonding(storeName string, cdc *wire.Codec) *cobra.Command { WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - delegatorAddr, err := cliCtx.GetFromAddress() + delAddr, err := cliCtx.GetFromAddress() if err != nil { return err } - validatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } @@ -364,13 +366,13 @@ func GetCmdBeginUnbonding(storeName string, cdc *wire.Codec) *cobra.Command { sharesPercentStr := viper.GetString(FlagSharesPercent) sharesAmount, err := getShares( storeName, cdc, sharesAmountStr, sharesPercentStr, - delegatorAddr, validatorAddr, + delAddr, valAddr, ) if err != nil { return err } - msg := stake.NewMsgBeginUnbonding(delegatorAddr, validatorAddr, sharesAmount) + msg := stake.NewMsgBeginUnbonding(delAddr, valAddr, sharesAmount) // build and sign the transaction, then broadcast to Tendermint return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) @@ -395,17 +397,17 @@ func GetCmdCompleteUnbonding(cdc *wire.Codec) *cobra.Command { WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - delegatorAddr, err := cliCtx.GetFromAddress() + delAddr, err := cliCtx.GetFromAddress() if err != nil { return err } - validatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } - msg := stake.NewMsgCompleteUnbonding(delegatorAddr, validatorAddr) + msg := stake.NewMsgCompleteUnbonding(delAddr, valAddr) // build and sign the transaction, then broadcast to Tendermint return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index a040c7541c0a..bf929387dd5d 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -87,7 +87,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Cod // defines a delegation without type Rat for shares type DelegationWithoutRat struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorAddr sdk.AccAddress `json:"validator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` Shares string `json:"shares"` Height int64 `json:"height"` } @@ -103,14 +103,14 @@ type DelegationSummary struct { func delegatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var validatorAddr sdk.AccAddress + var valAddr sdk.ValAddress var delegationSummary = DelegationSummary{} // read parameters vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + delAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) @@ -126,10 +126,10 @@ func delegatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handler } for _, validator := range validators { - validatorAddr = validator.Operator + valAddr = validator.Operator // Delegations - delegations, statusCode, errMsg, err := getDelegatorDelegations(cliCtx, cdc, delegatorAddr, validatorAddr) + delegations, statusCode, errMsg, err := getDelegatorDelegations(cliCtx, cdc, delAddr, valAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -140,7 +140,7 @@ func delegatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handler } // Undelegations - unbondingDelegation, statusCode, errMsg, err := getDelegatorUndelegations(cliCtx, cdc, delegatorAddr, validatorAddr) + unbondingDelegation, statusCode, errMsg, err := getDelegatorUndelegations(cliCtx, cdc, delAddr, valAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -153,7 +153,7 @@ func delegatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handler // Redelegations // only querying redelegations to a validator as this should give us already all relegations // if we also would put in redelegations from, we would have every redelegation double - redelegations, statusCode, errMsg, err := getDelegatorRedelegations(cliCtx, cdc, delegatorAddr, validatorAddr) + redelegations, statusCode, errMsg, err := getDelegatorRedelegations(cliCtx, cdc, delAddr, valAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -259,22 +259,21 @@ func unbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) h bech32delegator := vars["delegatorAddr"] bech32validator := vars["validatorAddr"] - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + delAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) + valAddr, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - validatorAddrAcc := sdk.AccAddress(validatorAddr) - key := stake.GetUBDKey(delegatorAddr, validatorAddrAcc) + key := stake.GetUBDKey(delAddr, valAddr) res, err := cliCtx.QueryStore(key, storeName) if err != nil { @@ -318,22 +317,21 @@ func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle bech32delegator := vars["delegatorAddr"] bech32validator := vars["validatorAddr"] - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + delAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) + valAddr, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - validatorAddrAcc := sdk.AccAddress(validatorAddr) - key := stake.GetDelegationKey(delegatorAddr, validatorAddrAcc) + key := stake.GetDelegationKey(delAddr, valAddr) res, err := cliCtx.QueryStore(key, storeName) if err != nil { @@ -377,7 +375,7 @@ func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle func delegatorValidatorsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var validatorAccAddr sdk.AccAddress + var valAddr sdk.ValAddress var bondedValidators []types.BechValidator // read parameters @@ -412,9 +410,9 @@ func delegatorValidatorsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) ht for _, validator := range validators { // get all transactions from the delegator to val and append - validatorAccAddr = validator.Operator + valAddr = validator.Operator - validator, statusCode, errMsg, errRes := getDelegatorValidator(cliCtx, cdc, delegatorAddr, validatorAccAddr) + validator, statusCode, errMsg, errRes := getDelegatorValidator(cliCtx, cdc, delegatorAddr, valAddr) if errRes != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, errRes.Error()))) @@ -444,8 +442,8 @@ func delegatorValidatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) htt bech32delegator := vars["delegatorAddr"] bech32validator := vars["validatorAddr"] - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - validatorAccAddr, err := sdk.AccAddressFromBech32(bech32validator) + delAddr, err := sdk.AccAddressFromBech32(bech32delegator) + valAddr, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) @@ -454,7 +452,7 @@ func delegatorValidatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) htt // Check if there if the delegator is bonded or redelegated to the validator - validator, statusCode, errMsg, err := getDelegatorValidator(cliCtx, cdc, delegatorAddr, validatorAccAddr) + validator, statusCode, errMsg, err := getDelegatorValidator(cliCtx, cdc, delAddr, valAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -516,14 +514,15 @@ func validatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handler // read parameters vars := mux.Vars(r) bech32validatorAddr := vars["addr"] - valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) + + valAddr, err := sdk.ValAddressFromBech32(bech32validatorAddr) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(fmt.Sprintf("error: %s", err.Error()))) return } - key := stake.GetValidatorKey(valAddress) + key := stake.GetValidatorKey(valAddr) res, err := cliCtx.QueryStore(key, storeName) if err != nil { @@ -538,7 +537,7 @@ func validatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handler return } - validator, err := types.UnmarshalValidator(cdc, valAddress, res) + validator, err := types.UnmarshalValidator(cdc, valAddr, res) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 3d7d419a3a64..24a8c3875282 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -104,26 +104,26 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx contex i := 0 for _, msg := range m.Delegations { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error())) return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { + if !bytes.Equal(info.GetPubKey().Address(), delAddr) { utils.WriteErrorResponse(&w, http.StatusUnauthorized, "Must use own delegator address") return } messages[i] = stake.MsgDelegate{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, Delegation: msg.Delegation, } @@ -131,23 +131,23 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx contex } for _, msg := range m.BeginRedelegates { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { + if !bytes.Equal(info.GetPubKey().Address(), delAddr) { utils.WriteErrorResponse(&w, http.StatusUnauthorized, "Must use own delegator address") return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) + valSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) + valDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return @@ -160,9 +160,9 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx contex } messages[i] = stake.MsgBeginRedelegate{ - DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + DelegatorAddr: delAddr, + ValidatorSrcAddr: valSrcAddr, + ValidatorDstAddr: valDstAddr, SharesAmount: shares, } @@ -170,50 +170,51 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx contex } for _, msg := range m.CompleteRedelegates { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error())) return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) + valSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) + + valDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { + if !bytes.Equal(info.GetPubKey().Address(), delAddr) { utils.WriteErrorResponse(&w, http.StatusUnauthorized, "Must use own delegator address") return } messages[i] = stake.MsgCompleteRedelegate{ - DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + DelegatorAddr: delAddr, + ValidatorSrcAddr: valSrcAddr, + ValidatorDstAddr: valDstAddr, } i++ } for _, msg := range m.BeginUnbondings { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error())) return } - if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { + if !bytes.Equal(info.GetPubKey().Address(), delAddr) { utils.WriteErrorResponse(&w, http.StatusUnauthorized, "Must use own delegator address") return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return @@ -226,8 +227,8 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx contex } messages[i] = stake.MsgBeginUnbonding{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, SharesAmount: shares, } @@ -235,26 +236,26 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx contex } for _, msg := range m.CompleteUnbondings { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error())) return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) if err != nil { utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { + if !bytes.Equal(info.GetPubKey().Address(), delAddr) { utils.WriteErrorResponse(&w, http.StatusUnauthorized, "Must use own delegator address") return } messages[i] = stake.MsgCompleteUnbonding{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, } i++ diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 96588f73b51b..171ded2b35f1 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -24,10 +24,10 @@ func contains(stringSlice []string, txType string) bool { return false } -func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( +func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delAddr sdk.AccAddress, valAddr sdk.ValAddress) ( bech32Validator types.BechValidator, httpStatusCode int, errMsg string, err error) { - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) + key := stake.GetDelegationKey(delAddr, valAddr) res, err := cliCtx.QueryStore(key, storeName) if err != nil { return types.BechValidator{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err @@ -36,7 +36,7 @@ func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegator return types.BechValidator{}, http.StatusNoContent, "", nil } - key = stake.GetValidatorKey(validatorAddr) + key = stake.GetValidatorKey(valAddr) res, err = cliCtx.QueryStore(key, storeName) if err != nil { return types.BechValidator{}, http.StatusInternalServerError, "couldn't query validator. Error: ", err @@ -44,7 +44,7 @@ func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegator if len(res) == 0 { return types.BechValidator{}, http.StatusNoContent, "", nil } - validator, err := types.UnmarshalValidator(cdc, validatorAddr, res) + validator, err := types.UnmarshalValidator(cdc, valAddr, res) if err != nil { return types.BechValidator{}, http.StatusBadRequest, "", err } @@ -56,9 +56,11 @@ func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegator return bech32Validator, http.StatusOK, "", nil } -func getDelegatorDelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( +func getDelegatorDelegations( + cliCtx context.CLIContext, cdc *wire.Codec, delAddr sdk.AccAddress, valAddr sdk.ValAddress) ( outputDelegation DelegationWithoutRat, httpStatusCode int, errMsg string, err error) { - delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) + + delegationKey := stake.GetDelegationKey(delAddr, valAddr) marshalledDelegation, err := cliCtx.QueryStore(delegationKey, storeName) if err != nil { return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err @@ -83,9 +85,11 @@ func getDelegatorDelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegat return outputDelegation, http.StatusOK, "", nil } -func getDelegatorUndelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( +func getDelegatorUndelegations( + cliCtx context.CLIContext, cdc *wire.Codec, delAddr sdk.AccAddress, valAddr sdk.ValAddress) ( unbonds types.UnbondingDelegation, httpStatusCode int, errMsg string, err error) { - undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) + + undelegationKey := stake.GetUBDKey(delAddr, valAddr) marshalledUnbondingDelegation, err := cliCtx.QueryStore(undelegationKey, storeName) if err != nil { return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't query unbonding-delegation. Error: ", err @@ -102,10 +106,11 @@ func getDelegatorUndelegations(cliCtx context.CLIContext, cdc *wire.Codec, deleg return unbondingDelegation, http.StatusOK, "", nil } -func getDelegatorRedelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( +func getDelegatorRedelegations( + cliCtx context.CLIContext, cdc *wire.Codec, delAddr sdk.AccAddress, valAddr sdk.ValAddress) ( regelegations types.Redelegation, httpStatusCode int, errMsg string, err error) { - key := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + key := stake.GetREDsByDelToValDstIndexKey(delAddr, valAddr) marshalledRedelegations, err := cliCtx.QueryStore(key, storeName) if err != nil { return types.Redelegation{}, http.StatusInternalServerError, "couldn't query redelegation. Error: ", err diff --git a/x/stake/genesis_test.go b/x/stake/genesis_test.go index 9cdbe19826bc..ddd29f6f8498 100644 --- a/x/stake/genesis_test.go +++ b/x/stake/genesis_test.go @@ -23,8 +23,8 @@ func TestInitGenesis(t *testing.T) { var delegations []Delegation validators := []Validator{ - NewValidator(keep.Addrs[0], keep.PKs[0], Description{Moniker: "hoop"}), - NewValidator(keep.Addrs[1], keep.PKs[1], Description{Moniker: "bloop"}), + NewValidator(sdk.ValAddress(keep.Addrs[0]), keep.PKs[0], Description{Moniker: "hoop"}), + NewValidator(sdk.ValAddress(keep.Addrs[1]), keep.PKs[1], Description{Moniker: "bloop"}), } genesisState := types.NewGenesisState(pool, params, validators, delegations) _, err := InitGenesis(ctx, keeper, genesisState) @@ -43,12 +43,12 @@ func TestInitGenesis(t *testing.T) { require.NoError(t, err) // now make sure the validators are bonded and intra-tx counters are correct - resVal, found := keeper.GetValidator(ctx, keep.Addrs[0]) + resVal, found := keeper.GetValidator(ctx, sdk.ValAddress(keep.Addrs[0])) require.True(t, found) require.Equal(t, sdk.Bonded, resVal.Status) require.Equal(t, int16(0), resVal.BondIntraTxCounter) - resVal, found = keeper.GetValidator(ctx, keep.Addrs[1]) + resVal, found = keeper.GetValidator(ctx, sdk.ValAddress(keep.Addrs[1])) require.True(t, found) require.Equal(t, sdk.Bonded, resVal.Status) require.Equal(t, int16(1), resVal.BondIntraTxCounter) @@ -76,7 +76,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { validators := make([]Validator, size) for i := range validators { - validators[i] = NewValidator(keep.Addrs[i], keep.PKs[i], Description{Moniker: fmt.Sprintf("#%d", i)}) + validators[i] = NewValidator(sdk.ValAddress(keep.Addrs[i]), keep.PKs[i], Description{Moniker: fmt.Sprintf("#%d", i)}) validators[i].Status = sdk.Bonded if i < 100 { diff --git a/x/stake/handler_test.go b/x/stake/handler_test.go index 6ab54e48c260..f7d01bcfc76b 100644 --- a/x/stake/handler_test.go +++ b/x/stake/handler_test.go @@ -16,23 +16,23 @@ import ( //______________________________________________________________________ -func newTestMsgCreateValidator(address sdk.AccAddress, pubKey crypto.PubKey, amt int64) MsgCreateValidator { +func newTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt int64) MsgCreateValidator { return types.NewMsgCreateValidator(address, pubKey, sdk.Coin{"steak", sdk.NewInt(amt)}, Description{}) } -func newTestMsgDelegate(delegatorAddr, validatorAddr sdk.AccAddress, amt int64) MsgDelegate { +func newTestMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt int64) MsgDelegate { return MsgDelegate{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, Delegation: sdk.Coin{"steak", sdk.NewInt(amt)}, } } -func newTestMsgCreateValidatorOnBehalfOf(delegatorAddr, validatorAddr sdk.AccAddress, valPubKey crypto.PubKey, amt int64) MsgCreateValidator { +func newTestMsgCreateValidatorOnBehalfOf(delAddr sdk.AccAddress, valAddr sdk.ValAddress, valPubKey crypto.PubKey, amt int64) MsgCreateValidator { return MsgCreateValidator{ Description: Description{}, - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, PubKey: valPubKey, Delegation: sdk.Coin{"steak", sdk.NewInt(amt)}, } @@ -49,7 +49,7 @@ func setInstantUnbondPeriod(keeper keep.Keeper, ctx sdk.Context) types.Params { //______________________________________________________________________ func TestValidatorByPowerIndex(t *testing.T) { - validatorAddr, validatorAddr3 := keep.Addrs[0], keep.Addrs[1] + validatorAddr, validatorAddr3 := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) initBond := int64(1000000) ctx, _, keeper := keep.CreateTestInput(t, false, initBond) @@ -61,7 +61,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) // verify the self-delegation exists - bond, found := keeper.GetDelegation(ctx, validatorAddr, validatorAddr) + bond, found := keeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found) gotBond := bond.Shares.RoundInt64() require.Equal(t, initBond, gotBond, @@ -110,8 +110,8 @@ func TestValidatorByPowerIndex(t *testing.T) { require.Equal(t, power2, power3) // unbond self-delegation - msgBeginUnbonding := NewMsgBeginUnbonding(validatorAddr, validatorAddr, sdk.NewDec(1000000)) - msgCompleteUnbonding := NewMsgCompleteUnbonding(validatorAddr, validatorAddr) + msgBeginUnbonding := NewMsgBeginUnbonding(sdk.AccAddress(validatorAddr), validatorAddr, sdk.NewDec(1000000)) + msgCompleteUnbonding := NewMsgCompleteUnbonding(sdk.AccAddress(validatorAddr), validatorAddr) got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) got = handleMsgCompleteUnbonding(ctx, msgCompleteUnbonding, keeper) @@ -126,7 +126,7 @@ func TestValidatorByPowerIndex(t *testing.T) { func TestDuplicatesMsgCreateValidator(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - addr1, addr2 := keep.Addrs[0], keep.Addrs[1] + addr1, addr2 := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) pk1, pk2 := keep.PKs[0], keep.PKs[1] msgCreateValidator1 := newTestMsgCreateValidator(addr1, pk1, 10) @@ -170,7 +170,7 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { func TestDuplicatesMsgCreateValidatorOnBehalfOf(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr := keep.Addrs[0] + validatorAddr := sdk.ValAddress(keep.Addrs[0]) delegatorAddr := keep.Addrs[1] pk := keep.PKs[0] msgCreateValidatorOnBehalfOf := newTestMsgCreateValidatorOnBehalfOf(delegatorAddr, validatorAddr, pk, 10) @@ -199,7 +199,7 @@ func TestIncrementsMsgDelegate(t *testing.T) { params := keeper.GetParams(ctx) bondAmount := int64(10) - validatorAddr, delegatorAddr := keep.Addrs[0], keep.Addrs[1] + validatorAddr, delegatorAddr := sdk.ValAddress(keep.Addrs[0]), keep.Addrs[1] // first create validator msgCreateValidator := newTestMsgCreateValidator(validatorAddr, keep.PKs[0], bondAmount) @@ -215,7 +215,7 @@ func TestIncrementsMsgDelegate(t *testing.T) { _, found = keeper.GetDelegation(ctx, delegatorAddr, validatorAddr) require.False(t, found) - bond, found := keeper.GetDelegation(ctx, validatorAddr, validatorAddr) + bond, found := keeper.GetDelegation(ctx, sdk.AccAddress(validatorAddr), validatorAddr) require.True(t, found) require.Equal(t, bondAmount, bond.Shares.RoundInt64()) @@ -271,7 +271,7 @@ func TestIncrementsMsgUnbond(t *testing.T) { denom := params.BondDenom // create validator, delegate - validatorAddr, delegatorAddr := keep.Addrs[0], keep.Addrs[1] + validatorAddr, delegatorAddr := sdk.ValAddress(keep.Addrs[0]), keep.Addrs[1] msgCreateValidator := newTestMsgCreateValidator(validatorAddr, keep.PKs[0], initBond) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) @@ -367,7 +367,7 @@ func TestMultipleMsgCreateValidator(t *testing.T) { ctx, accMapper, keeper := keep.CreateTestInput(t, false, initBond) params := setInstantUnbondPeriod(keeper, ctx) - validatorAddrs := []sdk.AccAddress{keep.Addrs[0], keep.Addrs[1], keep.Addrs[2]} + validatorAddrs := []sdk.ValAddress{sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]), sdk.ValAddress(keep.Addrs[2])} delegatorAddrs := []sdk.AccAddress{keep.Addrs[3], keep.Addrs[4], keep.Addrs[5]} // bond them all @@ -414,7 +414,7 @@ func TestMultipleMsgCreateValidator(t *testing.T) { func TestMultipleMsgDelegate(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr, delegatorAddrs := keep.Addrs[0], keep.Addrs[1:] + validatorAddr, delegatorAddrs := sdk.ValAddress(keep.Addrs[0]), keep.Addrs[1:] _ = setInstantUnbondPeriod(keeper, ctx) //first make a validator @@ -451,7 +451,7 @@ func TestMultipleMsgDelegate(t *testing.T) { func TestJailValidator(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr, delegatorAddr := keep.Addrs[0], keep.Addrs[1] + validatorAddr, delegatorAddr := sdk.ValAddress(keep.Addrs[0]), keep.Addrs[1] _ = setInstantUnbondPeriod(keeper, ctx) // create the validator @@ -467,8 +467,8 @@ func TestJailValidator(t *testing.T) { validator, _ := keeper.GetValidator(ctx, validatorAddr) // unbond the validators bond portion - msgBeginUnbondingValidator := NewMsgBeginUnbonding(validatorAddr, validatorAddr, sdk.NewDec(10)) - msgCompleteUnbondingValidator := NewMsgCompleteUnbonding(validatorAddr, validatorAddr) + msgBeginUnbondingValidator := NewMsgBeginUnbonding(sdk.AccAddress(validatorAddr), validatorAddr, sdk.NewDec(10)) + msgCompleteUnbondingValidator := NewMsgCompleteUnbonding(sdk.AccAddress(validatorAddr), validatorAddr) got = handleMsgBeginUnbonding(ctx, msgBeginUnbondingValidator, keeper) require.True(t, got.IsOK(), "expected no error") got = handleMsgCompleteUnbonding(ctx, msgCompleteUnbondingValidator, keeper) @@ -497,7 +497,7 @@ func TestJailValidator(t *testing.T) { func TestUnbondingPeriod(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr := keep.Addrs[0] + validatorAddr := sdk.ValAddress(keep.Addrs[0]) // set the unbonding time params := keeper.GetParams(ctx) @@ -510,12 +510,12 @@ func TestUnbondingPeriod(t *testing.T) { require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") // begin unbonding - msgBeginUnbonding := NewMsgBeginUnbonding(validatorAddr, validatorAddr, sdk.NewDec(10)) + msgBeginUnbonding := NewMsgBeginUnbonding(sdk.AccAddress(validatorAddr), validatorAddr, sdk.NewDec(10)) got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) require.True(t, got.IsOK(), "expected no error") // cannot complete unbonding at same time - msgCompleteUnbonding := NewMsgCompleteUnbonding(validatorAddr, validatorAddr) + msgCompleteUnbonding := NewMsgCompleteUnbonding(sdk.AccAddress(validatorAddr), validatorAddr) got = handleMsgCompleteUnbonding(ctx, msgCompleteUnbonding, keeper) require.True(t, !got.IsOK(), "expected an error") @@ -537,7 +537,7 @@ func TestUnbondingPeriod(t *testing.T) { func TestRedelegationPeriod(t *testing.T) { ctx, AccMapper, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr, validatorAddr2 := keep.Addrs[0], keep.Addrs[1] + validatorAddr, validatorAddr2 := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) denom := keeper.GetParams(ctx).BondDenom // set the unbonding time @@ -549,32 +549,32 @@ func TestRedelegationPeriod(t *testing.T) { msgCreateValidator := newTestMsgCreateValidator(validatorAddr, keep.PKs[0], 10) // initial balance - amt1 := AccMapper.GetAccount(ctx, validatorAddr).GetCoins().AmountOf(denom) + amt1 := AccMapper.GetAccount(ctx, sdk.AccAddress(validatorAddr)).GetCoins().AmountOf(denom) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") // balance should have been subtracted after creation - amt2 := AccMapper.GetAccount(ctx, validatorAddr).GetCoins().AmountOf(denom) + amt2 := AccMapper.GetAccount(ctx, sdk.AccAddress(validatorAddr)).GetCoins().AmountOf(denom) require.Equal(t, amt1.Sub(sdk.NewInt(10)).Int64(), amt2.Int64(), "expected coins to be subtracted") msgCreateValidator = newTestMsgCreateValidator(validatorAddr2, keep.PKs[1], 10) got = handleMsgCreateValidator(ctx, msgCreateValidator, keeper) require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") - bal1 := AccMapper.GetAccount(ctx, validatorAddr).GetCoins() + bal1 := AccMapper.GetAccount(ctx, sdk.AccAddress(validatorAddr)).GetCoins() // begin redelegate - msgBeginRedelegate := NewMsgBeginRedelegate(validatorAddr, validatorAddr, validatorAddr2, sdk.NewDec(10)) + msgBeginRedelegate := NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2, sdk.NewDec(10)) got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, got.IsOK(), "expected no error, %v", got) // origin account should not lose tokens as with a regular delegation - bal2 := AccMapper.GetAccount(ctx, validatorAddr).GetCoins() + bal2 := AccMapper.GetAccount(ctx, sdk.AccAddress(validatorAddr)).GetCoins() require.Equal(t, bal1, bal2) // cannot complete redelegation at same time - msgCompleteRedelegate := NewMsgCompleteRedelegate(validatorAddr, validatorAddr, validatorAddr2) + msgCompleteRedelegate := NewMsgCompleteRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) got = handleMsgCompleteRedelegate(ctx, msgCompleteRedelegate, keeper) require.True(t, !got.IsOK(), "expected an error") @@ -596,7 +596,9 @@ func TestRedelegationPeriod(t *testing.T) { func TestTransitiveRedelegation(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr, validatorAddr2, validatorAddr3 := keep.Addrs[0], keep.Addrs[1], keep.Addrs[2] + validatorAddr := sdk.ValAddress(keep.Addrs[0]) + validatorAddr2 := sdk.ValAddress(keep.Addrs[1]) + validatorAddr3 := sdk.ValAddress(keep.Addrs[2]) // set the unbonding time params := keeper.GetParams(ctx) @@ -617,17 +619,17 @@ func TestTransitiveRedelegation(t *testing.T) { require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") // begin redelegate - msgBeginRedelegate := NewMsgBeginRedelegate(validatorAddr, validatorAddr, validatorAddr2, sdk.NewDec(10)) + msgBeginRedelegate := NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2, sdk.NewDec(10)) got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, got.IsOK(), "expected no error, %v", got) // cannot redelegation to next validator while first delegation exists - msgBeginRedelegate = NewMsgBeginRedelegate(validatorAddr, validatorAddr2, validatorAddr3, sdk.NewDec(10)) + msgBeginRedelegate = NewMsgBeginRedelegate(sdk.AccAddress(validatorAddr), validatorAddr2, validatorAddr3, sdk.NewDec(10)) got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, !got.IsOK(), "expected an error, msg: %v", msgBeginRedelegate) // complete first redelegation - msgCompleteRedelegate := NewMsgCompleteRedelegate(validatorAddr, validatorAddr, validatorAddr2) + msgCompleteRedelegate := NewMsgCompleteRedelegate(sdk.AccAddress(validatorAddr), validatorAddr, validatorAddr2) got = handleMsgCompleteRedelegate(ctx, msgCompleteRedelegate, keeper) require.True(t, got.IsOK(), "expected no error") @@ -638,7 +640,9 @@ func TestTransitiveRedelegation(t *testing.T) { func TestUnbondingWhenExcessValidators(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr1, validatorAddr2, validatorAddr3 := keep.Addrs[0], keep.Addrs[1], keep.Addrs[2] + validatorAddr1 := sdk.ValAddress(keep.Addrs[0]) + validatorAddr2 := sdk.ValAddress(keep.Addrs[1]) + validatorAddr3 := sdk.ValAddress(keep.Addrs[2]) // set the unbonding time params := keeper.GetParams(ctx) @@ -663,7 +667,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { require.Equal(t, 2, len(keeper.GetValidatorsBonded(ctx))) // unbond the valdator-2 - msgBeginUnbonding := NewMsgBeginUnbonding(validatorAddr2, validatorAddr2, sdk.NewDec(30)) + msgBeginUnbonding := NewMsgBeginUnbonding(sdk.AccAddress(validatorAddr2), validatorAddr2, sdk.NewDec(30)) got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) require.True(t, got.IsOK(), "expected no error on runMsgBeginUnbonding") @@ -679,7 +683,7 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { func TestJoiningAsCliffValidator(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr1, validatorAddr2 := keep.Addrs[0], keep.Addrs[1] + validatorAddr1, validatorAddr2 := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) // make sure that the cliff validator is nil to begin with cliffVal := keeper.GetCliffValidator(ctx) @@ -712,7 +716,7 @@ func TestJoiningAsCliffValidator(t *testing.T) { func TestJoiningToCreateFirstCliffValidator(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr1, validatorAddr2 := keep.Addrs[0], keep.Addrs[1] + validatorAddr1, validatorAddr2 := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) // make sure that the cliff validator is nil to begin with cliffVal := keeper.GetCliffValidator(ctx) @@ -745,7 +749,9 @@ func TestJoiningToCreateFirstCliffValidator(t *testing.T) { func TestCliffValidator(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - validatorAddr1, validatorAddr2, validatorAddr3 := keep.Addrs[0], keep.Addrs[1], keep.Addrs[2] + validatorAddr1 := sdk.ValAddress(keep.Addrs[0]) + validatorAddr2 := sdk.ValAddress(keep.Addrs[1]) + validatorAddr3 := sdk.ValAddress(keep.Addrs[2]) // make sure that the cliff validator is nil to begin with cliffVal := keeper.GetCliffValidator(ctx) @@ -785,7 +791,7 @@ func TestCliffValidator(t *testing.T) { require.Equal(t, validatorAddr2.Bytes(), cliffVal) // unbond valdator-2 - msgBeginUnbonding := NewMsgBeginUnbonding(validatorAddr2, validatorAddr2, sdk.NewDec(30)) + msgBeginUnbonding := NewMsgBeginUnbonding(sdk.AccAddress(validatorAddr2), validatorAddr2, sdk.NewDec(30)) got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) require.True(t, got.IsOK(), "expected no error on runMsgBeginUnbonding") @@ -798,7 +804,7 @@ func TestCliffValidator(t *testing.T) { require.Equal(t, validatorAddr3.Bytes(), cliffVal) // unbond valdator-1 - msgBeginUnbonding = NewMsgBeginUnbonding(validatorAddr1, validatorAddr1, sdk.NewDec(50)) + msgBeginUnbonding = NewMsgBeginUnbonding(sdk.AccAddress(validatorAddr1), validatorAddr1, sdk.NewDec(50)) got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) require.True(t, got.IsOK(), "expected no error on runMsgBeginUnbonding") @@ -813,7 +819,7 @@ func TestCliffValidator(t *testing.T) { func TestBondUnbondRedelegateSlashTwice(t *testing.T) { ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - valA, valB, del := keep.Addrs[0], keep.Addrs[1], keep.Addrs[2] + valA, valB, del := sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]), keep.Addrs[2] msgCreateValidator := newTestMsgCreateValidator(valA, keep.PKs[0], 10) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) diff --git a/x/stake/keeper/delegation.go b/x/stake/keeper/delegation.go index a6e48517c95a..9f7a402fc20f 100644 --- a/x/stake/keeper/delegation.go +++ b/x/stake/keeper/delegation.go @@ -9,10 +9,11 @@ import ( // load a delegation func (k Keeper) GetDelegation(ctx sdk.Context, - delegatorAddr, validatorAddr sdk.AccAddress) (delegation types.Delegation, found bool) { + delAddr sdk.AccAddress, valAddr sdk.ValAddress) ( + delegation types.Delegation, found bool) { store := ctx.KVStore(k.storeKey) - key := GetDelegationKey(delegatorAddr, validatorAddr) + key := GetDelegationKey(delAddr, valAddr) value := store.Get(key) if value == nil { return delegation, false @@ -79,10 +80,10 @@ func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) { // load a unbonding delegation func (k Keeper) GetUnbondingDelegation(ctx sdk.Context, - DelegatorAddr, ValidatorAddr sdk.AccAddress) (ubd types.UnbondingDelegation, found bool) { + delAddr sdk.AccAddress, valAddr sdk.ValAddress) (ubd types.UnbondingDelegation, found bool) { store := ctx.KVStore(k.storeKey) - key := GetUBDKey(DelegatorAddr, ValidatorAddr) + key := GetUBDKey(delAddr, valAddr) value := store.Get(key) if value == nil { return ubd, false @@ -93,7 +94,7 @@ func (k Keeper) GetUnbondingDelegation(ctx sdk.Context, } // load all unbonding delegations from a particular validator -func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.AccAddress) (ubds []types.UnbondingDelegation) { +func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation) { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, GetUBDsByValIndexKey(valAddr)) for { @@ -147,10 +148,10 @@ func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDe // load a redelegation func (k Keeper) GetRedelegation(ctx sdk.Context, - DelegatorAddr, ValidatorSrcAddr, ValidatorDstAddr sdk.AccAddress) (red types.Redelegation, found bool) { + delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) { store := ctx.KVStore(k.storeKey) - key := GetREDKey(DelegatorAddr, ValidatorSrcAddr, ValidatorDstAddr) + key := GetREDKey(delAddr, valSrcAddr, valDstAddr) value := store.Get(key) if value == nil { return red, false @@ -161,7 +162,7 @@ func (k Keeper) GetRedelegation(ctx sdk.Context, } // load all redelegations from a particular validator -func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.AccAddress) (reds []types.Redelegation) { +func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (reds []types.Redelegation) { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, GetREDsFromValSrcIndexKey(valAddr)) for { @@ -180,10 +181,10 @@ func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.AccAd // has a redelegation func (k Keeper) HasReceivingRedelegation(ctx sdk.Context, - DelegatorAddr, ValidatorDstAddr sdk.AccAddress) bool { + delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool { store := ctx.KVStore(k.storeKey) - prefix := GetREDsByDelToValDstIndexKey(DelegatorAddr, ValidatorDstAddr) + prefix := GetREDsByDelToValDstIndexKey(delAddr, valDstAddr) iterator := sdk.KVStorePrefixIterator(store, prefix) //smallest to largest found := false @@ -217,14 +218,14 @@ func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) { //_____________________________________________________________________________________ // Perform a delegation, set/update everything necessary within the store. -func (k Keeper) Delegate(ctx sdk.Context, delegatorAddr sdk.AccAddress, bondAmt sdk.Coin, +func (k Keeper) Delegate(ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdk.Coin, validator types.Validator, subtractAccount bool) (newShares sdk.Dec, err sdk.Error) { // Get or create the delegator delegation - delegation, found := k.GetDelegation(ctx, delegatorAddr, validator.Operator) + delegation, found := k.GetDelegation(ctx, delAddr, validator.Operator) if !found { delegation = types.Delegation{ - DelegatorAddr: delegatorAddr, + DelegatorAddr: delAddr, ValidatorAddr: validator.Operator, Shares: sdk.ZeroDec(), } @@ -253,11 +254,11 @@ func (k Keeper) Delegate(ctx sdk.Context, delegatorAddr sdk.AccAddress, bondAmt } // unbond the the delegation return -func (k Keeper) unbond(ctx sdk.Context, delegatorAddr, validatorAddr sdk.AccAddress, +func (k Keeper) unbond(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec) (amount sdk.Dec, err sdk.Error) { // check if delegation has any shares in it unbond - delegation, found := k.GetDelegation(ctx, delegatorAddr, validatorAddr) + delegation, found := k.GetDelegation(ctx, delAddr, valAddr) if !found { err = types.ErrNoDelegatorForAddress(k.Codespace()) return @@ -270,7 +271,7 @@ func (k Keeper) unbond(ctx sdk.Context, delegatorAddr, validatorAddr sdk.AccAddr } // get validator - validator, found := k.GetValidator(ctx, validatorAddr) + validator, found := k.GetValidator(ctx, valAddr) if !found { err = types.ErrNoValidatorFound(k.Codespace()) return @@ -312,15 +313,16 @@ func (k Keeper) unbond(ctx sdk.Context, delegatorAddr, validatorAddr sdk.AccAddr //______________________________________________________________________________________________________ // complete unbonding an unbonding record -func (k Keeper) BeginUnbonding(ctx sdk.Context, delegatorAddr, validatorAddr sdk.AccAddress, sharesAmount sdk.Dec) sdk.Error { +func (k Keeper) BeginUnbonding(ctx sdk.Context, + delAddr sdk.AccAddress, valAddr sdk.ValAddress, sharesAmount sdk.Dec) sdk.Error { // TODO quick fix, instead we should use an index, see https://github.com/cosmos/cosmos-sdk/issues/1402 - _, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr) + _, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr) if found { return types.ErrExistingUnbondingDelegation(k.Codespace()) } - returnAmount, err := k.unbond(ctx, delegatorAddr, validatorAddr, sharesAmount) + returnAmount, err := k.unbond(ctx, delAddr, valAddr, sharesAmount) if err != nil { return err } @@ -331,8 +333,8 @@ func (k Keeper) BeginUnbonding(ctx sdk.Context, delegatorAddr, validatorAddr sdk balance := sdk.Coin{params.BondDenom, returnAmount.RoundInt()} ubd := types.UnbondingDelegation{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, MinTime: minTime, Balance: balance, InitialBalance: balance, @@ -342,9 +344,9 @@ func (k Keeper) BeginUnbonding(ctx sdk.Context, delegatorAddr, validatorAddr sdk } // complete unbonding an unbonding record -func (k Keeper) CompleteUnbonding(ctx sdk.Context, delegatorAddr, validatorAddr sdk.AccAddress) sdk.Error { +func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) sdk.Error { - ubd, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr) + ubd, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr) if !found { return types.ErrNoUnbondingDelegation(k.Codespace()) } @@ -364,26 +366,26 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delegatorAddr, validatorAddr } // complete unbonding an unbonding record -func (k Keeper) BeginRedelegation(ctx sdk.Context, delegatorAddr, validatorSrcAddr, - validatorDstAddr sdk.AccAddress, sharesAmount sdk.Dec) sdk.Error { +func (k Keeper) BeginRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, + valSrcAddr, valDstAddr sdk.ValAddress, sharesAmount sdk.Dec) sdk.Error { // check if this is a transitive redelegation - if k.HasReceivingRedelegation(ctx, delegatorAddr, validatorSrcAddr) { + if k.HasReceivingRedelegation(ctx, delAddr, valSrcAddr) { return types.ErrTransitiveRedelegation(k.Codespace()) } - returnAmount, err := k.unbond(ctx, delegatorAddr, validatorSrcAddr, sharesAmount) + returnAmount, err := k.unbond(ctx, delAddr, valSrcAddr, sharesAmount) if err != nil { return err } params := k.GetParams(ctx) returnCoin := sdk.Coin{params.BondDenom, returnAmount.RoundInt()} - dstValidator, found := k.GetValidator(ctx, validatorDstAddr) + dstValidator, found := k.GetValidator(ctx, valDstAddr) if !found { return types.ErrBadRedelegationDst(k.Codespace()) } - sharesCreated, err := k.Delegate(ctx, delegatorAddr, returnCoin, dstValidator, false) + sharesCreated, err := k.Delegate(ctx, delAddr, returnCoin, dstValidator, false) if err != nil { return err } @@ -392,9 +394,9 @@ func (k Keeper) BeginRedelegation(ctx sdk.Context, delegatorAddr, validatorSrcAd minTime := ctx.BlockHeader().Time.Add(params.UnbondingTime) red := types.Redelegation{ - DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + DelegatorAddr: delAddr, + ValidatorSrcAddr: valSrcAddr, + ValidatorDstAddr: valDstAddr, MinTime: minTime, SharesDst: sharesCreated, SharesSrc: sharesAmount, @@ -406,9 +408,10 @@ func (k Keeper) BeginRedelegation(ctx sdk.Context, delegatorAddr, validatorSrcAd } // complete unbonding an ongoing redelegation -func (k Keeper) CompleteRedelegation(ctx sdk.Context, delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) sdk.Error { +func (k Keeper) CompleteRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, + valSrcAddr, valDstAddr sdk.ValAddress) sdk.Error { - red, found := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr) + red, found := k.GetRedelegation(ctx, delAddr, valSrcAddr, valDstAddr) if !found { return types.ErrNoRedelegation(k.Codespace()) } diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index 958de62ed5b6..d539c35d05b5 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -36,8 +36,8 @@ const maxDigitsForAccount = 12 // ~220,000,000 atoms created at launch // gets the key for the validator with address // VALUE: stake/types.Validator -func GetValidatorKey(ownerAddr sdk.AccAddress) []byte { - return append(ValidatorsKey, ownerAddr.Bytes()...) +func GetValidatorKey(operatorAddr sdk.ValAddress) []byte { + return append(ValidatorsKey, operatorAddr.Bytes()...) } // gets the key for the validator with pubkey @@ -48,8 +48,8 @@ func GetValidatorByPubKeyIndexKey(pubkey crypto.PubKey) []byte { // gets the key for the current validator group // VALUE: none (key rearrangement with GetValKeyFromValBondedIndexKey) -func GetValidatorsBondedIndexKey(ownerAddr sdk.AccAddress) []byte { - return append(ValidatorsBondedIndexKey, ownerAddr.Bytes()...) +func GetValidatorsBondedIndexKey(operatorAddr sdk.ValAddress) []byte { + return append(ValidatorsBondedIndexKey, operatorAddr.Bytes()...) } // Get the validator owner address from ValBondedIndexKey @@ -97,37 +97,37 @@ func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { // get the key for the accumulated update validators // VALUE: abci.Validator // note records using these keys should never persist between blocks -func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { - return append(TendermintUpdatesKey, ownerAddr.Bytes()...) +func GetTendermintUpdatesKey(operatorAddr sdk.ValAddress) []byte { + return append(TendermintUpdatesKey, operatorAddr.Bytes()...) } //______________________________________________________________________________ // gets the key for delegator bond with validator // VALUE: stake/types.Delegation -func GetDelegationKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { - return append(GetDelegationsKey(delegatorAddr), validatorAddr.Bytes()...) +func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { + return append(GetDelegationsKey(delAddr), valAddr.Bytes()...) } // gets the prefix for a delegator for all validators -func GetDelegationsKey(delegatorAddr sdk.AccAddress) []byte { - return append(DelegationKey, delegatorAddr.Bytes()...) +func GetDelegationsKey(delAddr sdk.AccAddress) []byte { + return append(DelegationKey, delAddr.Bytes()...) } //______________________________________________________________________________ // gets the key for an unbonding delegation by delegator and validator addr // VALUE: stake/types.UnbondingDelegation -func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { +func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { return append( - GetUBDsKey(delegatorAddr.Bytes()), - validatorAddr.Bytes()...) + GetUBDsKey(delAddr.Bytes()), + valAddr.Bytes()...) } // gets the index-key for an unbonding delegation, stored by validator-index // VALUE: none (key rearrangement used) -func GetUBDByValIndexKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { - return append(GetUBDsByValIndexKey(validatorAddr), delegatorAddr.Bytes()...) +func GetUBDByValIndexKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { + return append(GetUBDsByValIndexKey(valAddr), delAddr.Bytes()...) } // rearranges the ValIndexKey to get the UBDKey @@ -144,42 +144,42 @@ func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { //______________ // gets the prefix for all unbonding delegations from a delegator -func GetUBDsKey(delegatorAddr sdk.AccAddress) []byte { - return append(UnbondingDelegationKey, delegatorAddr.Bytes()...) +func GetUBDsKey(delAddr sdk.AccAddress) []byte { + return append(UnbondingDelegationKey, delAddr.Bytes()...) } // gets the prefix keyspace for the indexes of unbonding delegations for a validator -func GetUBDsByValIndexKey(validatorAddr sdk.AccAddress) []byte { - return append(UnbondingDelegationByValIndexKey, validatorAddr.Bytes()...) +func GetUBDsByValIndexKey(valAddr sdk.ValAddress) []byte { + return append(UnbondingDelegationByValIndexKey, valAddr.Bytes()...) } //________________________________________________________________________________ // gets the key for a redelegation // VALUE: stake/types.RedelegationKey -func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { +func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { return append(append( - GetREDsKey(delegatorAddr.Bytes()), - validatorSrcAddr.Bytes()...), - validatorDstAddr.Bytes()...) + GetREDsKey(delAddr.Bytes()), + valSrcAddr.Bytes()...), + valDstAddr.Bytes()...) } // gets the index-key for a redelegation, stored by source-validator-index // VALUE: none (key rearrangement used) -func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { +func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { return append(append( - GetREDsFromValSrcIndexKey(validatorSrcAddr), - delegatorAddr.Bytes()...), - validatorDstAddr.Bytes()...) + GetREDsFromValSrcIndexKey(valSrcAddr), + delAddr.Bytes()...), + valDstAddr.Bytes()...) } // gets the index-key for a redelegation, stored by destination-validator-index // VALUE: none (key rearrangement used) -func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { +func GetREDByValDstIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { return append(append( - GetREDsToValDstIndexKey(validatorDstAddr), - delegatorAddr.Bytes()...), - validatorSrcAddr.Bytes()...) + GetREDsToValDstIndexKey(valDstAddr), + delAddr.Bytes()...), + valSrcAddr.Bytes()...) } // rearranges the ValSrcIndexKey to get the REDKey @@ -210,24 +210,24 @@ func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { //______________ // gets the prefix keyspace for redelegations from a delegator -func GetREDsKey(delegatorAddr sdk.AccAddress) []byte { - return append(RedelegationKey, delegatorAddr.Bytes()...) +func GetREDsKey(delAddr sdk.AccAddress) []byte { + return append(RedelegationKey, delAddr.Bytes()...) } // gets the prefix keyspace for all redelegations redelegating away from a source validator -func GetREDsFromValSrcIndexKey(validatorSrcAddr sdk.AccAddress) []byte { - return append(RedelegationByValSrcIndexKey, validatorSrcAddr.Bytes()...) +func GetREDsFromValSrcIndexKey(valSrcAddr sdk.ValAddress) []byte { + return append(RedelegationByValSrcIndexKey, valSrcAddr.Bytes()...) } // gets the prefix keyspace for all redelegations redelegating towards a destination validator -func GetREDsToValDstIndexKey(validatorDstAddr sdk.AccAddress) []byte { - return append(RedelegationByValDstIndexKey, validatorDstAddr.Bytes()...) +func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte { + return append(RedelegationByValDstIndexKey, valDstAddr.Bytes()...) } // gets the prefix keyspace for all redelegations redelegating towards a destination validator // from a particular delegator -func GetREDsByDelToValDstIndexKey(delegatorAddr, validatorDstAddr sdk.AccAddress) []byte { +func GetREDsByDelToValDstIndexKey(delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) []byte { return append( - GetREDsToValDstIndexKey(validatorDstAddr), - delegatorAddr.Bytes()...) + GetREDsToValDstIndexKey(valDstAddr), + delAddr.Bytes()...) } diff --git a/x/stake/keeper/sdk_types.go b/x/stake/keeper/sdk_types.go index aeec44fae959..480df701b101 100644 --- a/x/stake/keeper/sdk_types.go +++ b/x/stake/keeper/sdk_types.go @@ -51,7 +51,7 @@ func (k Keeper) IterateValidatorsBonded(ctx sdk.Context, fn func(index int64, va } // get the sdk.validator for a particular address -func (k Keeper) Validator(ctx sdk.Context, address sdk.AccAddress) sdk.Validator { +func (k Keeper) Validator(ctx sdk.Context, address sdk.ValAddress) sdk.Validator { val, found := k.GetValidator(ctx, address) if !found { return nil @@ -86,7 +86,7 @@ func (k Keeper) GetValidatorSet() sdk.ValidatorSet { } // get the delegation for a particular set of delegator and validator addresses -func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.AccAddress) sdk.Delegation { +func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) sdk.Delegation { bond, ok := k.GetDelegation(ctx, addrDel, addrVal) if !ok { return nil diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index 0470c28988a4..b84ce9d93a91 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -33,12 +33,12 @@ var ( Addrs[0], Addrs[1], } - addrVals = []sdk.AccAddress{ - Addrs[2], - Addrs[3], - Addrs[4], - Addrs[5], - Addrs[6], + addrVals = []sdk.ValAddress{ + sdk.ValAddress(Addrs[2]), + sdk.ValAddress(Addrs[3]), + sdk.ValAddress(Addrs[4]), + sdk.ValAddress(Addrs[5]), + sdk.ValAddress(Addrs[6]), } ) diff --git a/x/stake/keeper/validator.go b/x/stake/keeper/validator.go index e933a6d2360a..cb225df6cc77 100644 --- a/x/stake/keeper/validator.go +++ b/x/stake/keeper/validator.go @@ -12,7 +12,7 @@ import ( ) // get a single validator -func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.AccAddress) (validator types.Validator, found bool) { +func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator types.Validator, found bool) { store := ctx.KVStore(k.storeKey) value := store.Get(GetValidatorKey(addr)) if value == nil { @@ -223,7 +223,7 @@ func (k Keeper) UpdateValidator(ctx sdk.Context, validator types.Validator) type store.Set(GetTendermintUpdatesKey(validator.Operator), bz) if cliffPower != nil { - cliffAddr := sdk.AccAddress(k.GetCliffValidator(ctx)) + cliffAddr := sdk.ValAddress(k.GetCliffValidator(ctx)) if bytes.Equal(cliffAddr, validator.Operator) { k.updateCliffValidator(ctx, validator) } @@ -273,7 +273,7 @@ func (k Keeper) updateCliffValidator(ctx sdk.Context, affectedVal types.Validato store := ctx.KVStore(k.storeKey) pool := k.GetPool(ctx) - cliffAddr := sdk.AccAddress(k.GetCliffValidator(ctx)) + cliffAddr := sdk.ValAddress(k.GetCliffValidator(ctx)) oldCliffVal, found := k.GetValidator(ctx, cliffAddr) if !found { @@ -621,7 +621,7 @@ func (k Keeper) bondValidator(ctx sdk.Context, validator types.Validator) types. } // remove the validator record and associated indexes -func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.AccAddress) { +func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) { // first retrieve the old validator record validator, found := k.GetValidator(ctx, address) diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index 9e92ca33e702..e4a2663ae673 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -109,7 +109,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { validators := make([]types.Validator, numVals) for i := 0; i < len(validators); i++ { moniker := fmt.Sprintf("val#%d", int64(i)) - val := types.NewValidator(Addrs[i], PKs[i], types.Description{Moniker: moniker}) + val := types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{Moniker: moniker}) val.BondHeight = int64(i) val.BondIntraTxCounter = int16(i) val, pool, _ = val.AddTokensFromDel(pool, sdk.NewInt(int64((i+1)*10))) @@ -129,7 +129,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // require the cliff validator has changed cliffVal := validators[numVals-maxVals-1] - require.Equal(t, cliffVal.Operator, sdk.AccAddress(keeper.GetCliffValidator(ctx))) + require.Equal(t, cliffVal.Operator, sdk.ValAddress(keeper.GetCliffValidator(ctx))) // require the cliff validator power has changed cliffPower := keeper.GetCliffValidatorPower(ctx) @@ -172,7 +172,7 @@ func TestCliffValidatorChange(t *testing.T) { validators := make([]types.Validator, numVals) for i := 0; i < len(validators); i++ { moniker := fmt.Sprintf("val#%d", int64(i)) - val := types.NewValidator(Addrs[i], PKs[i], types.Description{Moniker: moniker}) + val := types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{Moniker: moniker}) val.BondHeight = int64(i) val.BondIntraTxCounter = int16(i) val, pool, _ = val.AddTokensFromDel(pool, sdk.NewInt(int64((i+1)*10))) @@ -190,7 +190,7 @@ func TestCliffValidatorChange(t *testing.T) { // assert new cliff validator to be set to the second lowest bonded validator by power newCliffVal := validators[numVals-maxVals+1] - require.Equal(t, newCliffVal.Operator, sdk.AccAddress(keeper.GetCliffValidator(ctx))) + require.Equal(t, newCliffVal.Operator, sdk.ValAddress(keeper.GetCliffValidator(ctx))) // assert cliff validator power should have been updated cliffPower := keeper.GetCliffValidatorPower(ctx) @@ -203,7 +203,7 @@ func TestCliffValidatorChange(t *testing.T) { // assert cliff validator has not change but increased in power cliffPower = keeper.GetCliffValidatorPower(ctx) - require.Equal(t, newCliffVal.Operator, sdk.AccAddress(keeper.GetCliffValidator(ctx))) + require.Equal(t, newCliffVal.Operator, sdk.ValAddress(keeper.GetCliffValidator(ctx))) require.Equal(t, GetValidatorsByPowerIndexKey(newCliffVal, pool), cliffPower) // add enough power to cliff validator to be equal in rank to next validator @@ -213,7 +213,7 @@ func TestCliffValidatorChange(t *testing.T) { // assert new cliff validator due to power rank construction newCliffVal = validators[numVals-maxVals+2] - require.Equal(t, newCliffVal.Operator, sdk.AccAddress(keeper.GetCliffValidator(ctx))) + require.Equal(t, newCliffVal.Operator, sdk.ValAddress(keeper.GetCliffValidator(ctx))) // assert cliff validator power should have been updated cliffPower = keeper.GetCliffValidatorPower(ctx) @@ -329,7 +329,7 @@ func GetValidatorSortingUnmixed(t *testing.T) { n := len(amts) var validators [5]types.Validator for i, amt := range amts { - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i].Status = sdk.Bonded validators[i].Tokens = sdk.NewDec(amt) validators[i].DelegatorShares = sdk.NewDec(amt) @@ -412,7 +412,7 @@ func GetValidatorSortingMixed(t *testing.T) { n := len(amts) var validators [5]types.Validator for i, amt := range amts { - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i].DelegatorShares = sdk.NewDec(amt) } @@ -431,15 +431,15 @@ func GetValidatorSortingMixed(t *testing.T) { for i := range amts { keeper.UpdateValidator(ctx, validators[i]) } - val0, found := keeper.GetValidator(ctx, Addrs[0]) + val0, found := keeper.GetValidator(ctx, sdk.ValAddress(Addrs[0])) require.True(t, found) - val1, found := keeper.GetValidator(ctx, Addrs[1]) + val1, found := keeper.GetValidator(ctx, sdk.ValAddress(Addrs[1])) require.True(t, found) - val2, found := keeper.GetValidator(ctx, Addrs[2]) + val2, found := keeper.GetValidator(ctx, sdk.ValAddress(Addrs[2])) require.True(t, found) - val3, found := keeper.GetValidator(ctx, Addrs[3]) + val3, found := keeper.GetValidator(ctx, sdk.ValAddress(Addrs[3])) require.True(t, found) - val4, found := keeper.GetValidator(ctx, Addrs[4]) + val4, found := keeper.GetValidator(ctx, sdk.ValAddress(Addrs[4])) require.True(t, found) require.Equal(t, sdk.Unbonded, val0.Status) require.Equal(t, sdk.Unbonded, val1.Status) @@ -479,7 +479,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) moniker := fmt.Sprintf("val#%d", int64(i)) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{Moniker: moniker}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{Moniker: moniker}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) validators[i] = keeper.UpdateValidator(ctx, validators[i]) @@ -553,9 +553,9 @@ func TestValidatorBondHeight(t *testing.T) { // initialize some validators into the state var validators [3]types.Validator - validators[0] = types.NewValidator(Addrs[0], PKs[0], types.Description{}) - validators[1] = types.NewValidator(Addrs[1], PKs[1], types.Description{}) - validators[2] = types.NewValidator(Addrs[2], PKs[2], types.Description{}) + validators[0] = types.NewValidator(sdk.ValAddress(Addrs[0]), PKs[0], types.Description{}) + validators[1] = types.NewValidator(sdk.ValAddress(Addrs[1]), PKs[1], types.Description{}) + validators[2] = types.NewValidator(sdk.ValAddress(Addrs[2]), PKs[2], types.Description{}) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, sdk.NewInt(200)) validators[1], pool, _ = validators[1].AddTokensFromDel(pool, sdk.NewInt(100)) @@ -600,7 +600,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { var validators [5]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) keeper.UpdateValidator(ctx, validators[i]) @@ -639,7 +639,7 @@ func TestClearTendermintUpdates(t *testing.T) { validators := make([]types.Validator, len(amts)) for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) keeper.UpdateValidator(ctx, validators[i]) @@ -659,7 +659,7 @@ func TestGetTendermintUpdatesAllNone(t *testing.T) { var validators [2]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -698,7 +698,7 @@ func TestGetTendermintUpdatesIdentical(t *testing.T) { var validators [2]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -721,7 +721,7 @@ func TestGetTendermintUpdatesSingleValueChange(t *testing.T) { var validators [2]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -749,7 +749,7 @@ func TestGetTendermintUpdatesMultipleValueChange(t *testing.T) { var validators [2]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -780,7 +780,7 @@ func TestGetTendermintUpdatesInserted(t *testing.T) { var validators [5]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -823,7 +823,7 @@ func TestGetTendermintUpdatesWithCliffValidator(t *testing.T) { var validators [5]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -861,7 +861,7 @@ func TestGetTendermintUpdatesPowerDecrease(t *testing.T) { var validators [2]types.Validator for i, amt := range amts { pool := keeper.GetPool(ctx) - validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } diff --git a/x/stake/simulation/msgs.go b/x/stake/simulation/msgs.go index 4280e70c1396..97ed112c0150 100644 --- a/x/stake/simulation/msgs.go +++ b/x/stake/simulation/msgs.go @@ -26,8 +26,8 @@ func SimulateMsgCreateValidator(m auth.AccountMapper, k stake.Keeper) simulation } key := simulation.RandomKey(r, keys) pubkey := key.PubKey() - address := sdk.AccAddress(pubkey.Address()) - amount := m.GetAccount(ctx, address).GetCoins().AmountOf(denom) + address := sdk.ValAddress(pubkey.Address()) + amount := m.GetAccount(ctx, sdk.AccAddress(address)).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } @@ -37,7 +37,7 @@ func SimulateMsgCreateValidator(m auth.AccountMapper, k stake.Keeper) simulation msg := stake.MsgCreateValidator{ Description: description, ValidatorAddr: address, - DelegatorAddr: address, + DelegatorAddr: sdk.AccAddress(address), PubKey: pubkey, Delegation: sdk.NewCoin(denom, amount), } @@ -65,7 +65,7 @@ func SimulateMsgEditValidator(k stake.Keeper) simulation.Operation { } key := simulation.RandomKey(r, keys) pubkey := key.PubKey() - address := sdk.AccAddress(pubkey.Address()) + address := sdk.ValAddress(pubkey.Address()) msg := stake.MsgEditValidator{ Description: description, ValidatorAddr: address, @@ -87,7 +87,7 @@ func SimulateMsgDelegate(m auth.AccountMapper, k stake.Keeper) simulation.Operat return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, fOp []simulation.FutureOperation, err sdk.Error) { denom := k.GetParams(ctx).BondDenom validatorKey := simulation.RandomKey(r, keys) - validatorAddress := sdk.AccAddress(validatorKey.PubKey().Address()) + validatorAddress := sdk.ValAddress(validatorKey.PubKey().Address()) delegatorKey := simulation.RandomKey(r, keys) delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) @@ -119,7 +119,7 @@ func SimulateMsgBeginUnbonding(m auth.AccountMapper, k stake.Keeper) simulation. return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, fOp []simulation.FutureOperation, err sdk.Error) { denom := k.GetParams(ctx).BondDenom validatorKey := simulation.RandomKey(r, keys) - validatorAddress := sdk.AccAddress(validatorKey.PubKey().Address()) + validatorAddress := sdk.ValAddress(validatorKey.PubKey().Address()) delegatorKey := simulation.RandomKey(r, keys) delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) @@ -150,7 +150,7 @@ func SimulateMsgBeginUnbonding(m auth.AccountMapper, k stake.Keeper) simulation. func SimulateMsgCompleteUnbonding(k stake.Keeper) simulation.Operation { return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, fOp []simulation.FutureOperation, err sdk.Error) { validatorKey := simulation.RandomKey(r, keys) - validatorAddress := sdk.AccAddress(validatorKey.PubKey().Address()) + validatorAddress := sdk.ValAddress(validatorKey.PubKey().Address()) delegatorKey := simulation.RandomKey(r, keys) delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) msg := stake.MsgCompleteUnbonding{ @@ -174,9 +174,9 @@ func SimulateMsgBeginRedelegate(m auth.AccountMapper, k stake.Keeper) simulation return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, fOp []simulation.FutureOperation, err sdk.Error) { denom := k.GetParams(ctx).BondDenom sourceValidatorKey := simulation.RandomKey(r, keys) - sourceValidatorAddress := sdk.AccAddress(sourceValidatorKey.PubKey().Address()) + sourceValidatorAddress := sdk.ValAddress(sourceValidatorKey.PubKey().Address()) destValidatorKey := simulation.RandomKey(r, keys) - destValidatorAddress := sdk.AccAddress(destValidatorKey.PubKey().Address()) + destValidatorAddress := sdk.ValAddress(destValidatorKey.PubKey().Address()) delegatorKey := simulation.RandomKey(r, keys) delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) // TODO @@ -209,9 +209,9 @@ func SimulateMsgBeginRedelegate(m auth.AccountMapper, k stake.Keeper) simulation func SimulateMsgCompleteRedelegate(k stake.Keeper) simulation.Operation { return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, fOp []simulation.FutureOperation, err sdk.Error) { validatorSrcKey := simulation.RandomKey(r, keys) - validatorSrcAddress := sdk.AccAddress(validatorSrcKey.PubKey().Address()) + validatorSrcAddress := sdk.ValAddress(validatorSrcKey.PubKey().Address()) validatorDstKey := simulation.RandomKey(r, keys) - validatorDstAddress := sdk.AccAddress(validatorDstKey.PubKey().Address()) + validatorDstAddress := sdk.ValAddress(validatorDstKey.PubKey().Address()) delegatorKey := simulation.RandomKey(r, keys) delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) msg := stake.MsgCompleteRedelegate{ diff --git a/x/stake/types/delegation.go b/x/stake/types/delegation.go index e3227c3ed18d..5a2274c3aee9 100644 --- a/x/stake/types/delegation.go +++ b/x/stake/types/delegation.go @@ -14,7 +14,7 @@ import ( // pubKey. type Delegation struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorAddr sdk.AccAddress `json:"validator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` Shares sdk.Dec `json:"shares"` Height int64 `json:"height"` // Last height bond updated } @@ -56,8 +56,9 @@ func UnmarshalDelegation(cdc *wire.Codec, key, value []byte) (delegation Delegat err = fmt.Errorf("%v", ErrBadDelegationAddr(DefaultCodespace).Data()) return } + delAddr := sdk.AccAddress(addrs[:sdk.AddrLen]) - valAddr := sdk.AccAddress(addrs[sdk.AddrLen:]) + valAddr := sdk.ValAddress(addrs[sdk.AddrLen:]) return Delegation{ DelegatorAddr: delAddr, @@ -80,7 +81,7 @@ var _ sdk.Delegation = Delegation{} // nolint - for sdk.Delegation func (d Delegation) GetDelegator() sdk.AccAddress { return d.DelegatorAddr } -func (d Delegation) GetValidator() sdk.AccAddress { return d.ValidatorAddr } +func (d Delegation) GetValidator() sdk.ValAddress { return d.ValidatorAddr } func (d Delegation) GetBondShares() sdk.Dec { return d.Shares } // HumanReadableString returns a human readable string representation of a @@ -99,7 +100,7 @@ func (d Delegation) HumanReadableString() (string, error) { // UnbondingDelegation reflects a delegation's passive unbonding queue. type UnbondingDelegation struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` // delegator - ValidatorAddr sdk.AccAddress `json:"validator_addr"` // validator unbonding from owner addr + ValidatorAddr sdk.ValAddress `json:"validator_addr"` // validator unbonding from operator addr CreationHeight int64 `json:"creation_height"` // height which the unbonding took place MinTime time.Time `json:"min_time"` // unix time for unbonding completion InitialBalance sdk.Coin `json:"initial_balance"` // atoms initially scheduled to receive at completion @@ -147,7 +148,7 @@ func UnmarshalUBD(cdc *wire.Codec, key, value []byte) (ubd UnbondingDelegation, return } delAddr := sdk.AccAddress(addrs[:sdk.AddrLen]) - valAddr := sdk.AccAddress(addrs[sdk.AddrLen:]) + valAddr := sdk.ValAddress(addrs[sdk.AddrLen:]) return UnbondingDelegation{ DelegatorAddr: delAddr, @@ -184,8 +185,8 @@ func (d UnbondingDelegation) HumanReadableString() (string, error) { // Redelegation reflects a delegation's passive re-delegation queue. type Redelegation struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` // delegator - ValidatorSrcAddr sdk.AccAddress `json:"validator_src_addr"` // validator redelegation source owner addr - ValidatorDstAddr sdk.AccAddress `json:"validator_dst_addr"` // validator redelegation destination owner addr + ValidatorSrcAddr sdk.ValAddress `json:"validator_src_addr"` // validator redelegation source operator addr + ValidatorDstAddr sdk.ValAddress `json:"validator_dst_addr"` // validator redelegation destination operator addr CreationHeight int64 `json:"creation_height"` // height which the redelegation took place MinTime time.Time `json:"min_time"` // unix time for redelegation completion InitialBalance sdk.Coin `json:"initial_balance"` // initial balance when redelegation started @@ -239,8 +240,8 @@ func UnmarshalRED(cdc *wire.Codec, key, value []byte) (red Redelegation, err err return } delAddr := sdk.AccAddress(addrs[:sdk.AddrLen]) - valSrcAddr := sdk.AccAddress(addrs[sdk.AddrLen : 2*sdk.AddrLen]) - valDstAddr := sdk.AccAddress(addrs[2*sdk.AddrLen:]) + valSrcAddr := sdk.ValAddress(addrs[sdk.AddrLen : 2*sdk.AddrLen]) + valDstAddr := sdk.ValAddress(addrs[2*sdk.AddrLen:]) return Redelegation{ DelegatorAddr: delAddr, diff --git a/x/stake/types/delegation_test.go b/x/stake/types/delegation_test.go index 5624b71015e6..8e0dda7e247b 100644 --- a/x/stake/types/delegation_test.go +++ b/x/stake/types/delegation_test.go @@ -10,12 +10,12 @@ import ( func TestDelegationEqual(t *testing.T) { d1 := Delegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorAddr: addr2, Shares: sdk.NewDec(100), } d2 := Delegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorAddr: addr2, Shares: sdk.NewDec(100), } @@ -23,7 +23,7 @@ func TestDelegationEqual(t *testing.T) { ok := d1.Equal(d2) require.True(t, ok) - d2.ValidatorAddr = addr3 + d2.ValidatorAddr = sdk.ValAddress(addr3) d2.Shares = sdk.NewDec(200) ok = d1.Equal(d2) @@ -32,7 +32,7 @@ func TestDelegationEqual(t *testing.T) { func TestDelegationHumanReadableString(t *testing.T) { d := Delegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorAddr: addr2, Shares: sdk.NewDec(100), } @@ -46,18 +46,18 @@ func TestDelegationHumanReadableString(t *testing.T) { func TestUnbondingDelegationEqual(t *testing.T) { ud1 := UnbondingDelegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorAddr: addr2, } ud2 := UnbondingDelegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorAddr: addr2, } ok := ud1.Equal(ud2) require.True(t, ok) - ud2.ValidatorAddr = addr3 + ud2.ValidatorAddr = sdk.ValAddress(addr3) ud2.MinTime = time.Unix(20*20*2, 0) ok = ud1.Equal(ud2) @@ -66,7 +66,7 @@ func TestUnbondingDelegationEqual(t *testing.T) { func TestUnbondingDelegationHumanReadableString(t *testing.T) { ud := UnbondingDelegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorAddr: addr2, } @@ -79,12 +79,12 @@ func TestUnbondingDelegationHumanReadableString(t *testing.T) { func TestRedelegationEqual(t *testing.T) { r1 := Redelegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorSrcAddr: addr2, ValidatorDstAddr: addr3, } r2 := Redelegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorSrcAddr: addr2, ValidatorDstAddr: addr3, } @@ -102,7 +102,7 @@ func TestRedelegationEqual(t *testing.T) { func TestRedelegationHumanReadableString(t *testing.T) { r := Redelegation{ - DelegatorAddr: addr1, + DelegatorAddr: sdk.AccAddress(addr1), ValidatorSrcAddr: addr2, ValidatorDstAddr: addr3, SharesDst: sdk.NewDec(10), diff --git a/x/stake/types/msg.go b/x/stake/types/msg.go index 282000294bce..71a8c86314a7 100644 --- a/x/stake/types/msg.go +++ b/x/stake/types/msg.go @@ -1,7 +1,7 @@ package types import ( - "reflect" + "bytes" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" @@ -21,30 +21,27 @@ var _, _ sdk.Msg = &MsgBeginRedelegate{}, &MsgCompleteRedelegate{} type MsgCreateValidator struct { Description DelegatorAddr sdk.AccAddress `json:"delegator_address"` - ValidatorAddr sdk.AccAddress `json:"validator_address"` + ValidatorAddr sdk.ValAddress `json:"validator_address"` PubKey crypto.PubKey `json:"pubkey"` Delegation sdk.Coin `json:"delegation"` } // Default way to create validator. Delegator address and validator address are the same -func NewMsgCreateValidator(validatorAddr sdk.AccAddress, pubkey crypto.PubKey, +func NewMsgCreateValidator(valAddr sdk.ValAddress, pubkey crypto.PubKey, selfDelegation sdk.Coin, description Description) MsgCreateValidator { - return MsgCreateValidator{ - Description: description, - DelegatorAddr: validatorAddr, - ValidatorAddr: validatorAddr, - PubKey: pubkey, - Delegation: selfDelegation, - } + + return NewMsgCreateValidatorOnBehalfOf( + sdk.AccAddress(valAddr), valAddr, pubkey, selfDelegation, description, + ) } // Creates validator msg by delegator address on behalf of validator address -func NewMsgCreateValidatorOnBehalfOf(delegatorAddr, validatorAddr sdk.AccAddress, pubkey crypto.PubKey, - delegation sdk.Coin, description Description) MsgCreateValidator { +func NewMsgCreateValidatorOnBehalfOf(delAddr sdk.AccAddress, valAddr sdk.ValAddress, + pubkey crypto.PubKey, delegation sdk.Coin, description Description) MsgCreateValidator { return MsgCreateValidator{ Description: description, - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, PubKey: pubkey, Delegation: delegation, } @@ -57,9 +54,11 @@ func (msg MsgCreateValidator) Type() string { return MsgType } func (msg MsgCreateValidator) GetSigners() []sdk.AccAddress { // delegator is first signer so delegator pays fees addrs := []sdk.AccAddress{msg.DelegatorAddr} - if !reflect.DeepEqual(msg.DelegatorAddr, msg.ValidatorAddr) { - // if validator addr is not same as delegator addr, validator must sign msg as well - addrs = append(addrs, msg.ValidatorAddr) + + if !bytes.Equal(msg.DelegatorAddr.Bytes(), msg.ValidatorAddr.Bytes()) { + // if validator addr is not same as delegator addr, validator must sign + // msg as well + addrs = append(addrs, sdk.AccAddress(msg.ValidatorAddr)) } return addrs } @@ -69,13 +68,13 @@ func (msg MsgCreateValidator) GetSignBytes() []byte { b, err := MsgCdc.MarshalJSON(struct { Description DelegatorAddr sdk.AccAddress `json:"delegator_address"` - ValidatorAddr sdk.AccAddress `json:"validator_address"` + ValidatorAddr sdk.ValAddress `json:"validator_address"` PubKey string `json:"pubkey"` Delegation sdk.Coin `json:"delegation"` }{ Description: msg.Description, ValidatorAddr: msg.ValidatorAddr, - PubKey: sdk.MustBech32ifyValPub(msg.PubKey), + PubKey: sdk.MustBech32ifyConsPub(msg.PubKey), Delegation: msg.Delegation, }) if err != nil { @@ -107,27 +106,27 @@ func (msg MsgCreateValidator) ValidateBasic() sdk.Error { // MsgEditValidator - struct for editing a validator type MsgEditValidator struct { Description - ValidatorAddr sdk.AccAddress `json:"address"` + ValidatorAddr sdk.ValAddress `json:"address"` } -func NewMsgEditValidator(validatorAddr sdk.AccAddress, description Description) MsgEditValidator { +func NewMsgEditValidator(valAddr sdk.ValAddress, description Description) MsgEditValidator { return MsgEditValidator{ Description: description, - ValidatorAddr: validatorAddr, + ValidatorAddr: valAddr, } } //nolint func (msg MsgEditValidator) Type() string { return MsgType } func (msg MsgEditValidator) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.ValidatorAddr} + return []sdk.AccAddress{sdk.AccAddress(msg.ValidatorAddr)} } // get the bytes for the message signer to sign on func (msg MsgEditValidator) GetSignBytes() []byte { b, err := MsgCdc.MarshalJSON(struct { Description - ValidatorAddr sdk.AccAddress `json:"address"` + ValidatorAddr sdk.ValAddress `json:"address"` }{ Description: msg.Description, ValidatorAddr: msg.ValidatorAddr, @@ -155,14 +154,14 @@ func (msg MsgEditValidator) ValidateBasic() sdk.Error { // MsgDelegate - struct for bonding transactions type MsgDelegate struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorAddr sdk.AccAddress `json:"validator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` Delegation sdk.Coin `json:"delegation"` } -func NewMsgDelegate(delegatorAddr, validatorAddr sdk.AccAddress, delegation sdk.Coin) MsgDelegate { +func NewMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, delegation sdk.Coin) MsgDelegate { return MsgDelegate{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, Delegation: delegation, } } @@ -201,18 +200,18 @@ func (msg MsgDelegate) ValidateBasic() sdk.Error { // MsgDelegate - struct for bonding transactions type MsgBeginRedelegate struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorSrcAddr sdk.AccAddress `json:"validator_src_addr"` - ValidatorDstAddr sdk.AccAddress `json:"validator_dst_addr"` + ValidatorSrcAddr sdk.ValAddress `json:"validator_src_addr"` + ValidatorDstAddr sdk.ValAddress `json:"validator_dst_addr"` SharesAmount sdk.Dec `json:"shares_amount"` } -func NewMsgBeginRedelegate(delegatorAddr, validatorSrcAddr, - validatorDstAddr sdk.AccAddress, sharesAmount sdk.Dec) MsgBeginRedelegate { +func NewMsgBeginRedelegate(delAddr sdk.AccAddress, valSrcAddr, + valDstAddr sdk.ValAddress, sharesAmount sdk.Dec) MsgBeginRedelegate { return MsgBeginRedelegate{ - DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + DelegatorAddr: delAddr, + ValidatorSrcAddr: valSrcAddr, + ValidatorDstAddr: valDstAddr, SharesAmount: sharesAmount, } } @@ -227,8 +226,8 @@ func (msg MsgBeginRedelegate) GetSigners() []sdk.AccAddress { func (msg MsgBeginRedelegate) GetSignBytes() []byte { b, err := MsgCdc.MarshalJSON(struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorSrcAddr sdk.AccAddress `json:"validator_src_addr"` - ValidatorDstAddr sdk.AccAddress `json:"validator_dst_addr"` + ValidatorSrcAddr sdk.ValAddress `json:"validator_src_addr"` + ValidatorDstAddr sdk.ValAddress `json:"validator_dst_addr"` SharesAmount string `json:"shares"` }{ DelegatorAddr: msg.DelegatorAddr, @@ -262,17 +261,15 @@ func (msg MsgBeginRedelegate) ValidateBasic() sdk.Error { // MsgDelegate - struct for bonding transactions type MsgCompleteRedelegate struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorSrcAddr sdk.AccAddress `json:"validator_source_addr"` - ValidatorDstAddr sdk.AccAddress `json:"validator_destination_addr"` + ValidatorSrcAddr sdk.ValAddress `json:"validator_source_addr"` + ValidatorDstAddr sdk.ValAddress `json:"validator_destination_addr"` } -func NewMsgCompleteRedelegate(delegatorAddr, validatorSrcAddr, - validatorDstAddr sdk.AccAddress) MsgCompleteRedelegate { - +func NewMsgCompleteRedelegate(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) MsgCompleteRedelegate { return MsgCompleteRedelegate{ - DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + DelegatorAddr: delAddr, + ValidatorSrcAddr: valSrcAddr, + ValidatorDstAddr: valDstAddr, } } @@ -310,14 +307,14 @@ func (msg MsgCompleteRedelegate) ValidateBasic() sdk.Error { // MsgBeginUnbonding - struct for unbonding transactions type MsgBeginUnbonding struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorAddr sdk.AccAddress `json:"validator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` SharesAmount sdk.Dec `json:"shares_amount"` } -func NewMsgBeginUnbonding(delegatorAddr, validatorAddr sdk.AccAddress, sharesAmount sdk.Dec) MsgBeginUnbonding { +func NewMsgBeginUnbonding(delAddr sdk.AccAddress, valAddr sdk.ValAddress, sharesAmount sdk.Dec) MsgBeginUnbonding { return MsgBeginUnbonding{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, SharesAmount: sharesAmount, } } @@ -330,7 +327,7 @@ func (msg MsgBeginUnbonding) GetSigners() []sdk.AccAddress { return []sdk.AccAdd func (msg MsgBeginUnbonding) GetSignBytes() []byte { b, err := MsgCdc.MarshalJSON(struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorAddr sdk.AccAddress `json:"validator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` SharesAmount string `json:"shares_amount"` }{ DelegatorAddr: msg.DelegatorAddr, @@ -360,13 +357,13 @@ func (msg MsgBeginUnbonding) ValidateBasic() sdk.Error { // MsgCompleteUnbonding - struct for unbonding transactions type MsgCompleteUnbonding struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorAddr sdk.AccAddress `json:"validator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` } -func NewMsgCompleteUnbonding(delegatorAddr, validatorAddr sdk.AccAddress) MsgCompleteUnbonding { +func NewMsgCompleteUnbonding(delAddr sdk.AccAddress, valAddr sdk.ValAddress) MsgCompleteUnbonding { return MsgCompleteUnbonding{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, } } diff --git a/x/stake/types/msg_test.go b/x/stake/types/msg_test.go index 2be34fb20754..eb66c04220bd 100644 --- a/x/stake/types/msg_test.go +++ b/x/stake/types/msg_test.go @@ -19,7 +19,7 @@ var ( func TestMsgCreateValidator(t *testing.T) { tests := []struct { name, moniker, identity, website, details string - validatorAddr sdk.AccAddress + validatorAddr sdk.ValAddress pubkey crypto.PubKey bond sdk.Coin expectPass bool @@ -49,7 +49,7 @@ func TestMsgCreateValidator(t *testing.T) { func TestMsgEditValidator(t *testing.T) { tests := []struct { name, moniker, identity, website, details string - validatorAddr sdk.AccAddress + validatorAddr sdk.ValAddress expectPass bool }{ {"basic good", "a", "b", "c", "d", addr1, true}, @@ -74,20 +74,20 @@ func TestMsgCreateValidatorOnBehalfOf(t *testing.T) { tests := []struct { name, moniker, identity, website, details string delegatorAddr sdk.AccAddress - validatorAddr sdk.AccAddress + validatorAddr sdk.ValAddress validatorPubKey crypto.PubKey bond sdk.Coin expectPass bool }{ - {"basic good", "a", "b", "c", "d", addr1, addr2, pk2, coinPos, true}, - {"partial description", "", "", "c", "", addr1, addr2, pk2, coinPos, true}, - {"empty description", "", "", "", "", addr1, addr2, pk2, coinPos, false}, - {"empty delegator address", "a", "b", "c", "d", emptyAddr, addr2, pk2, coinPos, false}, - {"empty validator address", "a", "b", "c", "d", addr1, emptyAddr, pk2, coinPos, false}, - {"empty pubkey", "a", "b", "c", "d", addr1, addr2, emptyPubkey, coinPos, true}, - {"empty bond", "a", "b", "c", "d", addr1, addr2, pk2, coinZero, false}, - {"negative bond", "a", "b", "c", "d", addr1, addr2, pk2, coinNeg, false}, - {"negative bond", "a", "b", "c", "d", addr1, addr2, pk2, coinNeg, false}, + {"basic good", "a", "b", "c", "d", sdk.AccAddress(addr1), addr2, pk2, coinPos, true}, + {"partial description", "", "", "c", "", sdk.AccAddress(addr1), addr2, pk2, coinPos, true}, + {"empty description", "", "", "", "", sdk.AccAddress(addr1), addr2, pk2, coinPos, false}, + {"empty delegator address", "a", "b", "c", "d", sdk.AccAddress(emptyAddr), addr2, pk2, coinPos, false}, + {"empty validator address", "a", "b", "c", "d", sdk.AccAddress(addr1), emptyAddr, pk2, coinPos, false}, + {"empty pubkey", "a", "b", "c", "d", sdk.AccAddress(addr1), addr2, emptyPubkey, coinPos, true}, + {"empty bond", "a", "b", "c", "d", sdk.AccAddress(addr1), addr2, pk2, coinZero, false}, + {"negative bond", "a", "b", "c", "d", sdk.AccAddress(addr1), addr2, pk2, coinNeg, false}, + {"negative bond", "a", "b", "c", "d", sdk.AccAddress(addr1), addr2, pk2, coinNeg, false}, } for _, tc := range tests { @@ -102,11 +102,11 @@ func TestMsgCreateValidatorOnBehalfOf(t *testing.T) { msg := NewMsgCreateValidator(addr1, pk1, coinPos, Description{}) addrs := msg.GetSigners() - require.Equal(t, []sdk.AccAddress{addr1}, addrs, "Signers on default msg is wrong") + require.Equal(t, []sdk.AccAddress{sdk.AccAddress(addr1)}, addrs, "Signers on default msg is wrong") - msg = NewMsgCreateValidatorOnBehalfOf(addr2, addr1, pk1, coinPos, Description{}) + msg = NewMsgCreateValidatorOnBehalfOf(sdk.AccAddress(addr2), addr1, pk1, coinPos, Description{}) addrs = msg.GetSigners() - require.Equal(t, []sdk.AccAddress{addr2, addr1}, addrs, "Signers for onbehalfof msg is wrong") + require.Equal(t, []sdk.AccAddress{sdk.AccAddress(addr2), sdk.AccAddress(addr1)}, addrs, "Signers for onbehalfof msg is wrong") } // test ValidateBasic for MsgDelegate @@ -114,16 +114,16 @@ func TestMsgDelegate(t *testing.T) { tests := []struct { name string delegatorAddr sdk.AccAddress - validatorAddr sdk.AccAddress + validatorAddr sdk.ValAddress bond sdk.Coin expectPass bool }{ - {"basic good", addr1, addr2, coinPos, true}, - {"self bond", addr1, addr1, coinPos, true}, - {"empty delegator", emptyAddr, addr1, coinPos, false}, - {"empty validator", addr1, emptyAddr, coinPos, false}, - {"empty bond", addr1, addr2, coinZero, false}, - {"negative bond", addr1, addr2, coinNeg, false}, + {"basic good", sdk.AccAddress(addr1), addr2, coinPos, true}, + {"self bond", sdk.AccAddress(addr1), addr1, coinPos, true}, + {"empty delegator", sdk.AccAddress(emptyAddr), addr1, coinPos, false}, + {"empty validator", sdk.AccAddress(addr1), emptyAddr, coinPos, false}, + {"empty bond", sdk.AccAddress(addr1), addr2, coinZero, false}, + {"negative bond", sdk.AccAddress(addr1), addr2, coinNeg, false}, } for _, tc := range tests { @@ -141,17 +141,17 @@ func TestMsgBeginRedelegate(t *testing.T) { tests := []struct { name string delegatorAddr sdk.AccAddress - validatorSrcAddr sdk.AccAddress - validatorDstAddr sdk.AccAddress + validatorSrcAddr sdk.ValAddress + validatorDstAddr sdk.ValAddress sharesAmount sdk.Dec expectPass bool }{ - {"regular", addr1, addr2, addr3, sdk.NewDecWithPrec(1, 1), true}, - {"negative decimal", addr1, addr2, addr3, sdk.NewDecWithPrec(-1, 1), false}, - {"zero amount", addr1, addr2, addr3, sdk.ZeroDec(), false}, - {"empty delegator", emptyAddr, addr1, addr3, sdk.NewDecWithPrec(1, 1), false}, - {"empty source validator", addr1, emptyAddr, addr3, sdk.NewDecWithPrec(1, 1), false}, - {"empty destination validator", addr1, addr2, emptyAddr, sdk.NewDecWithPrec(1, 1), false}, + {"regular", sdk.AccAddress(addr1), addr2, addr3, sdk.NewDecWithPrec(1, 1), true}, + {"negative decimal", sdk.AccAddress(addr1), addr2, addr3, sdk.NewDecWithPrec(-1, 1), false}, + {"zero amount", sdk.AccAddress(addr1), addr2, addr3, sdk.ZeroDec(), false}, + {"empty delegator", sdk.AccAddress(emptyAddr), addr1, addr3, sdk.NewDecWithPrec(1, 1), false}, + {"empty source validator", sdk.AccAddress(addr1), emptyAddr, addr3, sdk.NewDecWithPrec(1, 1), false}, + {"empty destination validator", sdk.AccAddress(addr1), addr2, emptyAddr, sdk.NewDecWithPrec(1, 1), false}, } for _, tc := range tests { @@ -169,14 +169,14 @@ func TestMsgCompleteRedelegate(t *testing.T) { tests := []struct { name string delegatorAddr sdk.AccAddress - validatorSrcAddr sdk.AccAddress - validatorDstAddr sdk.AccAddress + validatorSrcAddr sdk.ValAddress + validatorDstAddr sdk.ValAddress expectPass bool }{ - {"regular", addr1, addr2, addr3, true}, - {"empty delegator", emptyAddr, addr1, addr3, false}, - {"empty source validator", addr1, emptyAddr, addr3, false}, - {"empty destination validator", addr1, addr2, emptyAddr, false}, + {"regular", sdk.AccAddress(addr1), addr2, addr3, true}, + {"empty delegator", sdk.AccAddress(emptyAddr), addr1, addr3, false}, + {"empty source validator", sdk.AccAddress(addr1), emptyAddr, addr3, false}, + {"empty destination validator", sdk.AccAddress(addr1), addr2, emptyAddr, false}, } for _, tc := range tests { @@ -194,15 +194,15 @@ func TestMsgBeginUnbonding(t *testing.T) { tests := []struct { name string delegatorAddr sdk.AccAddress - validatorAddr sdk.AccAddress + validatorAddr sdk.ValAddress sharesAmount sdk.Dec expectPass bool }{ - {"regular", addr1, addr2, sdk.NewDecWithPrec(1, 1), true}, - {"negative decimal", addr1, addr2, sdk.NewDecWithPrec(-1, 1), false}, - {"zero amount", addr1, addr2, sdk.ZeroDec(), false}, - {"empty delegator", emptyAddr, addr1, sdk.NewDecWithPrec(1, 1), false}, - {"empty validator", addr1, emptyAddr, sdk.NewDecWithPrec(1, 1), false}, + {"regular", sdk.AccAddress(addr1), addr2, sdk.NewDecWithPrec(1, 1), true}, + {"negative decimal", sdk.AccAddress(addr1), addr2, sdk.NewDecWithPrec(-1, 1), false}, + {"zero amount", sdk.AccAddress(addr1), addr2, sdk.ZeroDec(), false}, + {"empty delegator", sdk.AccAddress(emptyAddr), addr1, sdk.NewDecWithPrec(1, 1), false}, + {"empty validator", sdk.AccAddress(addr1), emptyAddr, sdk.NewDecWithPrec(1, 1), false}, } for _, tc := range tests { @@ -220,12 +220,12 @@ func TestMsgCompleteUnbonding(t *testing.T) { tests := []struct { name string delegatorAddr sdk.AccAddress - validatorAddr sdk.AccAddress + validatorAddr sdk.ValAddress expectPass bool }{ - {"regular", addr1, addr2, true}, - {"empty delegator", emptyAddr, addr1, false}, - {"empty validator", addr1, emptyAddr, false}, + {"regular", sdk.AccAddress(addr1), addr2, true}, + {"empty delegator", sdk.AccAddress(emptyAddr), addr1, false}, + {"empty validator", sdk.AccAddress(addr1), emptyAddr, false}, } for _, tc := range tests { diff --git a/x/stake/types/test_utils.go b/x/stake/types/test_utils.go index 02c4d4fca9a4..b9d77ce9f55a 100644 --- a/x/stake/types/test_utils.go +++ b/x/stake/types/test_utils.go @@ -10,10 +10,10 @@ var ( pk1 = ed25519.GenPrivKey().PubKey() pk2 = ed25519.GenPrivKey().PubKey() pk3 = ed25519.GenPrivKey().PubKey() - addr1 = sdk.AccAddress(pk1.Address()) - addr2 = sdk.AccAddress(pk2.Address()) - addr3 = sdk.AccAddress(pk3.Address()) + addr1 = sdk.ValAddress(pk1.Address()) + addr2 = sdk.ValAddress(pk2.Address()) + addr3 = sdk.ValAddress(pk3.Address()) - emptyAddr sdk.AccAddress + emptyAddr sdk.ValAddress emptyPubkey crypto.PubKey ) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 9d0435752866..2cb952db2859 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -20,7 +20,7 @@ import ( // exchange rate. Voting power can be calculated as total bonds multiplied by // exchange rate. type Validator struct { - Operator sdk.AccAddress `json:"operator"` // sender of BondTx - UnbondTx returns here + Operator sdk.ValAddress `json:"operator"` // sender of BondTx - UnbondTx returns here PubKey crypto.PubKey `json:"pub_key"` // pubkey of validator Jailed bool `json:"jailed"` // has the validator been jailed from bonded status? @@ -43,7 +43,7 @@ type Validator struct { } // NewValidator - initialize a new validator -func NewValidator(operator sdk.AccAddress, pubKey crypto.PubKey, description Description) Validator { +func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Description) Validator { return Validator{ Operator: operator, PubKey: pubKey, @@ -147,14 +147,14 @@ func UnmarshalValidator(cdc *wire.Codec, operatorAddr, value []byte) (validator // validator. An error is returned if the operator or the operator's public key // cannot be converted to Bech32 format. func (v Validator) HumanReadableString() (string, error) { - bechVal, err := sdk.Bech32ifyValPub(v.PubKey) + bechConsPubKey, err := sdk.Bech32ifyConsPub(v.PubKey) if err != nil { return "", err } resp := "Validator \n" resp += fmt.Sprintf("Operator: %s\n", v.Operator) - resp += fmt.Sprintf("Validator: %s\n", bechVal) + resp += fmt.Sprintf("Validator: %s\n", bechConsPubKey) resp += fmt.Sprintf("Jailed: %v\n", v.Jailed) resp += fmt.Sprintf("Status: %s\n", sdk.BondStatusToString(v.Status)) resp += fmt.Sprintf("Tokens: %s\n", v.Tokens.String()) @@ -175,7 +175,7 @@ func (v Validator) HumanReadableString() (string, error) { // validator struct for bech output type BechValidator struct { - Operator sdk.AccAddress `json:"operator"` // in bech32 + Operator sdk.ValAddress `json:"operator"` // in bech32 PubKey string `json:"pub_key"` // in bech32 Jailed bool `json:"jailed"` // has the validator been jailed from bonded status? @@ -199,14 +199,14 @@ type BechValidator struct { // get the bech validator from the the regular validator func (v Validator) Bech32Validator() (BechValidator, error) { - bechValPubkey, err := sdk.Bech32ifyValPub(v.PubKey) + bechConsPubKey, err := sdk.Bech32ifyConsPub(v.PubKey) if err != nil { return BechValidator{}, err } return BechValidator{ Operator: v.Operator, - PubKey: bechValPubkey, + PubKey: bechConsPubKey, Jailed: v.Jailed, Status: v.Status, @@ -432,7 +432,7 @@ var _ sdk.Validator = Validator{} func (v Validator) GetJailed() bool { return v.Jailed } func (v Validator) GetMoniker() string { return v.Description.Moniker } func (v Validator) GetStatus() sdk.BondStatus { return v.Status } -func (v Validator) GetOperator() sdk.AccAddress { return v.Operator } +func (v Validator) GetOperator() sdk.ValAddress { return v.Operator } func (v Validator) GetPubKey() crypto.PubKey { return v.PubKey } func (v Validator) GetPower() sdk.Dec { return v.BondedTokens() } func (v Validator) GetTokens() sdk.Dec { return v.Tokens }