x/authz: Add DelegateAuthorization, UndelegateAuthorization (#8472)

* add proto msgs

* add delegate authorization

* add delegate authorization tests

* add delegate authorization to cli

* fix lint

* add cli tests

* made max_tokens optional

* add tests

* add table tests

* resolve conflicts

* add undelegate authorization

* proto-gen

* fix errors

* fix lint

* resolve conflicts

* fix imports

* add allow & deny lists to delegate authorization

* refactor authorizations

* proto-docs

* fix lint

* review changes

* golint

* proto lint

* review changes

* add staking authorization

* review changes

* fix protos

* review changes

* review changes

* clean docs

* proto-docs

* proto-gen

* proto-docs
This commit is contained in:
MD Aleem 2021-02-20 12:27:57 +05:30 committed by GitHub
parent 7e481cc716
commit 7df79b55f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 11946 additions and 9867 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,6 @@
syntax = "proto3"; syntax = "proto3";
package cosmos.authz.v1beta1; package cosmos.authz.v1beta1;
import "cosmos/base/v1beta1/coin.proto";
import "cosmos_proto/cosmos.proto"; import "cosmos_proto/cosmos.proto";
import "google/protobuf/timestamp.proto"; import "google/protobuf/timestamp.proto";
import "gogoproto/gogo.proto"; import "gogoproto/gogo.proto";
@ -9,15 +8,6 @@ import "google/protobuf/any.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/authz/types"; option go_package = "github.com/cosmos/cosmos-sdk/x/authz/types";
// SendAuthorization allows the grantee to spend up to spend_limit coins from
// the granter's account.
message SendAuthorization {
option (cosmos_proto.implements_interface) = "Authorization";
repeated cosmos.base.v1beta1.Coin spend_limit = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
}
// GenericAuthorization gives the grantee unrestricted permissions to execute // GenericAuthorization gives the grantee unrestricted permissions to execute
// the provided method on behalf of the granter's account. // the provided method on behalf of the granter's account.
message GenericAuthorization { message GenericAuthorization {

View File

@ -5,7 +5,6 @@ import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto"; import "google/protobuf/any.proto";
import "gogoproto/gogo.proto"; import "gogoproto/gogo.proto";
import "cosmos_proto/cosmos.proto"; import "cosmos_proto/cosmos.proto";
import "cosmos/authz/v1beta1/tx.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/authz/types"; option go_package = "github.com/cosmos/cosmos-sdk/x/authz/types";

View File

@ -1,10 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package cosmos.authz.v1beta1; package cosmos.authz.v1beta1;
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "google/api/annotations.proto"; import "google/api/annotations.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/query/v1beta1/pagination.proto"; import "cosmos/base/query/v1beta1/pagination.proto";
import "cosmos/authz/v1beta1/authz.proto"; import "cosmos/authz/v1beta1/authz.proto";

View File

@ -0,0 +1,17 @@
syntax = "proto3";
package cosmos.bank.v1beta1;
import "gogoproto/gogo.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/v1beta1/coin.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/bank/types";
// SendAuthorization allows the grantee to spend up to spend_limit coins from
// the granter's account.
message SendAuthorization {
option (cosmos_proto.implements_interface) = "Authorization";
repeated cosmos.base.v1beta1.Coin spend_limit = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
}

View File

@ -0,0 +1,43 @@
syntax = "proto3";
package cosmos.staking.v1beta1;
import "gogoproto/gogo.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/v1beta1/coin.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/staking/types";
// StakeAuthorization defines authorization for delegate/undelegate/redelegate.
message StakeAuthorization {
option (cosmos_proto.implements_interface) = "Authorization";
// max_tokens specifies the maximum amount of tokens can be delegate to a validator. If it is
// empty, there is no spend limit and any amount of coins can be delegated.
cosmos.base.v1beta1.Coin max_tokens = 1 [(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin"];
// validators is the oneof that represents either allow_list or deny_list
oneof validators {
// allow_list specifies list of validator addresses to whom grantee can delegate tokens on behalf of granter's
// account.
Validators allow_list = 2;
// deny_list specifies list of validator addresses to whom grantee can not delegate tokens.
Validators deny_list = 3;
}
// Validators defines list of validator addresses.
message Validators {
repeated string address = 1;
}
// authorization_type defines one of AuthorizationType.
AuthorizationType authorization_type = 4;
}
// AuthorizationType defines the type of staking module authorization type
enum AuthorizationType {
// AUTHORIZATION_TYPE_UNSPECIFIED specifies an unknown authorization type
AUTHORIZATION_TYPE_UNSPECIFIED = 0;
// AUTHORIZATION_TYPE_DELEGATE defines an authorization type for Msg/Delegate
AUTHORIZATION_TYPE_DELEGATE = 1;
// AUTHORIZATION_TYPE_UNDELEGATE defines an authorization type for Msg/Undelegate
AUTHORIZATION_TYPE_UNDELEGATE = 2;
// AUTHORIZATION_TYPE_REDELEGATE defines an authorization type for Msg/BeginRedelegate
AUTHORIZATION_TYPE_REDELEGATE = 3;
}

View File

@ -12,6 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
// GetQueryCmd returns the cli query commands for this module // GetQueryCmd returns the cli query commands for this module
@ -97,7 +98,7 @@ func GetCmdQueryAuthorization() *cobra.Command {
fmt.Sprintf(`Query authorization for a granter-grantee pair that matches the given msg-type: fmt.Sprintf(`Query authorization for a granter-grantee pair that matches the given msg-type:
Example: Example:
$ %s query %s authorization cosmos1skjw.. cosmos1skjwj.. %s $ %s query %s authorization cosmos1skjw.. cosmos1skjwj.. %s
`, version.AppName, types.ModuleName, types.SendAuthorization{}.MethodName()), `, version.AppName, types.ModuleName, bank.SendAuthorization{}.MethodName()),
), ),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd) clientCtx, err := client.GetClientQueryContext(cmd)

View File

@ -0,0 +1,186 @@
// +build norace
package cli_test
import (
"fmt"
"strings"
"time"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz/client/cli"
authztestutil "github.com/cosmos/cosmos-sdk/x/authz/client/testutil"
"github.com/cosmos/cosmos-sdk/x/authz/types"
)
func (s *IntegrationTestSuite) TestQueryAuthorizations() {
val := s.network.Validators[0]
grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
_, err := authztestutil.ExecGrantAuthorization(
val,
[]string{
grantee.String(),
"send",
fmt.Sprintf("--%s=100steak", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
testCases := []struct {
name string
args []string
expectErr bool
expErrMsg string
}{
{
"Error: Invalid grantee",
[]string{
val.Address.String(),
"invalid grantee",
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"decoding bech32 failed: invalid character in string: ' '",
},
{
"Error: Invalid granter",
[]string{
"invalid granter",
grantee.String(),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"decoding bech32 failed: invalid character in string: ' '",
},
{
"Valid txn (json)",
[]string{
val.Address.String(),
grantee.String(),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
false,
``,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryAuthorizations()
clientCtx := val.ClientCtx
resp, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
s.Require().Contains(string(resp.Bytes()), tc.expErrMsg)
} else {
s.Require().NoError(err)
var grants types.QueryAuthorizationsResponse
err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(resp.Bytes(), &grants)
s.Require().NoError(err)
}
})
}
}
func (s *IntegrationTestSuite) TestQueryAuthorization() {
val := s.network.Validators[0]
grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
_, err := authztestutil.ExecGrantAuthorization(
val,
[]string{
grantee.String(),
"send",
fmt.Sprintf("--%s=100steak", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
testCases := []struct {
name string
args []string
expectErr bool
expectedOutput string
}{
{
"Error: Invalid grantee",
[]string{
val.Address.String(),
"invalid grantee",
typeMsgSend,
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"",
},
{
"Error: Invalid granter",
[]string{
"invalid granter",
grantee.String(),
typeMsgSend,
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"",
},
{
"no authorization found",
[]string{
val.Address.String(),
grantee.String(),
"typeMsgSend",
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"",
},
{
"Valid txn (json)",
[]string{
val.Address.String(),
grantee.String(),
typeMsgSend,
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
false,
`{"@type":"/cosmos.bank.v1beta1.SendAuthorization","spend_limit":[{"denom":"steak","amount":"100"}]}`,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryAuthorization()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
s.Require().Contains(strings.TrimSpace(out.String()), tc.expectedOutput)
}
})
}
}

View File

@ -16,12 +16,20 @@ import (
"github.com/cosmos/cosmos-sdk/types/msgservice" "github.com/cosmos/cosmos-sdk/types/msgservice"
"github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/version"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client" authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
staking "github.com/cosmos/cosmos-sdk/x/staking/types"
) )
const FlagSpendLimit = "spend-limit" const FlagSpendLimit = "spend-limit"
const FlagMsgType = "msg-type" const FlagMsgType = "msg-type"
const FlagExpiration = "expiration" const FlagExpiration = "expiration"
const FlagAllowedValidators = "allowed-validators"
const FlagDenyValidators = "deny-validators"
const delegate = "delegate"
const redelegate = "redelegate"
const unbond = "unbond"
// GetTxCmd returns the transaction commands for this module // GetTxCmd returns the transaction commands for this module
func GetTxCmd() *cobra.Command { func GetTxCmd() *cobra.Command {
@ -45,7 +53,7 @@ func GetTxCmd() *cobra.Command {
func NewCmdGrantAuthorization() *cobra.Command { func NewCmdGrantAuthorization() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "grant <grantee> <authorization_type=\"send\"|\"generic\"> --from <granter>", Use: "grant <grantee> <authorization_type=\"send\"|\"generic\"|\"delegate\"|\"unbond\"|\"redelegate\"> --from <granter>",
Short: "Grant authorization to an address", Short: "Grant authorization to an address",
Long: strings.TrimSpace( Long: strings.TrimSpace(
fmt.Sprintf(`Grant authorization to an address to execute a transaction on your behalf: fmt.Sprintf(`Grant authorization to an address to execute a transaction on your behalf:
@ -53,20 +61,26 @@ func NewCmdGrantAuthorization() *cobra.Command {
Examples: Examples:
$ %s tx %s grant cosmos1skjw.. send %s --spend-limit=1000stake --from=cosmos1skl.. $ %s tx %s grant cosmos1skjw.. send %s --spend-limit=1000stake --from=cosmos1skl..
$ %s tx %s grant cosmos1skjw.. generic --msg-type=/cosmos.gov.v1beta1.Msg/Vote --from=cosmos1sk.. $ %s tx %s grant cosmos1skjw.. generic --msg-type=/cosmos.gov.v1beta1.Msg/Vote --from=cosmos1sk..
`, version.AppName, types.ModuleName, types.SendAuthorization{}.MethodName(), version.AppName, types.ModuleName), `, version.AppName, types.ModuleName, bank.SendAuthorization{}.MethodName(), version.AppName, types.ModuleName),
), ),
Args: cobra.RangeArgs(2, 3), Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd) clientCtx, err := client.GetClientTxContext(cmd)
if err != nil { if err != nil {
return err return err
} }
grantee, err := sdk.AccAddressFromBech32(args[0]) grantee, err := sdk.AccAddressFromBech32(args[0])
if err != nil { if err != nil {
return err return err
} }
var authorization types.Authorization exp, err := cmd.Flags().GetInt64(FlagExpiration)
if err != nil {
return err
}
var authorization exported.Authorization
switch args[1] { switch args[1] {
case "send": case "send":
limit, err := cmd.Flags().GetString(FlagSpendLimit) limit, err := cmd.Flags().GetString(FlagSpendLimit)
@ -83,9 +97,7 @@ Examples:
return fmt.Errorf("spend-limit should be greater than zero") return fmt.Errorf("spend-limit should be greater than zero")
} }
authorization = &types.SendAuthorization{ authorization = bank.NewSendAuthorization(spendLimit)
SpendLimit: spendLimit,
}
case "generic": case "generic":
msgType, err := cmd.Flags().GetString(FlagMsgType) msgType, err := cmd.Flags().GetString(FlagMsgType)
if err != nil { if err != nil {
@ -93,15 +105,61 @@ Examples:
} }
authorization = types.NewGenericAuthorization(msgType) authorization = types.NewGenericAuthorization(msgType)
case delegate, unbond, redelegate:
limit, err := cmd.Flags().GetString(FlagSpendLimit)
if err != nil {
return err
}
allowValidators, err := cmd.Flags().GetStringSlice(FlagAllowedValidators)
if err != nil {
return err
}
denyValidators, err := cmd.Flags().GetStringSlice(FlagDenyValidators)
if err != nil {
return err
}
var delegateLimit *sdk.Coin
if limit != "" {
spendLimit, err := sdk.ParseCoinsNormalized(limit)
if err != nil {
return err
}
if !spendLimit.IsAllPositive() {
return fmt.Errorf("spend-limit should be greater than zero")
}
delegateLimit = &spendLimit[0]
}
allowed, err := bech32toValidatorAddresses(allowValidators)
if err != nil {
return err
}
denied, err := bech32toValidatorAddresses(denyValidators)
if err != nil {
return err
}
switch args[1] {
case delegate:
authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, delegateLimit)
case unbond:
authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, delegateLimit)
default:
authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, delegateLimit)
}
if err != nil {
return err
}
default: default:
return fmt.Errorf("invalid authorization type, %s", args[1]) return fmt.Errorf("invalid authorization type, %s", args[1])
} }
exp, err := cmd.Flags().GetInt64(FlagExpiration)
if err != nil {
return err
}
msg, err := types.NewMsgGrantAuthorization(clientCtx.GetFromAddress(), grantee, authorization, time.Unix(exp, 0)) msg, err := types.NewMsgGrantAuthorization(clientCtx.GetFromAddress(), grantee, authorization, time.Unix(exp, 0))
if err != nil { if err != nil {
return err return err
@ -120,6 +178,8 @@ Examples:
flags.AddTxFlagsToCmd(cmd) flags.AddTxFlagsToCmd(cmd)
cmd.Flags().String(FlagMsgType, "", "The Msg method name for which we are creating a GenericAuthorization") cmd.Flags().String(FlagMsgType, "", "The Msg method name for which we are creating a GenericAuthorization")
cmd.Flags().String(FlagSpendLimit, "", "SpendLimit for Send Authorization, an array of Coins allowed spend") cmd.Flags().String(FlagSpendLimit, "", "SpendLimit for Send Authorization, an array of Coins allowed spend")
cmd.Flags().StringSlice(FlagAllowedValidators, []string{}, "Allowed validators addresses separated by ,")
cmd.Flags().StringSlice(FlagDenyValidators, []string{}, "Deny validators addresses separated by ,")
cmd.Flags().Int64(FlagExpiration, time.Now().AddDate(1, 0, 0).Unix(), "The Unix timestamp. Default is one year.") cmd.Flags().Int64(FlagExpiration, time.Now().AddDate(1, 0, 0).Unix(), "The Unix timestamp. Default is one year.")
return cmd return cmd
} }
@ -132,7 +192,7 @@ func NewCmdRevokeAuthorization() *cobra.Command {
fmt.Sprintf(`revoke authorization from a granter to a grantee: fmt.Sprintf(`revoke authorization from a granter to a grantee:
Example: Example:
$ %s tx %s revoke cosmos1skj.. %s --from=cosmos1skj.. $ %s tx %s revoke cosmos1skj.. %s --from=cosmos1skj..
`, version.AppName, types.ModuleName, types.SendAuthorization{}.MethodName()), `, version.AppName, types.ModuleName, bank.SendAuthorization{}.MethodName()),
), ),
Args: cobra.ExactArgs(2), Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
@ -220,3 +280,15 @@ Example:
return cmd return cmd
} }
func bech32toValidatorAddresses(validators []string) ([]sdk.ValAddress, error) {
vals := make([]sdk.ValAddress, len(validators))
for i, validator := range validators {
addr, err := sdk.ValAddressFromBech32(validator)
if err != nil {
return nil, err
}
vals[i] = addr
}
return vals, nil
}

View File

@ -1,10 +1,7 @@
// +build norace
package cli_test package cli_test
import ( import (
"fmt" "fmt"
"strings"
"testing" "testing"
"time" "time"
@ -12,8 +9,6 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keyring"
@ -26,10 +21,12 @@ import (
govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli"
govtestutil "github.com/cosmos/cosmos-sdk/x/gov/client/testutil" govtestutil "github.com/cosmos/cosmos-sdk/x/gov/client/testutil"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
stakingcli "github.com/cosmos/cosmos-sdk/x/staking/client/cli"
"github.com/cosmos/cosmos-sdk/x/authz/types" authztestutil "github.com/cosmos/cosmos-sdk/x/authz/client/testutil"
bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
type IntegrationTestSuite struct { type IntegrationTestSuite struct {
@ -68,6 +65,9 @@ func (s *IntegrationTestSuite) SetupSuite() {
s.Require().NoError(err) s.Require().NoError(err)
s.grantee = newAddr s.grantee = newAddr
_, err = s.network.WaitForHeight(1)
s.Require().NoError(err)
// create a proposal with deposit // create a proposal with deposit
_, err = govtestutil.MsgSubmitProposal(val.ClientCtx, val.Address.String(), _, err = govtestutil.MsgSubmitProposal(val.ClientCtx, val.Address.String(),
"Text Proposal 1", "Where is the title!?", govtypes.ProposalTypeText, "Text Proposal 1", "Where is the title!?", govtypes.ProposalTypeText,
@ -83,175 +83,10 @@ func (s *IntegrationTestSuite) TearDownSuite() {
s.network.Cleanup() s.network.Cleanup()
} }
var typeMsgSend = types.SendAuthorization{}.MethodName() var typeMsgSend = bank.SendAuthorization{}.MethodName()
var typeMsgVote = "/cosmos.gov.v1beta1.Msg/Vote" var typeMsgVote = "/cosmos.gov.v1beta1.Msg/Vote"
func (s *IntegrationTestSuite) TestQueryAuthorizations() { var commonFlags = []string{}
val := s.network.Validators[0]
grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
_, err := execGrantAuthorization(
val,
[]string{
grantee.String(),
"send",
fmt.Sprintf("--%s=100steak", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
testCases := []struct {
name string
args []string
expectErr bool
expErrMsg string
}{
{
"Error: Invalid grantee",
[]string{
val.Address.String(),
"invalid grantee",
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"decoding bech32 failed: invalid character in string: ' '",
},
{
"Error: Invalid granter",
[]string{
"invalid granter",
grantee.String(),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"decoding bech32 failed: invalid character in string: ' '",
},
{
"Valid txn (json)",
[]string{
val.Address.String(),
grantee.String(),
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
false,
``,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryAuthorizations()
clientCtx := val.ClientCtx
resp, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
s.Require().Contains(string(resp.Bytes()), tc.expErrMsg)
} else {
s.Require().NoError(err)
var grants types.QueryAuthorizationsResponse
err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(resp.Bytes(), &grants)
s.Require().NoError(err)
}
})
}
}
func (s *IntegrationTestSuite) TestQueryAuthorization() {
val := s.network.Validators[0]
grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
_, err := execGrantAuthorization(
val,
[]string{
grantee.String(),
"send",
fmt.Sprintf("--%s=100steak", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
testCases := []struct {
name string
args []string
expectErr bool
expectedOutput string
}{
{
"Error: Invalid grantee",
[]string{
val.Address.String(),
"invalid grantee",
typeMsgSend,
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"",
},
{
"Error: Invalid granter",
[]string{
"invalid granter",
grantee.String(),
typeMsgSend,
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"",
},
{
"no authorization found",
[]string{
val.Address.String(),
grantee.String(),
"typeMsgSend",
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
true,
"",
},
{
"Valid txn (json)",
[]string{
val.Address.String(),
grantee.String(),
typeMsgSend,
fmt.Sprintf("--%s=json", tmcli.OutputFlag),
},
false,
`{"@type":"/cosmos.authz.v1beta1.SendAuthorization","spend_limit":[{"denom":"steak","amount":"100"}]}`,
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.GetCmdQueryAuthorization()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
s.Require().Contains(strings.TrimSpace(out.String()), tc.expectedOutput)
}
})
}
}
func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() { func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
val := s.network.Validators[0] val := s.network.Validators[0]
@ -315,13 +150,94 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=invalid-msg-type", cli.FlagMsgType), fmt.Sprintf("--%s=invalid-msg-type", cli.FlagMsgType),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
}, },
&sdk.TxResponse{}, 29, &sdk.TxResponse{}, 29,
false, false,
}, },
{
"failed with error both validators not allowed",
[]string{
grantee.String(),
"delegate",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
nil, 0,
true,
},
{
"valid tx delegate authorization allowed validators",
[]string{
grantee.String(),
"delegate",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
false,
},
{
"valid tx delegate authorization deny validators",
[]string{
grantee.String(),
"delegate",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
false,
},
{
"valid tx undelegate authorization",
[]string{
grantee.String(),
"unbond",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
false,
},
{
"valid tx redelegate authorization",
[]string{
grantee.String(),
"redelegate",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
false,
},
{ {
"Valid tx send authorization", "Valid tx send authorization",
[]string{ []string{
@ -358,7 +274,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
tc := tc tc := tc
s.Run(tc.name, func() { s.Run(tc.name, func() {
clientCtx := val.ClientCtx clientCtx := val.ClientCtx
out, err := execGrantAuthorization( out, err := authztestutil.ExecGrantAuthorization(
val, val,
tc.args, tc.args,
) )
@ -374,8 +290,8 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
} }
} }
func execGrantAuthorization(val *network.Validator, args []string) (testutil.BufferWriter, error) { func execDelegate(val *network.Validator, args []string) (testutil.BufferWriter, error) {
cmd := cli.NewCmdGrantAuthorization() cmd := stakingcli.NewDelegateCmd()
clientCtx := val.ClientCtx clientCtx := val.ClientCtx
return clitestutil.ExecTestCLICmd(clientCtx, cmd, args) return clitestutil.ExecTestCLICmd(clientCtx, cmd, args)
} }
@ -387,7 +303,7 @@ func (s *IntegrationTestSuite) TestCmdRevokeAuthorizations() {
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix() twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
// send-authorization // send-authorization
_, err := execGrantAuthorization( _, err := authztestutil.ExecGrantAuthorization(
val, val,
[]string{ []string{
grantee.String(), grantee.String(),
@ -403,7 +319,7 @@ func (s *IntegrationTestSuite) TestCmdRevokeAuthorizations() {
s.Require().NoError(err) s.Require().NoError(err)
// generic-authorization // generic-authorization
_, err = execGrantAuthorization( _, err = authztestutil.ExecGrantAuthorization(
val, val,
[]string{ []string{
grantee.String(), grantee.String(),
@ -501,7 +417,7 @@ func (s *IntegrationTestSuite) TestExecAuthorizationWithExpiration() {
grantee := s.grantee grantee := s.grantee
tenSeconds := time.Now().Add(time.Second * time.Duration(10)).Unix() tenSeconds := time.Now().Add(time.Second * time.Duration(10)).Unix()
_, err := execGrantAuthorization( _, err := authztestutil.ExecGrantAuthorization(
val, val,
[]string{ []string{
grantee.String(), grantee.String(),
@ -541,7 +457,7 @@ func (s *IntegrationTestSuite) TestNewExecGenericAuthorized() {
grantee := s.grantee grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix() twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
_, err := execGrantAuthorization( _, err := authztestutil.ExecGrantAuthorization(
val, val,
[]string{ []string{
grantee.String(), grantee.String(),
@ -630,7 +546,7 @@ func (s *IntegrationTestSuite) TestNewExecGrantAuthorized() {
grantee := s.grantee grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix() twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
_, err := execGrantAuthorization( _, err := authztestutil.ExecGrantAuthorization(
val, val,
[]string{ []string{
grantee.String(), grantee.String(),
@ -662,33 +578,9 @@ func (s *IntegrationTestSuite) TestNewExecGrantAuthorized() {
testCases := []struct { testCases := []struct {
name string name string
args []string args []string
respType proto.Message
expectedCode uint32 expectedCode uint32
expectErr bool expectErr bool
}{ }{
{
"fail invalid grantee",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, "grantee"),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=true", flags.FlagGenerateOnly),
},
nil,
0,
true,
},
{
"fail invalid json path",
[]string{
"/invalid/file.txt",
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
},
nil,
0,
true,
},
{ {
"valid txn", "valid txn",
[]string{ []string{
@ -698,10 +590,21 @@ func (s *IntegrationTestSuite) TestNewExecGrantAuthorized() {
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
}, },
&sdk.TxResponse{},
0, 0,
false, false,
}, },
{
"error over spent",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
4,
false,
},
} }
for _, tc := range testCases { for _, tc := range testCases {
@ -714,10 +617,403 @@ func (s *IntegrationTestSuite) TestNewExecGrantAuthorized() {
if tc.expectErr { if tc.expectErr {
s.Require().Error(err) s.Require().Error(err)
} else { } else {
var response sdk.TxResponse
s.Require().NoError(err) s.Require().NoError(err)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), &response), out.String())
txResp := tc.respType.(*sdk.TxResponse) s.Require().Equal(tc.expectedCode, response.Code, out.String())
s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) }
})
}
}
func (s *IntegrationTestSuite) TestExecDelegateAuthorization() {
val := s.network.Validators[0]
grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
_, err := authztestutil.ExecGrantAuthorization(
val,
[]string{
grantee.String(),
"delegate",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
tokens := sdk.NewCoins(
sdk.NewCoin("stake", sdk.NewInt(50)),
)
delegateTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Delegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg := testutil.WriteToNewTempFile(s.T(), delegateTx)
testCases := []struct {
name string
args []string
expectedCode uint32
expectErr bool
errMsg string
}{
{
"valid txn: (delegate half tokens)",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
{
"valid txn: (delegate remaining half tokens)",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
{
"failed with error no authorization found",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
4,
false,
"authorization not found",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.NewCmdExecAuthorization()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
s.Require().Contains(err.Error(), tc.errMsg)
} else {
var response sdk.TxResponse
s.Require().NoError(err)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), &response), out.String())
s.Require().Equal(tc.expectedCode, response.Code, out.String())
}
})
}
//test delegate no spend-limit
_, err = authztestutil.ExecGrantAuthorization(
val,
[]string{
grantee.String(),
"delegate",
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
tokens = sdk.NewCoins(
sdk.NewCoin("stake", sdk.NewInt(50)),
)
delegateTx = fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Delegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg = testutil.WriteToNewTempFile(s.T(), delegateTx)
testCases = []struct {
name string
args []string
expectedCode uint32
expectErr bool
errMsg string
}{
{
"valid txn",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
{
"valid txn",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.NewCmdExecAuthorization()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
s.Require().Contains(err.Error(), tc.errMsg)
} else {
var response sdk.TxResponse
s.Require().NoError(err)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), &response), out.String())
s.Require().Equal(tc.expectedCode, response.Code, out.String())
}
})
}
// test delegating to denied validator
_, err = authztestutil.ExecGrantAuthorization(
val,
[]string{
grantee.String(),
"delegate",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
args := []string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
}
cmd := cli.NewCmdExecAuthorization()
out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
s.Require().NoError(err)
s.Contains(out.String(), fmt.Sprintf("cannot delegate/undelegate to %s validator", val.ValAddress.String()))
}
func (s *IntegrationTestSuite) TestExecUndelegateAuthorization() {
val := s.network.Validators[0]
grantee := s.grantee
twoHours := time.Now().Add(time.Minute * time.Duration(120)).Unix()
// granting undelegate msg authorization
_, err := authztestutil.ExecGrantAuthorization(
val,
[]string{
grantee.String(),
"unbond",
fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
// delegating stakes to validator
_, err = execDelegate(
val,
[]string{
val.ValAddress.String(),
"100stake",
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
tokens := sdk.NewCoins(
sdk.NewCoin("stake", sdk.NewInt(50)),
)
undelegateTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Undelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg := testutil.WriteToNewTempFile(s.T(), undelegateTx)
testCases := []struct {
name string
args []string
expectedCode uint32
expectErr bool
errMsg string
}{
{
"valid txn: (undelegate half tokens)",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
{
"valid txn: (undelegate remaining half tokens)",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
{
"failed with error no authorization found",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
4,
false,
"authorization not found",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.NewCmdExecAuthorization()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
s.Require().Contains(err.Error(), tc.errMsg)
} else {
var response sdk.TxResponse
s.Require().NoError(err)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), &response), out.String())
s.Require().Equal(tc.expectedCode, response.Code, out.String())
}
})
}
// grant undelegate authorization without limit
_, err = authztestutil.ExecGrantAuthorization(
val,
[]string{
grantee.String(),
"unbond",
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, fmt.Sprintf("%s", val.ValAddress.String())),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
)
s.Require().NoError(err)
tokens = sdk.NewCoins(
sdk.NewCoin("stake", sdk.NewInt(50)),
)
undelegateTx = fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Undelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg = testutil.WriteToNewTempFile(s.T(), undelegateTx)
testCases = []struct {
name string
args []string
expectedCode uint32
expectErr bool
errMsg string
}{
{
"valid txn",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
{
"valid txn",
[]string{
execMsg.Name(),
fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
},
0,
false,
"",
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
cmd := cli.NewCmdExecAuthorization()
clientCtx := val.ClientCtx
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
if tc.expectErr {
s.Require().Error(err)
s.Require().Contains(err.Error(), tc.errMsg)
} else {
var response sdk.TxResponse
s.Require().NoError(err)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), &response), out.String())
s.Require().Equal(tc.expectedCode, response.Code, out.String())
} }
}) })
} }

View File

@ -1,10 +1,9 @@
// +build norace
package rest_test package rest_test
import ( import (
"fmt" "fmt"
"testing" "testing"
"time"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
@ -14,9 +13,11 @@ import (
"github.com/cosmos/cosmos-sdk/testutil/network" "github.com/cosmos/cosmos-sdk/testutil/network"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/authz/client/cli"
authztestutil "github.com/cosmos/cosmos-sdk/x/authz/client/testutil" authztestutil "github.com/cosmos/cosmos-sdk/x/authz/client/testutil"
types "github.com/cosmos/cosmos-sdk/x/authz/types" types "github.com/cosmos/cosmos-sdk/x/authz/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
type IntegrationTestSuite struct { type IntegrationTestSuite struct {
@ -26,7 +27,8 @@ type IntegrationTestSuite struct {
grantee sdk.AccAddress grantee sdk.AccAddress
} }
var typeMsgSend = types.SendAuthorization{}.MethodName() var typeMsgSend = banktypes.SendAuthorization{}.MethodName()
var typeMsgVote = "/cosmos.gov.v1beta1.Msg/Vote"
func (s *IntegrationTestSuite) SetupSuite() { func (s *IntegrationTestSuite) SetupSuite() {
s.T().Log("setting up integration test suite") s.T().Log("setting up integration test suite")
@ -55,7 +57,16 @@ func (s *IntegrationTestSuite) SetupSuite() {
s.Require().NoError(err) s.Require().NoError(err)
// grant authorization // grant authorization
_, err = authztestutil.MsgGrantAuthorizationExec(val.ClientCtx, val.Address.String(), newAddr.String(), typeMsgSend, "100stake") _, err = authztestutil.ExecGrantAuthorization(val, []string{
newAddr.String(),
"send",
fmt.Sprintf("--%s=100steak", cli.FlagSpendLimit),
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()),
})
s.Require().NoError(err) s.Require().NoError(err)
s.grantee = newAddr s.grantee = newAddr
@ -79,37 +90,37 @@ func (s *IntegrationTestSuite) TestQueryAuthorizationGRPC() {
}{ }{
{ {
"fail invalid granter address", "fail invalid granter address",
fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?msg_type=%s", baseURL, "invalid_granter", s.grantee.String(), typeMsgSend), fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?method_name=%s", baseURL, "invalid_granter", s.grantee.String(), typeMsgSend),
true, true,
"decoding bech32 failed: invalid index of 1: invalid request", "decoding bech32 failed: invalid index of 1: invalid request",
}, },
{ {
"fail invalid grantee address", "fail invalid grantee address",
fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?msg_type=%s", baseURL, val.Address.String(), "invalid_grantee", typeMsgSend), fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?method_name=%s", baseURL, val.Address.String(), "invalid_grantee", typeMsgSend),
true, true,
"decoding bech32 failed: invalid index of 1: invalid request", "decoding bech32 failed: invalid index of 1: invalid request",
}, },
{ {
"fail with empty granter", "fail with empty granter",
fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?msg_type=%s", baseURL, "", s.grantee.String(), typeMsgSend), fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?method_name=%s", baseURL, "", s.grantee.String(), typeMsgSend),
true, true,
"Not Implemented", "Not Implemented",
}, },
{ {
"fail with empty grantee", "fail with empty grantee",
fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?msg_type=%s", baseURL, val.Address.String(), "", typeMsgSend), fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?method_name=%s", baseURL, val.Address.String(), "", typeMsgSend),
true, true,
"Not Implemented", "Not Implemented",
}, },
{ {
"fail invalid msg-type", "fail invalid msg-type",
fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?msg_type=%s", baseURL, val.Address.String(), s.grantee.String(), "invalidMsg"), fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?method_name=%s", baseURL, val.Address.String(), s.grantee.String(), "invalidMsg"),
true, true,
"rpc error: code = NotFound desc = no authorization found for invalidMsg type: key not found", "rpc error: code = NotFound desc = no authorization found for invalidMsg type: key not found",
}, },
{ {
"valid query", "valid query",
fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?msg_type=%s", baseURL, val.Address.String(), s.grantee.String(), typeMsgSend), fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grant?method_name=%s", baseURL, val.Address.String(), s.grantee.String(), typeMsgSend),
false, false,
"", "",
}, },
@ -126,7 +137,7 @@ func (s *IntegrationTestSuite) TestQueryAuthorizationGRPC() {
s.Require().NoError(err) s.Require().NoError(err)
authorization.Authorization.UnpackInterfaces(val.ClientCtx.InterfaceRegistry) authorization.Authorization.UnpackInterfaces(val.ClientCtx.InterfaceRegistry)
auth := authorization.Authorization.GetAuthorizationGrant() auth := authorization.Authorization.GetAuthorizationGrant()
s.Require().Equal(auth.MethodName(), types.SendAuthorization{}.MethodName()) s.Require().Equal(auth.MethodName(), banktypes.SendAuthorization{}.MethodName())
} }
}) })
} }
@ -184,7 +195,16 @@ func (s *IntegrationTestSuite) TestQueryAuthorizationsGRPC() {
false, false,
"", "",
func() { func() {
_, err := authztestutil.MsgGrantAuthorizationExec(val.ClientCtx, val.Address.String(), s.grantee.String(), "/cosmos.gov.v1beta1.Msg/Vote", "") _, err := authztestutil.ExecGrantAuthorization(val, []string{
s.grantee.String(),
"generic",
fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()),
fmt.Sprintf("--%s=%s", cli.FlagMsgType, typeMsgVote),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()),
})
s.Require().NoError(err) s.Require().NoError(err)
}, },
func(authorizations *types.QueryAuthorizationsResponse) { func(authorizations *types.QueryAuthorizationsResponse) {

View File

@ -1,34 +1,14 @@
package testutil package testutil
import ( import (
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/testutil/network"
authzcli "github.com/cosmos/cosmos-sdk/x/authz/client/cli" "github.com/cosmos/cosmos-sdk/x/authz/client/cli"
) )
var commonArgs = []string{ func ExecGrantAuthorization(val *network.Validator, args []string) (testutil.BufferWriter, error) {
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), cmd := cli.NewCmdGrantAuthorization()
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), clientCtx := val.ClientCtx
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10))).String()), return clitestutil.ExecTestCLICmd(clientCtx, cmd, args)
}
func MsgGrantAuthorizationExec(clientCtx client.Context, granter, grantee, msgName, limit string, extraArgs ...string) (testutil.BufferWriter, error) {
args := []string{
grantee,
msgName,
}
if limit != "" {
args = append(args, limit)
}
args = append(args, fmt.Sprintf("--%s=%s", flags.FlagFrom, granter))
args = append(args, fmt.Sprintf("--%s=%d", authzcli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()))
args = append(args, commonArgs...)
return clitestutil.ExecTestCLICmd(clientCtx, authzcli.NewCmdGrantAuthorization(), args)
} }

View File

@ -0,0 +1,21 @@
package exported
import (
"github.com/gogo/protobuf/proto"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// Authorization represents the interface of various Authorization types.
type Authorization interface {
proto.Message
// MethodName returns the fully-qualified Msg service method name as described in ADR 031.
MethodName() string
// Accept determines whether this grant permits the provided sdk.ServiceMsg to be performed, and if
// so provides an upgraded authorization instance.
Accept(msg sdk.ServiceMsg, block tmproto.Header) (updated Authorization, delete bool, err error)
}

View File

@ -3,8 +3,6 @@ package exported
import ( import (
"time" "time"
"github.com/cosmos/cosmos-sdk/x/authz/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
) )
@ -14,7 +12,7 @@ type Keeper interface {
// Grants the provided authorization to the grantee on the granter's account with the provided expiration time // Grants the provided authorization to the grantee on the granter's account with the provided expiration time
// If there is an existing authorization grant for the same sdk.Msg type, this grant overwrites that. // If there is an existing authorization grant for the same sdk.Msg type, this grant overwrites that.
Grant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, authorization types.Authorization, expiration time.Time) error Grant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, authorization Authorization, expiration time.Time) error
// Revokes any authorization for the provided message type granted to the grantee by the granter. // Revokes any authorization for the provided message type granted to the grantee by the granter.
Revoke(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) Revoke(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string)
@ -22,5 +20,5 @@ type Keeper interface {
// Returns any Authorization (or nil), with the expiration time, // Returns any Authorization (or nil), with the expiration time,
// granted to the grantee by the granter for the provided msg type. // granted to the grantee by the granter for the provided msg type.
// If the Authorization is expired already, it will revoke the authorization and return nil // If the Authorization is expired already, it will revoke the authorization and return nil
GetOrRevokeAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) (cap types.Authorization, expiration time.Time) GetOrRevokeAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) (cap Authorization, expiration time.Time)
} }

View File

@ -2,6 +2,7 @@ package authz
import ( import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
"github.com/cosmos/cosmos-sdk/x/authz/keeper" "github.com/cosmos/cosmos-sdk/x/authz/keeper"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
) )
@ -17,7 +18,7 @@ func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, data *types.GenesisState
if err != nil { if err != nil {
panic(err) panic(err)
} }
authorization, ok := entry.Authorization.GetCachedValue().(types.Authorization) authorization, ok := entry.Authorization.GetCachedValue().(exported.Authorization)
if !ok { if !ok {
panic("expected authorization") panic("expected authorization")
} }

View File

@ -12,7 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
authz "github.com/cosmos/cosmos-sdk/x/authz" authz "github.com/cosmos/cosmos-sdk/x/authz"
"github.com/cosmos/cosmos-sdk/x/authz/keeper" "github.com/cosmos/cosmos-sdk/x/authz/keeper"
"github.com/cosmos/cosmos-sdk/x/authz/types" bank "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
type GenesisTestSuite struct { type GenesisTestSuite struct {
@ -41,7 +41,7 @@ func (suite *GenesisTestSuite) TestImportExportGenesis() {
coins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1_000))) coins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1_000)))
now := suite.ctx.BlockHeader().Time now := suite.ctx.BlockHeader().Time
grant := &types.SendAuthorization{SpendLimit: coins} grant := &bank.SendAuthorization{SpendLimit: coins}
err := suite.keeper.Grant(suite.ctx, granteeAddr, granterAddr, grant, now.Add(time.Hour)) err := suite.keeper.Grant(suite.ctx, granteeAddr, granterAddr, grant, now.Add(time.Hour))
suite.Require().NoError(err) suite.Require().NoError(err)
genesis := authz.ExportGenesis(suite.ctx, suite.keeper) genesis := authz.ExportGenesis(suite.ctx, suite.keeper)

View File

@ -6,14 +6,16 @@ import (
"time" "time"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
func (suite *TestSuite) TestGRPCQueryAuthorization() { func (suite *TestSuite) TestGRPCQueryAuthorization() {
app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs
var ( var (
req *types.QueryAuthorizationRequest req *types.QueryAuthorizationRequest
expAuthorization types.Authorization expAuthorization exported.Authorization
) )
testCases := []struct { testCases := []struct {
msg string msg string
@ -55,7 +57,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() {
func() { func() {
now := ctx.BlockHeader().Time now := ctx.BlockHeader().Time
newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100))
expAuthorization = &types.SendAuthorization{SpendLimit: newCoins} expAuthorization = &banktypes.SendAuthorization{SpendLimit: newCoins}
err := app.AuthzKeeper.Grant(ctx, addrs[0], addrs[1], expAuthorization, now.Add(time.Hour)) err := app.AuthzKeeper.Grant(ctx, addrs[0], addrs[1], expAuthorization, now.Add(time.Hour))
suite.Require().NoError(err) suite.Require().NoError(err)
req = &types.QueryAuthorizationRequest{ req = &types.QueryAuthorizationRequest{
@ -66,7 +68,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() {
}, },
true, true,
func(res *types.QueryAuthorizationResponse) { func(res *types.QueryAuthorizationResponse) {
var auth types.Authorization var auth exported.Authorization
err := suite.app.InterfaceRegistry().UnpackAny(res.Authorization.Authorization, &auth) err := suite.app.InterfaceRegistry().UnpackAny(res.Authorization.Authorization, &auth)
suite.Require().NoError(err) suite.Require().NoError(err)
suite.Require().NotNil(auth) suite.Require().NotNil(auth)
@ -92,7 +94,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorizations() {
app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs
var ( var (
req *types.QueryAuthorizationsRequest req *types.QueryAuthorizationsRequest
expAuthorization types.Authorization expAuthorization exported.Authorization
) )
testCases := []struct { testCases := []struct {
msg string msg string
@ -123,7 +125,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorizations() {
func() { func() {
now := ctx.BlockHeader().Time now := ctx.BlockHeader().Time
newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100))
expAuthorization = &types.SendAuthorization{SpendLimit: newCoins} expAuthorization = &banktypes.SendAuthorization{SpendLimit: newCoins}
err := app.AuthzKeeper.Grant(ctx, addrs[0], addrs[1], expAuthorization, now.Add(time.Hour)) err := app.AuthzKeeper.Grant(ctx, addrs[0], addrs[1], expAuthorization, now.Add(time.Hour))
suite.Require().NoError(err) suite.Require().NoError(err)
req = &types.QueryAuthorizationsRequest{ req = &types.QueryAuthorizationsRequest{
@ -133,7 +135,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorizations() {
}, },
true, true,
func(res *types.QueryAuthorizationsResponse) { func(res *types.QueryAuthorizationsResponse) {
var auth types.Authorization var auth exported.Authorization
suite.Require().Equal(1, len(res.Authorizations)) suite.Require().Equal(1, len(res.Authorizations))
err := suite.app.InterfaceRegistry().UnpackAny(res.Authorizations[0].Authorization, &auth) err := suite.app.InterfaceRegistry().UnpackAny(res.Authorizations[0].Authorization, &auth)
suite.Require().NoError(err) suite.Require().NoError(err)

View File

@ -13,6 +13,7 @@ import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
) )
@ -47,7 +48,7 @@ func (k Keeper) getAuthorizationGrant(ctx sdk.Context, grantStoreKey []byte) (gr
return grant, true return grant, true
} }
func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, updated types.Authorization) error { func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, updated exported.Authorization) error {
grantStoreKey := types.GetAuthorizationStoreKey(grantee, granter, updated.MethodName()) grantStoreKey := types.GetAuthorizationStoreKey(grantee, granter, updated.MethodName())
grant, found := k.getAuthorizationGrant(ctx, grantStoreKey) grant, found := k.getAuthorizationGrant(ctx, grantStoreKey)
if !found { if !found {
@ -86,9 +87,9 @@ func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, service
if authorization == nil { if authorization == nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "authorization not found") return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "authorization not found")
} }
allow, updated, del := authorization.Accept(serviceMsg, ctx.BlockHeader()) updated, del, err := authorization.Accept(serviceMsg, ctx.BlockHeader())
if !allow { if err != nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "requested amount is more than spend limit") return nil, err
} }
if del { if del {
k.Revoke(ctx, grantee, granter, serviceMsg.Type()) k.Revoke(ctx, grantee, granter, serviceMsg.Type())
@ -117,7 +118,7 @@ func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, service
// Grant method grants the provided authorization to the grantee on the granter's account with the provided expiration // Grant method grants the provided authorization to the grantee on the granter's account with the provided expiration
// time. If there is an existing authorization grant for the same `sdk.Msg` type, this grant // time. If there is an existing authorization grant for the same `sdk.Msg` type, this grant
// overwrites that. // overwrites that.
func (k Keeper) Grant(ctx sdk.Context, grantee, granter sdk.AccAddress, authorization types.Authorization, expiration time.Time) error { func (k Keeper) Grant(ctx sdk.Context, grantee, granter sdk.AccAddress, authorization exported.Authorization, expiration time.Time) error {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
grant, err := types.NewAuthorizationGrant(authorization, expiration) grant, err := types.NewAuthorizationGrant(authorization, expiration)
@ -164,7 +165,7 @@ func (k Keeper) Revoke(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccA
} }
// GetAuthorizations Returns list of `Authorizations` granted to the grantee by the granter. // GetAuthorizations Returns list of `Authorizations` granted to the grantee by the granter.
func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress) (authorizations []types.Authorization) { func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress) (authorizations []exported.Authorization) {
store := ctx.KVStore(k.storeKey) store := ctx.KVStore(k.storeKey)
key := types.GetAuthorizationStoreKey(grantee, granter, "") key := types.GetAuthorizationStoreKey(grantee, granter, "")
iter := sdk.KVStorePrefixIterator(store, key) iter := sdk.KVStorePrefixIterator(store, key)
@ -180,7 +181,7 @@ func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, grant
// GetOrRevokeAuthorization Returns any `Authorization` (or `nil`), with the expiration time, // GetOrRevokeAuthorization Returns any `Authorization` (or `nil`), with the expiration time,
// granted to the grantee by the granter for the provided msg type. // granted to the grantee by the granter for the provided msg type.
// If the Authorization is expired already, it will revoke the authorization and return nil // If the Authorization is expired already, it will revoke the authorization and return nil
func (k Keeper) GetOrRevokeAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) (cap types.Authorization, expiration time.Time) { func (k Keeper) GetOrRevokeAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) (cap exported.Authorization, expiration time.Time) {
grant, found := k.getAuthorizationGrant(ctx, types.GetAuthorizationStoreKey(grantee, granter, msgType)) grant, found := k.getAuthorizationGrant(ctx, types.GetAuthorizationStoreKey(grantee, granter, msgType))
if !found { if !found {
return nil, time.Time{} return nil, time.Time{}

View File

@ -53,7 +53,7 @@ func (s *TestSuite) TestKeeper() {
recipientAddr := addrs[2] recipientAddr := addrs[2]
s.T().Log("verify that no authorization returns nil") s.T().Log("verify that no authorization returns nil")
authorization, expiration := app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, expiration := app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().Nil(authorization) s.Require().Nil(authorization)
s.Require().Equal(expiration, time.Time{}) s.Require().Equal(expiration, time.Time{})
now := s.ctx.BlockHeader().Time now := s.ctx.BlockHeader().Time
@ -61,38 +61,38 @@ func (s *TestSuite) TestKeeper() {
newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100))
s.T().Log("verify if expired authorization is rejected") s.T().Log("verify if expired authorization is rejected")
x := &types.SendAuthorization{SpendLimit: newCoins} x := &banktypes.SendAuthorization{SpendLimit: newCoins}
err := app.AuthzKeeper.Grant(ctx, granterAddr, granteeAddr, x, now.Add(-1*time.Hour)) err := app.AuthzKeeper.Grant(ctx, granterAddr, granteeAddr, x, now.Add(-1*time.Hour))
s.Require().NoError(err) s.Require().NoError(err)
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().Nil(authorization) s.Require().Nil(authorization)
s.T().Log("verify if authorization is accepted") s.T().Log("verify if authorization is accepted")
x = &types.SendAuthorization{SpendLimit: newCoins} x = &banktypes.SendAuthorization{SpendLimit: newCoins}
err = app.AuthzKeeper.Grant(ctx, granteeAddr, granterAddr, x, now.Add(time.Hour)) err = app.AuthzKeeper.Grant(ctx, granteeAddr, granterAddr, x, now.Add(time.Hour))
s.Require().NoError(err) s.Require().NoError(err)
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().NotNil(authorization) s.Require().NotNil(authorization)
s.Require().Equal(authorization.MethodName(), types.SendAuthorization{}.MethodName()) s.Require().Equal(authorization.MethodName(), banktypes.SendAuthorization{}.MethodName())
s.T().Log("verify fetching authorization with wrong msg type fails") s.T().Log("verify fetching authorization with wrong msg type fails")
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgMultiSend{})) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgMultiSend{}))
s.Require().Nil(authorization) s.Require().Nil(authorization)
s.T().Log("verify fetching authorization with wrong grantee fails") s.T().Log("verify fetching authorization with wrong grantee fails")
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, recipientAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, recipientAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().Nil(authorization) s.Require().Nil(authorization)
s.T().Log("verify revoke fails with wrong information") s.T().Log("verify revoke fails with wrong information")
err = app.AuthzKeeper.Revoke(ctx, recipientAddr, granterAddr, types.SendAuthorization{}.MethodName()) err = app.AuthzKeeper.Revoke(ctx, recipientAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().Error(err) s.Require().Error(err)
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, recipientAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, recipientAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().Nil(authorization) s.Require().Nil(authorization)
s.T().Log("verify revoke executes with correct information") s.T().Log("verify revoke executes with correct information")
err = app.AuthzKeeper.Revoke(ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) err = app.AuthzKeeper.Revoke(ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().NoError(err) s.Require().NoError(err)
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().Nil(authorization) s.Require().Nil(authorization)
} }
@ -112,7 +112,7 @@ func (s *TestSuite) TestKeeperIter() {
newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100))
s.T().Log("verify if expired authorization is rejected") s.T().Log("verify if expired authorization is rejected")
x := &types.SendAuthorization{SpendLimit: newCoins} x := &banktypes.SendAuthorization{SpendLimit: newCoins}
err := app.AuthzKeeper.Grant(ctx, granteeAddr, granterAddr, x, now.Add(-1*time.Hour)) err := app.AuthzKeeper.Grant(ctx, granteeAddr, granterAddr, x, now.Add(-1*time.Hour))
s.Require().NoError(err) s.Require().NoError(err)
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, "abcd") authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, "abcd")
@ -141,7 +141,7 @@ func (s *TestSuite) TestKeeperFees() {
msgs := types.NewMsgExecAuthorized(granteeAddr, []sdk.ServiceMsg{ msgs := types.NewMsgExecAuthorized(granteeAddr, []sdk.ServiceMsg{
{ {
MethodName: types.SendAuthorization{}.MethodName(), MethodName: banktypes.SendAuthorization{}.MethodName(),
Request: &banktypes.MsgSend{ Request: &banktypes.MsgSend{
Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)), Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)),
FromAddress: granterAddr.String(), FromAddress: granterAddr.String(),
@ -162,12 +162,12 @@ func (s *TestSuite) TestKeeperFees() {
s.T().Log("verify dispatch executes with correct information") s.T().Log("verify dispatch executes with correct information")
// grant authorization // grant authorization
err = app.AuthzKeeper.Grant(s.ctx, granteeAddr, granterAddr, &types.SendAuthorization{SpendLimit: smallCoin}, now) err = app.AuthzKeeper.Grant(s.ctx, granteeAddr, granterAddr, &banktypes.SendAuthorization{SpendLimit: smallCoin}, now)
s.Require().NoError(err) s.Require().NoError(err)
authorization, _ := app.AuthzKeeper.GetOrRevokeAuthorization(s.ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ := app.AuthzKeeper.GetOrRevokeAuthorization(s.ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().NotNil(authorization) s.Require().NotNil(authorization)
s.Require().Equal(authorization.MethodName(), types.SendAuthorization{}.MethodName()) s.Require().Equal(authorization.MethodName(), banktypes.SendAuthorization{}.MethodName())
executeMsgs, err = msgs.GetServiceMsgs() executeMsgs, err = msgs.GetServiceMsgs()
s.Require().NoError(err) s.Require().NoError(err)
@ -176,7 +176,7 @@ func (s *TestSuite) TestKeeperFees() {
s.Require().NoError(err) s.Require().NoError(err)
s.Require().NotNil(result) s.Require().NotNil(result)
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(s.ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(s.ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().NotNil(authorization) s.Require().NotNil(authorization)
s.T().Log("verify dispatch fails with overlimit") s.T().Log("verify dispatch fails with overlimit")
@ -184,7 +184,7 @@ func (s *TestSuite) TestKeeperFees() {
msgs = types.NewMsgExecAuthorized(granteeAddr, []sdk.ServiceMsg{ msgs = types.NewMsgExecAuthorized(granteeAddr, []sdk.ServiceMsg{
{ {
MethodName: types.SendAuthorization{}.MethodName(), MethodName: banktypes.SendAuthorization{}.MethodName(),
Request: &banktypes.MsgSend{ Request: &banktypes.MsgSend{
Amount: someCoin, Amount: someCoin,
FromAddress: granterAddr.String(), FromAddress: granterAddr.String(),
@ -201,7 +201,7 @@ func (s *TestSuite) TestKeeperFees() {
s.Require().Nil(result) s.Require().Nil(result)
s.Require().NotNil(err) s.Require().NotNil(err)
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(s.ctx, granteeAddr, granterAddr, types.SendAuthorization{}.MethodName()) authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(s.ctx, granteeAddr, granterAddr, banktypes.SendAuthorization{}.MethodName())
s.Require().NotNil(authorization) s.Require().NotNil(authorization)
} }

View File

@ -12,13 +12,14 @@ import (
"github.com/cosmos/cosmos-sdk/types/kv" "github.com/cosmos/cosmos-sdk/types/kv"
"github.com/cosmos/cosmos-sdk/x/authz/simulation" "github.com/cosmos/cosmos-sdk/x/authz/simulation"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
func TestDecodeStore(t *testing.T) { func TestDecodeStore(t *testing.T) {
cdc := simapp.MakeTestEncodingConfig().Marshaler cdc := simapp.MakeTestEncodingConfig().Marshaler
dec := simulation.NewDecodeStore(cdc) dec := simulation.NewDecodeStore(cdc)
grant, _ := types.NewAuthorizationGrant(types.NewSendAuthorization(sdk.NewCoins(sdk.NewInt64Coin("foo", 123))), time.Now().UTC()) grant, _ := types.NewAuthorizationGrant(banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewInt64Coin("foo", 123))), time.Now().UTC())
grantBz, err := cdc.MarshalBinaryBare(&grant) grantBz, err := cdc.MarshalBinaryBare(&grant)
require.NoError(t, err) require.NoError(t, err)
kvPairs := kv.Pairs{ kvPairs := kv.Pairs{

View File

@ -97,7 +97,7 @@ func SimulateMsgGrantAuthorization(ak types.AccountKeeper, bk types.BankKeeper,
blockTime := ctx.BlockTime() blockTime := ctx.BlockTime()
msg, err := types.NewMsgGrantAuthorization(granter.Address, grantee.Address, msg, err := types.NewMsgGrantAuthorization(granter.Address, grantee.Address,
types.NewSendAuthorization(spendableCoins.Sub(fees)), blockTime.AddDate(1, 0, 0)) banktype.NewSendAuthorization(spendableCoins.Sub(fees)), blockTime.AddDate(1, 0, 0))
if err != nil { if err != nil {
return simtypes.NoOpMsg(types.ModuleName, TypeMsgGrantAuthorization, err.Error()), nil, err return simtypes.NoOpMsg(types.ModuleName, TypeMsgGrantAuthorization, err.Error()), nil, err
@ -239,7 +239,7 @@ func SimulateMsgExecuteAuthorized(ak types.AccountKeeper, bk types.BankKeeper, k
sendCoins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(10))) sendCoins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(10)))
execMsg := sdk.ServiceMsg{ execMsg := sdk.ServiceMsg{
MethodName: types.SendAuthorization{}.MethodName(), MethodName: banktype.SendAuthorization{}.MethodName(),
Request: banktype.NewMsgSend( Request: banktype.NewMsgSend(
granterAddr, granterAddr,
granteeAddr, granteeAddr,
@ -248,10 +248,10 @@ func SimulateMsgExecuteAuthorized(ak types.AccountKeeper, bk types.BankKeeper, k
} }
msg := types.NewMsgExecAuthorized(grantee.Address, []sdk.ServiceMsg{execMsg}) msg := types.NewMsgExecAuthorized(grantee.Address, []sdk.ServiceMsg{execMsg})
sendGrant := targetGrant.Authorization.GetCachedValue().(*types.SendAuthorization) sendGrant := targetGrant.Authorization.GetCachedValue().(*banktype.SendAuthorization)
allow, _, _ := sendGrant.Accept(execMsg, ctx.BlockHeader()) _, _, err = sendGrant.Accept(execMsg, ctx.BlockHeader())
if !allow { if err != nil {
return simtypes.NoOpMsg(types.ModuleName, TypeMsgExecDelegated, "not allowed"), nil, nil return simtypes.NoOpMsg(types.ModuleName, TypeMsgExecDelegated, err.Error()), nil, nil
} }
txGen := simappparams.MakeTestEncodingConfig().TxConfig txGen := simappparams.MakeTestEncodingConfig().TxConfig

View File

@ -17,6 +17,7 @@ import (
simtypes "github.com/cosmos/cosmos-sdk/types/simulation" simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/authz/simulation" "github.com/cosmos/cosmos-sdk/x/authz/simulation"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
type SimTestSuite struct { type SimTestSuite struct {
@ -136,7 +137,7 @@ func (suite *SimTestSuite) TestSimulateRevokeAuthorization() {
granter := accounts[0] granter := accounts[0]
grantee := accounts[1] grantee := accounts[1]
authorization := types.NewSendAuthorization(initCoins) authorization := banktypes.NewSendAuthorization(initCoins)
err := suite.app.AuthzKeeper.Grant(suite.ctx, grantee.Address, granter.Address, authorization, time.Now().Add(30*time.Hour)) err := suite.app.AuthzKeeper.Grant(suite.ctx, grantee.Address, granter.Address, authorization, time.Now().Add(30*time.Hour))
suite.Require().NoError(err) suite.Require().NoError(err)
@ -152,7 +153,7 @@ func (suite *SimTestSuite) TestSimulateRevokeAuthorization() {
suite.Require().True(operationMsg.OK) suite.Require().True(operationMsg.OK)
suite.Require().Equal(granter.Address.String(), msg.Granter) suite.Require().Equal(granter.Address.String(), msg.Granter)
suite.Require().Equal(grantee.Address.String(), msg.Grantee) suite.Require().Equal(grantee.Address.String(), msg.Grantee)
suite.Require().Equal(types.SendAuthorization{}.MethodName(), msg.MethodName) suite.Require().Equal(banktypes.SendAuthorization{}.MethodName(), msg.MethodName)
suite.Require().Len(futureOperations, 0) suite.Require().Len(futureOperations, 0)
} }
@ -171,7 +172,7 @@ func (suite *SimTestSuite) TestSimulateExecAuthorization() {
granter := accounts[0] granter := accounts[0]
grantee := accounts[1] grantee := accounts[1]
authorization := types.NewSendAuthorization(initCoins) authorization := banktypes.NewSendAuthorization(initCoins)
err := suite.app.AuthzKeeper.Grant(suite.ctx, grantee.Address, granter.Address, authorization, time.Now().Add(30*time.Hour)) err := suite.app.AuthzKeeper.Grant(suite.ctx, grantee.Address, granter.Address, authorization, time.Now().Add(30*time.Hour))
suite.Require().NoError(err) suite.Require().NoError(err)

View File

@ -3,28 +3,14 @@ package types
import ( import (
"time" "time"
"github.com/gogo/protobuf/proto"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
proto "github.com/gogo/protobuf/proto"
) )
type Authorization interface {
proto.Message
// MethodName returns the fully-qualified Msg service method name as described in ADR 031.
MethodName() string
// Accept determines whether this grant permits the provided sdk.ServiceMsg to be performed, and if
// so provides an upgraded authorization instance.
Accept(msg sdk.ServiceMsg, block tmproto.Header) (allow bool, updated Authorization, delete bool)
}
// NewAuthorizationGrant returns new AuthrizationGrant // NewAuthorizationGrant returns new AuthrizationGrant
func NewAuthorizationGrant(authorization Authorization, expiration time.Time) (AuthorizationGrant, error) { func NewAuthorizationGrant(authorization exported.Authorization, expiration time.Time) (AuthorizationGrant, error) {
auth := AuthorizationGrant{ auth := AuthorizationGrant{
Expiration: expiration, Expiration: expiration,
} }
@ -49,13 +35,13 @@ var (
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (auth AuthorizationGrant) UnpackInterfaces(unpacker types.AnyUnpacker) error { func (auth AuthorizationGrant) UnpackInterfaces(unpacker types.AnyUnpacker) error {
var authorization Authorization var authorization exported.Authorization
return unpacker.UnpackAny(auth.Authorization, &authorization) return unpacker.UnpackAny(auth.Authorization, &authorization)
} }
// GetAuthorizationGrant returns the cached value from the AuthorizationGrant.Authorization if present. // GetAuthorizationGrant returns the cached value from the AuthorizationGrant.Authorization if present.
func (auth AuthorizationGrant) GetAuthorizationGrant() Authorization { func (auth AuthorizationGrant) GetAuthorizationGrant() exported.Authorization {
authorization, ok := auth.Authorization.GetCachedValue().(Authorization) authorization, ok := auth.Authorization.GetCachedValue().(exported.Authorization)
if !ok { if !ok {
return nil return nil
} }

View File

@ -5,9 +5,7 @@ package types
import ( import (
fmt "fmt" fmt "fmt"
types1 "github.com/cosmos/cosmos-sdk/codec/types" types "github.com/cosmos/cosmos-sdk/codec/types"
github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types"
types "github.com/cosmos/cosmos-sdk/types"
_ "github.com/gogo/protobuf/gogoproto" _ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto" proto "github.com/gogo/protobuf/proto"
github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
@ -31,52 +29,6 @@ var _ = time.Kitchen
// proto package needs to be updated. // proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// SendAuthorization allows the grantee to spend up to spend_limit coins from
// the granter's account.
type SendAuthorization struct {
SpendLimit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=spend_limit,json=spendLimit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"spend_limit"`
}
func (m *SendAuthorization) Reset() { *m = SendAuthorization{} }
func (m *SendAuthorization) String() string { return proto.CompactTextString(m) }
func (*SendAuthorization) ProtoMessage() {}
func (*SendAuthorization) Descriptor() ([]byte, []int) {
return fileDescriptor_544dc2e84b61c637, []int{0}
}
func (m *SendAuthorization) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SendAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SendAuthorization.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SendAuthorization) XXX_Merge(src proto.Message) {
xxx_messageInfo_SendAuthorization.Merge(m, src)
}
func (m *SendAuthorization) XXX_Size() int {
return m.Size()
}
func (m *SendAuthorization) XXX_DiscardUnknown() {
xxx_messageInfo_SendAuthorization.DiscardUnknown(m)
}
var xxx_messageInfo_SendAuthorization proto.InternalMessageInfo
func (m *SendAuthorization) GetSpendLimit() github_com_cosmos_cosmos_sdk_types.Coins {
if m != nil {
return m.SpendLimit
}
return nil
}
// GenericAuthorization gives the grantee unrestricted permissions to execute // GenericAuthorization gives the grantee unrestricted permissions to execute
// the provided method on behalf of the granter's account. // the provided method on behalf of the granter's account.
type GenericAuthorization struct { type GenericAuthorization struct {
@ -90,7 +42,7 @@ func (m *GenericAuthorization) Reset() { *m = GenericAuthorization{} }
func (m *GenericAuthorization) String() string { return proto.CompactTextString(m) } func (m *GenericAuthorization) String() string { return proto.CompactTextString(m) }
func (*GenericAuthorization) ProtoMessage() {} func (*GenericAuthorization) ProtoMessage() {}
func (*GenericAuthorization) Descriptor() ([]byte, []int) { func (*GenericAuthorization) Descriptor() ([]byte, []int) {
return fileDescriptor_544dc2e84b61c637, []int{1} return fileDescriptor_544dc2e84b61c637, []int{0}
} }
func (m *GenericAuthorization) XXX_Unmarshal(b []byte) error { func (m *GenericAuthorization) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b) return m.Unmarshal(b)
@ -129,15 +81,15 @@ func (m *GenericAuthorization) GetMessageName() string {
// AuthorizationGrant gives permissions to execute // AuthorizationGrant gives permissions to execute
// the provide method with expiration time. // the provide method with expiration time.
type AuthorizationGrant struct { type AuthorizationGrant struct {
Authorization *types1.Any `protobuf:"bytes,1,opt,name=authorization,proto3" json:"authorization,omitempty"` Authorization *types.Any `protobuf:"bytes,1,opt,name=authorization,proto3" json:"authorization,omitempty"`
Expiration time.Time `protobuf:"bytes,2,opt,name=expiration,proto3,stdtime" json:"expiration"` Expiration time.Time `protobuf:"bytes,2,opt,name=expiration,proto3,stdtime" json:"expiration"`
} }
func (m *AuthorizationGrant) Reset() { *m = AuthorizationGrant{} } func (m *AuthorizationGrant) Reset() { *m = AuthorizationGrant{} }
func (m *AuthorizationGrant) String() string { return proto.CompactTextString(m) } func (m *AuthorizationGrant) String() string { return proto.CompactTextString(m) }
func (*AuthorizationGrant) ProtoMessage() {} func (*AuthorizationGrant) ProtoMessage() {}
func (*AuthorizationGrant) Descriptor() ([]byte, []int) { func (*AuthorizationGrant) Descriptor() ([]byte, []int) {
return fileDescriptor_544dc2e84b61c637, []int{2} return fileDescriptor_544dc2e84b61c637, []int{1}
} }
func (m *AuthorizationGrant) XXX_Unmarshal(b []byte) error { func (m *AuthorizationGrant) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b) return m.Unmarshal(b)
@ -166,7 +118,7 @@ func (m *AuthorizationGrant) XXX_DiscardUnknown() {
var xxx_messageInfo_AuthorizationGrant proto.InternalMessageInfo var xxx_messageInfo_AuthorizationGrant proto.InternalMessageInfo
func (m *AuthorizationGrant) GetAuthorization() *types1.Any { func (m *AuthorizationGrant) GetAuthorization() *types.Any {
if m != nil { if m != nil {
return m.Authorization return m.Authorization
} }
@ -181,7 +133,6 @@ func (m *AuthorizationGrant) GetExpiration() time.Time {
} }
func init() { func init() {
proto.RegisterType((*SendAuthorization)(nil), "cosmos.authz.v1beta1.SendAuthorization")
proto.RegisterType((*GenericAuthorization)(nil), "cosmos.authz.v1beta1.GenericAuthorization") proto.RegisterType((*GenericAuthorization)(nil), "cosmos.authz.v1beta1.GenericAuthorization")
proto.RegisterType((*AuthorizationGrant)(nil), "cosmos.authz.v1beta1.AuthorizationGrant") proto.RegisterType((*AuthorizationGrant)(nil), "cosmos.authz.v1beta1.AuthorizationGrant")
} }
@ -189,70 +140,28 @@ func init() {
func init() { proto.RegisterFile("cosmos/authz/v1beta1/authz.proto", fileDescriptor_544dc2e84b61c637) } func init() { proto.RegisterFile("cosmos/authz/v1beta1/authz.proto", fileDescriptor_544dc2e84b61c637) }
var fileDescriptor_544dc2e84b61c637 = []byte{ var fileDescriptor_544dc2e84b61c637 = []byte{
// 410 bytes of a gzipped FileDescriptorProto // 333 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xbf, 0x8e, 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, 0x93, 0xc5, 0xc6, 0x36, 0x56, 0x1b, 0xdb,
0x05, 0x79, 0x8d, 0x19, 0x49, 0xa0, 0xd9, 0xe9, 0xce, 0xff, 0x82, 0x7f, 0x01, 0xd0, 0x1b, 0x74, 0xf8, 0xda, 0xd8, 0xc6, 0xc3, 0x65, 0x18, 0xcb, 0x28, 0x0f, 0xdc, 0x31, 0x72, 0xbd, 0x0d, 0x7d,
0x6e, 0x6a, 0xcc, 0x95, 0x77, 0x0b, 0x8f, 0xf0, 0x7e, 0x57, 0xd3, 0xdd, 0x4b, 0x1f, 0x99, 0xf4, 0xb4, 0xc5, 0xe4, 0xd9, 0x9b, 0xea, 0xfd, 0xca, 0x59, 0x0a, 0x22, 0xf8, 0x5f, 0xbe, 0x77, 0xf3,
0x50, 0x9f, 0x1e, 0xba, 0xe2, 0x8b, 0x78, 0xf4, 0xfd, 0x10, 0x9b, 0x0c, 0xd5, 0xde, 0x35, 0x84, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x62, 0x49, 0x9d, 0xc0, 0xfc, 0x01, 0x00, 0x00,
0xe4, 0xae, 0xa2, 0xb5, 0x61, 0x3d, 0xd0, 0xac, 0xf1, 0x5f, 0xac, 0xb7, 0xfd, 0x0f, 0x8c, 0x1f,
0x77, 0x19, 0x2e, 0xb7, 0x21, 0x48, 0xf6, 0x74, 0xf1, 0xf5, 0xaa, 0x0d, 0xc0, 0xba, 0x0d, 0xc0,
0xaf, 0x36, 0x00, 0xcb, 0x5d, 0xe0, 0xac, 0x77, 0x81, 0xf3, 0x73, 0x17, 0x38, 0xef, 0x9e, 0xfd,
0x37, 0xeb, 0x3b, 0x7b, 0x2d, 0x75, 0xe6, 0xe9, 0x23, 0xfd, 0xbe, 0xe7, 0xbf, 0x03, 0x00, 0x00,
0xff, 0xff, 0x87, 0x61, 0xb9, 0xa8, 0xb3, 0x02, 0x00, 0x00,
}
func (m *SendAuthorization) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SendAuthorization) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SendAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.SpendLimit) > 0 {
for iNdEx := len(m.SpendLimit) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.SpendLimit[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAuthz(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
} }
func (m *GenericAuthorization) Marshal() (dAtA []byte, err error) { func (m *GenericAuthorization) Marshal() (dAtA []byte, err error) {
@ -339,21 +248,6 @@ func encodeVarintAuthz(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v) dAtA[offset] = uint8(v)
return base return base
} }
func (m *SendAuthorization) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.SpendLimit) > 0 {
for _, e := range m.SpendLimit {
l = e.Size()
n += 1 + l + sovAuthz(uint64(l))
}
}
return n
}
func (m *GenericAuthorization) Size() (n int) { func (m *GenericAuthorization) Size() (n int) {
if m == nil { if m == nil {
return 0 return 0
@ -388,90 +282,6 @@ func sovAuthz(x uint64) (n int) {
func sozAuthz(x uint64) (n int) { func sozAuthz(x uint64) (n int) {
return sovAuthz(uint64((x << 1) ^ uint64((int64(x) >> 63)))) return sovAuthz(uint64((x << 1) ^ uint64((int64(x) >> 63))))
} }
func (m *SendAuthorization) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SendAuthorization: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SendAuthorization: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SpendLimit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAuthz
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAuthz
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.SpendLimit = append(m.SpendLimit, types.Coin{})
if err := m.SpendLimit[len(m.SpendLimit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAuthz(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAuthz
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GenericAuthorization) Unmarshal(dAtA []byte) error { func (m *GenericAuthorization) Unmarshal(dAtA []byte) error {
l := len(dAtA) l := len(dAtA)
iNdEx := 0 iNdEx := 0
@ -613,7 +423,7 @@ func (m *AuthorizationGrant) Unmarshal(dAtA []byte) error {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
if m.Authorization == nil { if m.Authorization == nil {
m.Authorization = &types1.Any{} m.Authorization = &types.Any{}
} }
if err := m.Authorization.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { if err := m.Authorization.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err return err

View File

@ -4,6 +4,9 @@ import (
types "github.com/cosmos/cosmos-sdk/codec/types" types "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/msgservice" "github.com/cosmos/cosmos-sdk/types/msgservice"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
staking "github.com/cosmos/cosmos-sdk/x/staking/types"
) )
// RegisterInterfaces registers the interfaces types with the interface registry // RegisterInterfaces registers the interfaces types with the interface registry
@ -16,9 +19,10 @@ func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterInterface( registry.RegisterInterface(
"cosmos.authz.v1beta1.Authorization", "cosmos.authz.v1beta1.Authorization",
(*Authorization)(nil), (*exported.Authorization)(nil),
&SendAuthorization{}, &bank.SendAuthorization{},
&GenericAuthorization{}, &GenericAuthorization{},
&staking.StakeAuthorization{},
) )
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)

View File

@ -4,10 +4,11 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
) )
var ( var (
_ Authorization = &GenericAuthorization{} _ exported.Authorization = &GenericAuthorization{}
) )
// NewGenericAuthorization creates a new GenericAuthorization object. // NewGenericAuthorization creates a new GenericAuthorization object.
@ -23,6 +24,6 @@ func (cap GenericAuthorization) MethodName() string {
} }
// Accept implements Authorization.Accept. // Accept implements Authorization.Accept.
func (cap GenericAuthorization) Accept(msg sdk.ServiceMsg, block tmproto.Header) (allow bool, updated Authorization, delete bool) { func (cap GenericAuthorization) Accept(msg sdk.ServiceMsg, block tmproto.Header) (updated exported.Authorization, delete bool, err error) {
return true, &cap, false return &cap, false, nil
} }

View File

@ -2,6 +2,7 @@ package types
import ( import (
"github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
) )
// NewGenesisState creates new GenesisState object // NewGenesisState creates new GenesisState object
@ -36,6 +37,6 @@ func (data GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error {
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (msg GrantAuthorization) UnpackInterfaces(unpacker types.AnyUnpacker) error { func (msg GrantAuthorization) UnpackInterfaces(unpacker types.AnyUnpacker) error {
var authorization Authorization var authorization exported.Authorization
return unpacker.UnpackAny(msg.Authorization, &authorization) return unpacker.UnpackAny(msg.Authorization, &authorization)
} }

View File

@ -153,29 +153,29 @@ func init() {
} }
var fileDescriptor_4c2fbb971da7c892 = []byte{ var fileDescriptor_4c2fbb971da7c892 = []byte{
// 346 bytes of a gzipped FileDescriptorProto // 340 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x91, 0xbb, 0x6e, 0xc2, 0x30, 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x52, 0xbb, 0x6e, 0xc2, 0x30,
0x14, 0x86, 0xe3, 0x82, 0x7a, 0x31, 0x65, 0x68, 0xc4, 0x90, 0x22, 0x35, 0x20, 0xa6, 0xa8, 0x12, 0x14, 0x8d, 0x0b, 0xea, 0xc3, 0x94, 0xa1, 0x11, 0x43, 0xca, 0x10, 0x10, 0x53, 0x54, 0x09, 0x5b,
0xb6, 0xa0, 0x4f, 0x40, 0x84, 0xc4, 0xd4, 0x85, 0x32, 0x75, 0xa9,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x16, 0x6f, 0x3e, 0x6d, 0x31, 0x79, 0xc6, 0x73, 0xf3, 0x3c, 0xe4, 0x22,
0x5e, 0xe8, 0x34, 0x5b, 0x0b, 0xcc, 0x22, 0xae, 0xbc, 0xd3, 0xd4, 0xef, 0xee, 0x2f, 0x00, 0x00, 0xa1, 0x22, 0x38, 0x55, 0x7e, 0xb7, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x94, 0xbe, 0x5b, 0xfa,
0xff, 0xff, 0x52, 0x9c, 0x43, 0x7a, 0x5a, 0x02, 0x00, 0x00, 0x3b, 0x02, 0x00, 0x00,
} }
func (m *GenesisState) Marshal() (dAtA []byte, err error) { func (m *GenesisState) Marshal() (dAtA []byte, err error) {

View File

@ -7,11 +7,12 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
) )
var granter = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) var granter = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address())
var grantee = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) var grantee = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address())
var msgType = SendAuthorization{}.MethodName() var msgType = bank.SendAuthorization{}.MethodName()
func TestGrantkey(t *testing.T) { func TestGrantkey(t *testing.T) {
granter1, grantee1 := ExtractAddressesFromGrantKey(GetAuthorizationStoreKey(grantee, granter, msgType)) granter1, grantee1 := ExtractAddressesFromGrantKey(GetAuthorizationStoreKey(grantee, granter, msgType))

View File

@ -8,6 +8,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
) )
var ( var (
@ -21,7 +22,7 @@ var (
// NewMsgGrantAuthorization creates a new MsgGrantAuthorization // NewMsgGrantAuthorization creates a new MsgGrantAuthorization
//nolint:interfacer //nolint:interfacer
func NewMsgGrantAuthorization(granter sdk.AccAddress, grantee sdk.AccAddress, authorization Authorization, expiration time.Time) (*MsgGrantAuthorizationRequest, error) { func NewMsgGrantAuthorization(granter sdk.AccAddress, grantee sdk.AccAddress, authorization exported.Authorization, expiration time.Time) (*MsgGrantAuthorizationRequest, error) {
m := &MsgGrantAuthorizationRequest{ m := &MsgGrantAuthorizationRequest{
Granter: granter.String(), Granter: granter.String(),
Grantee: grantee.String(), Grantee: grantee.String(),
@ -66,8 +67,8 @@ func (msg MsgGrantAuthorizationRequest) ValidateBasic() error {
} }
// GetGrantAuthorization returns the cache value from the MsgGrantAuthorization.Authorization if present. // GetGrantAuthorization returns the cache value from the MsgGrantAuthorization.Authorization if present.
func (msg *MsgGrantAuthorizationRequest) GetGrantAuthorization() Authorization { func (msg *MsgGrantAuthorizationRequest) GetGrantAuthorization() exported.Authorization {
authorization, ok := msg.Authorization.GetCachedValue().(Authorization) authorization, ok := msg.Authorization.GetCachedValue().(exported.Authorization)
if !ok { if !ok {
return nil return nil
} }
@ -75,7 +76,7 @@ func (msg *MsgGrantAuthorizationRequest) GetGrantAuthorization() Authorization {
} }
// SetAuthorization converts Authorization to any and adds it to MsgGrantAuthorization.Authorization. // SetAuthorization converts Authorization to any and adds it to MsgGrantAuthorization.Authorization.
func (msg *MsgGrantAuthorizationRequest) SetAuthorization(authorization Authorization) error { func (msg *MsgGrantAuthorizationRequest) SetAuthorization(authorization exported.Authorization) error {
m, ok := authorization.(proto.Message) m, ok := authorization.(proto.Message)
if !ok { if !ok {
return sdkerrors.Wrapf(sdkerrors.ErrPackAny, "can't proto marshal %T", m) return sdkerrors.Wrapf(sdkerrors.ErrPackAny, "can't proto marshal %T", m)
@ -103,7 +104,7 @@ func (msg MsgExecAuthorizedRequest) UnpackInterfaces(unpacker types.AnyUnpacker)
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (msg MsgGrantAuthorizationRequest) UnpackInterfaces(unpacker types.AnyUnpacker) error { func (msg MsgGrantAuthorizationRequest) UnpackInterfaces(unpacker types.AnyUnpacker) error {
var authorization Authorization var authorization exported.Authorization
return unpacker.UnpackAny(msg.Authorization, &authorization) return unpacker.UnpackAny(msg.Authorization, &authorization)
} }

View File

@ -9,6 +9,7 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
"github.com/cosmos/cosmos-sdk/x/authz/types" "github.com/cosmos/cosmos-sdk/x/authz/types"
) )
@ -29,7 +30,7 @@ func TestMsgExecAuthorized(t *testing.T) {
{"zero-messages test: should fail", grantee, []sdk.ServiceMsg{}, false}, {"zero-messages test: should fail", grantee, []sdk.ServiceMsg{}, false},
{"valid test: msg type", grantee, []sdk.ServiceMsg{ {"valid test: msg type", grantee, []sdk.ServiceMsg{
{ {
MethodName: types.SendAuthorization{}.MethodName(), MethodName: banktypes.SendAuthorization{}.MethodName(),
Request: &banktypes.MsgSend{ Request: &banktypes.MsgSend{
Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)), Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)),
FromAddress: granter.String(), FromAddress: granter.String(),
@ -73,17 +74,17 @@ func TestMsgGrantAuthorization(t *testing.T) {
tests := []struct { tests := []struct {
title string title string
granter, grantee sdk.AccAddress granter, grantee sdk.AccAddress
authorization types.Authorization authorization exported.Authorization
expiration time.Time expiration time.Time
expectErr bool expectErr bool
expectPass bool expectPass bool
}{ }{
{"nil granter address", nil, grantee, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, {"nil granter address", nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
{"nil grantee address", granter, nil, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, {"nil grantee address", granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
{"nil granter and grantee address", nil, nil, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, {"nil granter and grantee address", nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
{"nil authorization", granter, grantee, nil, time.Now(), true, false}, {"nil authorization", granter, grantee, nil, time.Now(), true, false},
{"valid test case", granter, grantee, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true}, {"valid test case", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true},
{"past time", granter, grantee, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false}, {"past time", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false},
} }
for i, tc := range tests { for i, tc := range tests {
msg, err := types.NewMsgGrantAuthorization( msg, err := types.NewMsgGrantAuthorization(

View File

@ -6,12 +6,9 @@ package types
import ( import (
context "context" context "context"
fmt "fmt" fmt "fmt"
_ "github.com/cosmos/cosmos-sdk/codec/types"
query "github.com/cosmos/cosmos-sdk/types/query" query "github.com/cosmos/cosmos-sdk/types/query"
_ "github.com/gogo/protobuf/gogoproto"
grpc1 "github.com/gogo/protobuf/grpc" grpc1 "github.com/gogo/protobuf/grpc"
proto "github.com/gogo/protobuf/proto" proto "github.com/gogo/protobuf/proto"
_ "github.com/regen-network/cosmos-proto"
_ "google.golang.org/genproto/googleapis/api/annotations" _ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
@ -266,38 +263,36 @@ func init() {
func init() { proto.RegisterFile("cosmos/authz/v1beta1/query.proto", fileDescriptor_376d714ffdeb1545) } func init() { proto.RegisterFile("cosmos/authz/v1beta1/query.proto", fileDescriptor_376d714ffdeb1545) }
var fileDescriptor_376d714ffdeb1545 = []byte{ var fileDescriptor_376d714ffdeb1545 = []byte{
// 489 bytes of a gzipped FileDescriptorProto // 461 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0xbf, 0x6f, 0xd4, 0x30, 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0x31, 0x8f, 0xd3, 0x30,
0x14, 0xc7, 0xcf, 0x77, 0x02, 0x84, 0x4f, 0xed, 0x60, 0x75, 0x48, 0x03, 0x0a, 0xa7, 0x0c, 0x50, 0x14, 0xc7, 0xeb, 0x56, 0x80, 0x70, 0x75, 0x37, 0x58, 0x0c, 0x21, 0xa0, 0x50, 0x65, 0x80, 0xd3,
0x55, 0x22, 0xe6, 0x8e, 0xbf, 0xa0, 0xa5, 0xa2, 0x82, 0xa1, 0x2a, 0x19, 0x59, 0x2a, 0xa7, 0x7d, 0x49, 0xc4, 0xb4, 0x7c, 0x82, 0x3b, 0x4e, 0x9c, 0x60, 0x38, 0x1d, 0x19, 0x59, 0x90, 0xd3, 0x3e,
0x38, 0x11, 0x8d, 0x9d, 0xc6, 0x0e, 0xa2, 0x45, 0x2c, 0xac, 0x2c, 0x48, 0x2c, 0xfc, 0x29, 0x2c, 0x25, 0x11, 0x4d, 0x9c, 0xc6, 0x0e, 0xa2, 0x45, 0x2c, 0xac, 0x2c, 0x48, 0x2c, 0x7c, 0x14, 0x16,
0x0c, 0x6c, 0x8c, 0x95, 0x58, 0x18, 0xd1, 0x1d, 0x7f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74, 0x11, 0x0c, 0x7e, 0x2d, 0x82, 0xc1, 0xcb, 0x75, 0x14, 0xa3, 0xd7, 0xf4, 0xad, 0x31, 0x95, 0xd3, 0x0c, 0x44, 0x70, 0x5d, 0xfd, 0x10, 0x1e, 0xff,
0x9e, 0xe9, 0xb4, 0x4a, 0xa2, 0x7d, 0x99, 0x37, 0x3a, 0xf6, 0xf3, 0x50, 0x1d, 0xbc, 0xa6, 0x6f, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x91, 0xf5, 0x18, 0x65, 0xb6, 0x04, 0x00, 0x00,
0x9d, 0xa8, 0x3e, 0x2e, 0x40, 0x25, 0x37, 0xcd, 0x0f, 0xe1, 0xf1, 0xdf, 0x00, 0x00, 0x00, 0xff,
0xff, 0x92, 0xc3, 0xa0, 0xea, 0x02, 0x05, 0x00, 0x00,
} }
// Reference imports to suppress errors if they are not otherwise used. // Reference imports to suppress errors if they are not otherwise used.

338
x/bank/types/authz.pb.go Normal file
View File

@ -0,0 +1,338 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/bank/v1beta1/authz.proto
package types
import (
fmt "fmt"
github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types"
types "github.com/cosmos/cosmos-sdk/types"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
_ "github.com/regen-network/cosmos-proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// SendAuthorization allows the grantee to spend up to spend_limit coins from
// the granter's account.
type SendAuthorization struct {
SpendLimit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=spend_limit,json=spendLimit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"spend_limit"`
}
func (m *SendAuthorization) Reset() { *m = SendAuthorization{} }
func (m *SendAuthorization) String() string { return proto.CompactTextString(m) }
func (*SendAuthorization) ProtoMessage() {}
func (*SendAuthorization) Descriptor() ([]byte, []int) {
return fileDescriptor_a4d2a37888ea779f, []int{0}
}
func (m *SendAuthorization) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SendAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SendAuthorization.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SendAuthorization) XXX_Merge(src proto.Message) {
xxx_messageInfo_SendAuthorization.Merge(m, src)
}
func (m *SendAuthorization) XXX_Size() int {
return m.Size()
}
func (m *SendAuthorization) XXX_DiscardUnknown() {
xxx_messageInfo_SendAuthorization.DiscardUnknown(m)
}
var xxx_messageInfo_SendAuthorization proto.InternalMessageInfo
func (m *SendAuthorization) GetSpendLimit() github_com_cosmos_cosmos_sdk_types.Coins {
if m != nil {
return m.SpendLimit
}
return nil
}
func init() {
proto.RegisterType((*SendAuthorization)(nil), "cosmos.bank.v1beta1.SendAuthorization")
}
func init() { proto.RegisterFile("cosmos/bank/v1beta1/authz.proto", fileDescriptor_a4d2a37888ea779f) }
var fileDescriptor_a4d2a37888ea779f = []byte{
// 257 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xce, 0x2f, 0xce,
0xcd, 0x2f, 0xd6, 0x4f, 0x4a, 0xcc, 0xcb, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4,
0x4f, 0x2c, 0x2d, 0xc9, 0xa8, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 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xe2, 0xb5, 0xa2, 0x02, 0x12, 0x9e, 0x60, 0x9b, 0x92, 0xd8,
0xc0, 0x5e, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x3b, 0xce, 0xe1, 0x4c, 0x6b, 0x01, 0x00,
0x00,
}
func (m *SendAuthorization) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SendAuthorization) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SendAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.SpendLimit) > 0 {
for iNdEx := len(m.SpendLimit) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.SpendLimit[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAuthz(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func encodeVarintAuthz(dAtA []byte, offset int, v uint64) int {
offset -= sovAuthz(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *SendAuthorization) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.SpendLimit) > 0 {
for _, e := range m.SpendLimit {
l = e.Size()
n += 1 + l + sovAuthz(uint64(l))
}
}
return n
}
func sovAuthz(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozAuthz(x uint64) (n int) {
return sovAuthz(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *SendAuthorization) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SendAuthorization: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SendAuthorization: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SpendLimit", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAuthz
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAuthz
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.SpendLimit = append(m.SpendLimit, types.Coin{})
if err := m.SpendLimit[len(m.SpendLimit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAuthz(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAuthz
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipAuthz(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAuthz
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAuthz
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAuthz
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthAuthz
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupAuthz
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthAuthz
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthAuthz = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowAuthz = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupAuthz = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -6,11 +6,12 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
bank "github.com/cosmos/cosmos-sdk/x/bank/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authz "github.com/cosmos/cosmos-sdk/x/authz/exported"
) )
var ( var (
_ Authorization = &SendAuthorization{} _ authz.Authorization = &SendAuthorization{}
) )
// NewSendAuthorization creates a new SendAuthorization object. // NewSendAuthorization creates a new SendAuthorization object.
@ -26,20 +27,20 @@ func (authorization SendAuthorization) MethodName() string {
} }
// Accept implements Authorization.Accept. // Accept implements Authorization.Accept.
func (authorization SendAuthorization) Accept(msg sdk.ServiceMsg, block tmproto.Header) (allow bool, updated Authorization, delete bool) { func (authorization SendAuthorization) Accept(msg sdk.ServiceMsg, block tmproto.Header) (updated authz.Authorization, delete bool, err error) {
if reflect.TypeOf(msg.Request) == reflect.TypeOf(&bank.MsgSend{}) { if reflect.TypeOf(msg.Request) == reflect.TypeOf(&MsgSend{}) {
msg, ok := msg.Request.(*bank.MsgSend) msg, ok := msg.Request.(*MsgSend)
if ok { if ok {
limitLeft, isNegative := authorization.SpendLimit.SafeSub(msg.Amount) limitLeft, isNegative := authorization.SpendLimit.SafeSub(msg.Amount)
if isNegative { if isNegative {
return false, nil, false return nil, false, sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "requested amount is more than spend limit")
} }
if limitLeft.IsZero() { if limitLeft.IsZero() {
return true, nil, true return nil, true, nil
} }
return true, &SendAuthorization{SpendLimit: limitLeft}, false return &SendAuthorization{SpendLimit: limitLeft}, false, nil
} }
} }
return false, nil, false return nil, false, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "type mismatch")
} }

View File

@ -232,7 +232,7 @@ func (m *MsgVoteResponse) XXX_DiscardUnknown() {
var xxx_messageInfo_MsgVoteResponse proto.InternalMessageInfo var xxx_messageInfo_MsgVoteResponse proto.InternalMessageInfo
// MsgVoteWeightedResponse defines the MsgVoteWeighted response type. // MsgVoteWeightedResponse defines the Msg/VoteWeighted response type.
type MsgVoteWeightedResponse struct { type MsgVoteWeightedResponse struct {
} }

135
x/staking/types/authz.go Normal file
View File

@ -0,0 +1,135 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authz "github.com/cosmos/cosmos-sdk/x/authz/exported"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
var (
_ authz.Authorization = &StakeAuthorization{}
TypeDelegate = "/cosmos.staking.v1beta1.Msg/Delegate"
TypeUndelegate = "/cosmos.staking.v1beta1.Msg/Undelegate"
TypeBeginRedelegate = "/cosmos.staking.v1beta1.Msg/BeginRedelegate"
)
// NewStakeAuthorization creates a new StakeAuthorization object.
func NewStakeAuthorization(allowed []sdk.ValAddress, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin) (*StakeAuthorization, error) {
allowedValidators, deniedValidators, err := validateAndBech32fy(allowed, denied)
if err != nil {
return nil, err
}
authorization := StakeAuthorization{}
if allowedValidators != nil {
authorization.Validators = &StakeAuthorization_AllowList{AllowList: &StakeAuthorization_Validators{Address: allowedValidators}}
} else {
authorization.Validators = &StakeAuthorization_DenyList{DenyList: &StakeAuthorization_Validators{Address: deniedValidators}}
}
if amount != nil {
authorization.MaxTokens = amount
}
authorization.AuthorizationType = authzType
return &authorization, nil
}
// MethodName implements Authorization.MethodName.
func (authorization StakeAuthorization) MethodName() string {
authzType, err := normalizeAuthzType(authorization.AuthorizationType)
if err != nil {
panic(err)
}
return authzType
}
// Accept implements Authorization.Accept.
func (authorization StakeAuthorization) Accept(msg sdk.ServiceMsg, block tmproto.Header) (updated authz.Authorization, delete bool, err error) {
var validatorAddress string
var amount sdk.Coin
switch msg := msg.Request.(type) {
case *MsgDelegate:
validatorAddress = msg.ValidatorAddress
amount = msg.Amount
case *MsgUndelegate:
validatorAddress = msg.ValidatorAddress
amount = msg.Amount
case *MsgBeginRedelegate:
validatorAddress = msg.ValidatorDstAddress
amount = msg.Amount
default:
return nil, false, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "unknown msg type")
}
isValidatorExists := false
allowedList := authorization.GetAllowList().GetAddress()
for _, validator := range allowedList {
if validator == validatorAddress {
isValidatorExists = true
break
}
}
denyList := authorization.GetDenyList().GetAddress()
for _, validator := range denyList {
if validator == validatorAddress {
return nil, false, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, " cannot delegate/undelegate to %s validator", validator)
}
}
if !isValidatorExists {
return nil, false, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "cannot delegate/undelegate to %s validator", validatorAddress)
}
if authorization.MaxTokens == nil {
return &StakeAuthorization{Validators: authorization.GetValidators(), AuthorizationType: authorization.GetAuthorizationType()}, false, nil
}
limitLeft := authorization.MaxTokens.Sub(amount)
if limitLeft.IsZero() {
return nil, true, nil
}
return &StakeAuthorization{Validators: authorization.GetValidators(), MaxTokens: &limitLeft, AuthorizationType: authorization.GetAuthorizationType()}, false, nil
}
func validateAndBech32fy(allowed []sdk.ValAddress, denied []sdk.ValAddress) ([]string, []string, error) {
if len(allowed) == 0 && len(denied) == 0 {
return nil, nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "both allowed & deny list cannot be empty")
}
if len(allowed) > 0 && len(denied) > 0 {
return nil, nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "cannot set both allowed & deny list")
}
allowedValidators := make([]string, len(allowed))
if len(allowed) > 0 {
for i, validator := range allowed {
allowedValidators[i] = validator.String()
}
return allowedValidators, nil, nil
}
deniedValidators := make([]string, len(denied))
for i, validator := range denied {
deniedValidators[i] = validator.String()
}
return nil, deniedValidators, nil
}
func normalizeAuthzType(authzType AuthorizationType) (string, error) {
switch authzType {
case AuthorizationType_AUTHORIZATION_TYPE_DELEGATE:
return TypeDelegate, nil
case AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE:
return TypeUndelegate, nil
case AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE:
return TypeBeginRedelegate, nil
default:
return "", sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "unknown authorization type %T", authzType)
}
}

797
x/staking/types/authz.pb.go Normal file
View File

@ -0,0 +1,797 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/staking/v1beta1/authz.proto
package types
import (
fmt "fmt"
types "github.com/cosmos/cosmos-sdk/types"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
_ "github.com/regen-network/cosmos-proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// AuthorizationType defines the type of staking module authorization type
type AuthorizationType int32
const (
// AUTHORIZATION_TYPE_UNSPECIFIED specifies an unknown authorization type
AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED AuthorizationType = 0
// AUTHORIZATION_TYPE_DELEGATE defines an authorization type for Msg/Delegate
AuthorizationType_AUTHORIZATION_TYPE_DELEGATE AuthorizationType = 1
// AUTHORIZATION_TYPE_UNDELEGATE defines an authorization type for Msg/Undelegate
AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE AuthorizationType = 2
// AUTHORIZATION_TYPE_REDELEGATE defines an authorization type for Msg/BeginRedelegate
AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE AuthorizationType = 3
)
var AuthorizationType_name = map[int32]string{
0: "AUTHORIZATION_TYPE_UNSPECIFIED",
1: "AUTHORIZATION_TYPE_DELEGATE",
2: "AUTHORIZATION_TYPE_UNDELEGATE",
3: "AUTHORIZATION_TYPE_REDELEGATE",
}
var AuthorizationType_value = map[string]int32{
"AUTHORIZATION_TYPE_UNSPECIFIED": 0,
"AUTHORIZATION_TYPE_DELEGATE": 1,
"AUTHORIZATION_TYPE_UNDELEGATE": 2,
"AUTHORIZATION_TYPE_REDELEGATE": 3,
}
func (x AuthorizationType) String() string {
return proto.EnumName(AuthorizationType_name, int32(x))
}
func (AuthorizationType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_d6d8cdbc6f4432f0, []int{0}
}
// StakeAuthorization defines authorization for delegate/undelegate/redelegate.
type StakeAuthorization struct {
// max_tokens specifies the maximum amount of tokens can be delegate to a validator. If it is
// empty, there is no spend limit and any amount of coins can be delegated.
MaxTokens *types.Coin `protobuf:"bytes,1,opt,name=max_tokens,json=maxTokens,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"max_tokens,omitempty"`
// validators is the oneof that represents either allow_list or deny_list
//
// Types that are valid to be assigned to Validators:
// *StakeAuthorization_AllowList
// *StakeAuthorization_DenyList
Validators isStakeAuthorization_Validators `protobuf_oneof:"validators"`
// authorization_type defines one of AuthorizationType.
AuthorizationType AuthorizationType `protobuf:"varint,4,opt,name=authorization_type,json=authorizationType,proto3,enum=cosmos.staking.v1beta1.AuthorizationType" json:"authorization_type,omitempty"`
}
func (m *StakeAuthorization) Reset() { *m = StakeAuthorization{} }
func (m *StakeAuthorization) String() string { return proto.CompactTextString(m) }
func (*StakeAuthorization) ProtoMessage() {}
func (*StakeAuthorization) Descriptor() ([]byte, []int) {
return fileDescriptor_d6d8cdbc6f4432f0, []int{0}
}
func (m *StakeAuthorization) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StakeAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_StakeAuthorization.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *StakeAuthorization) XXX_Merge(src proto.Message) {
xxx_messageInfo_StakeAuthorization.Merge(m, src)
}
func (m *StakeAuthorization) XXX_Size() int {
return m.Size()
}
func (m *StakeAuthorization) XXX_DiscardUnknown() {
xxx_messageInfo_StakeAuthorization.DiscardUnknown(m)
}
var xxx_messageInfo_StakeAuthorization proto.InternalMessageInfo
type isStakeAuthorization_Validators interface {
isStakeAuthorization_Validators()
MarshalTo([]byte) (int, error)
Size() int
}
type StakeAuthorization_AllowList struct {
AllowList *StakeAuthorization_Validators `protobuf:"bytes,2,opt,name=allow_list,json=allowList,proto3,oneof" json:"allow_list,omitempty"`
}
type StakeAuthorization_DenyList struct {
DenyList *StakeAuthorization_Validators `protobuf:"bytes,3,opt,name=deny_list,json=denyList,proto3,oneof" json:"deny_list,omitempty"`
}
func (*StakeAuthorization_AllowList) isStakeAuthorization_Validators() {}
func (*StakeAuthorization_DenyList) isStakeAuthorization_Validators() {}
func (m *StakeAuthorization) GetValidators() isStakeAuthorization_Validators {
if m != nil {
return m.Validators
}
return nil
}
func (m *StakeAuthorization) GetMaxTokens() *types.Coin {
if m != nil {
return m.MaxTokens
}
return nil
}
func (m *StakeAuthorization) GetAllowList() *StakeAuthorization_Validators {
if x, ok := m.GetValidators().(*StakeAuthorization_AllowList); ok {
return x.AllowList
}
return nil
}
func (m *StakeAuthorization) GetDenyList() *StakeAuthorization_Validators {
if x, ok := m.GetValidators().(*StakeAuthorization_DenyList); ok {
return x.DenyList
}
return nil
}
func (m *StakeAuthorization) GetAuthorizationType() AuthorizationType {
if m != nil {
return m.AuthorizationType
}
return AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED
}
// XXX_OneofWrappers is for the internal use of the proto package.
func (*StakeAuthorization) XXX_OneofWrappers() []interface{} {
return []interface{}{
(*StakeAuthorization_AllowList)(nil),
(*StakeAuthorization_DenyList)(nil),
}
}
// Validators defines list of validator addresses.
type StakeAuthorization_Validators struct {
Address []string `protobuf:"bytes,1,rep,name=address,proto3" json:"address,omitempty"`
}
func (m *StakeAuthorization_Validators) Reset() { *m = StakeAuthorization_Validators{} }
func (m *StakeAuthorization_Validators) String() string { return proto.CompactTextString(m) }
func (*StakeAuthorization_Validators) ProtoMessage() {}
func (*StakeAuthorization_Validators) Descriptor() ([]byte, []int) {
return fileDescriptor_d6d8cdbc6f4432f0, []int{0, 0}
}
func (m *StakeAuthorization_Validators) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StakeAuthorization_Validators) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_StakeAuthorization_Validators.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *StakeAuthorization_Validators) XXX_Merge(src proto.Message) {
xxx_messageInfo_StakeAuthorization_Validators.Merge(m, src)
}
func (m *StakeAuthorization_Validators) XXX_Size() int {
return m.Size()
}
func (m *StakeAuthorization_Validators) XXX_DiscardUnknown() {
xxx_messageInfo_StakeAuthorization_Validators.DiscardUnknown(m)
}
var xxx_messageInfo_StakeAuthorization_Validators proto.InternalMessageInfo
func (m *StakeAuthorization_Validators) GetAddress() []string {
if m != nil {
return m.Address
}
return nil
}
func init() {
proto.RegisterEnum("cosmos.staking.v1beta1.AuthorizationType", AuthorizationType_name, AuthorizationType_value)
proto.RegisterType((*StakeAuthorization)(nil), "cosmos.staking.v1beta1.StakeAuthorization")
proto.RegisterType((*StakeAuthorization_Validators)(nil), "cosmos.staking.v1beta1.StakeAuthorization.Validators")
}
func init() {
proto.RegisterFile("cosmos/staking/v1beta1/authz.proto", fileDescriptor_d6d8cdbc6f4432f0)
}
var fileDescriptor_d6d8cdbc6f4432f0 = []byte{
// 462 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xcb, 0x6e, 0xd3, 0x40,
0x14, 0x86, 0x3d, 0x0d, 0x02, 0x72, 0xb8, 0xa8, 0x19, 0x21, 0x94, 0x06, 0x31, 0x2d, 0x59, 0x40,
0xb8, 0x74, 0xac, 0x16, 0xb1, 0x61, 0x97, 0xb4, 0x2e, 0x8d, 0x54, 0xb5, 0x95, 0xeb, 0x56, 0xd0,
0x8d, 0x35, 0x89, 0x47, 0xc9, 0x28, 0xb6, 0x27, 0xf2, 0x4c, 0x4a, 0xd2, 0xa7, 0xe0, 0x09, 0x78,
0x00, 0xd6, 0x3c, 0x04, 0x0b, 0x16, 0x15, 0x2b, 0x76, 0xa0, 0xe4, 0x45, 0x90, 0xc7, 0xae, 0xa1,
0x34, 0x65, 0xc3, 0xca, 0x97, 0xf3, 0xcd, 0xf7, 0x9f, 0x63, 0x1d, 0x43, 0xbd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00,
}
func (m *StakeAuthorization) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StakeAuthorization) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StakeAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.AuthorizationType != 0 {
i = encodeVarintAuthz(dAtA, i, uint64(m.AuthorizationType))
i--
dAtA[i] = 0x20
}
if m.Validators != nil {
{
size := m.Validators.Size()
i -= size
if _, err := m.Validators.MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
}
}
if m.MaxTokens != nil {
{
size, err := m.MaxTokens.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAuthz(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *StakeAuthorization_AllowList) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StakeAuthorization_AllowList) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.AllowList != nil {
{
size, err := m.AllowList.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAuthz(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
return len(dAtA) - i, nil
}
func (m *StakeAuthorization_DenyList) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StakeAuthorization_DenyList) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
if m.DenyList != nil {
{
size, err := m.DenyList.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintAuthz(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
return len(dAtA) - i, nil
}
func (m *StakeAuthorization_Validators) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StakeAuthorization_Validators) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StakeAuthorization_Validators) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Address) > 0 {
for iNdEx := len(m.Address) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Address[iNdEx])
copy(dAtA[i:], m.Address[iNdEx])
i = encodeVarintAuthz(dAtA, i, uint64(len(m.Address[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func encodeVarintAuthz(dAtA []byte, offset int, v uint64) int {
offset -= sovAuthz(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *StakeAuthorization) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.MaxTokens != nil {
l = m.MaxTokens.Size()
n += 1 + l + sovAuthz(uint64(l))
}
if m.Validators != nil {
n += m.Validators.Size()
}
if m.AuthorizationType != 0 {
n += 1 + sovAuthz(uint64(m.AuthorizationType))
}
return n
}
func (m *StakeAuthorization_AllowList) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.AllowList != nil {
l = m.AllowList.Size()
n += 1 + l + sovAuthz(uint64(l))
}
return n
}
func (m *StakeAuthorization_DenyList) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.DenyList != nil {
l = m.DenyList.Size()
n += 1 + l + sovAuthz(uint64(l))
}
return n
}
func (m *StakeAuthorization_Validators) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Address) > 0 {
for _, s := range m.Address {
l = len(s)
n += 1 + l + sovAuthz(uint64(l))
}
}
return n
}
func sovAuthz(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozAuthz(x uint64) (n int) {
return sovAuthz(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *StakeAuthorization) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StakeAuthorization: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StakeAuthorization: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxTokens", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAuthz
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAuthz
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.MaxTokens == nil {
m.MaxTokens = &types.Coin{}
}
if err := m.MaxTokens.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AllowList", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAuthz
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAuthz
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &StakeAuthorization_Validators{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Validators = &StakeAuthorization_AllowList{v}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DenyList", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthAuthz
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthAuthz
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &StakeAuthorization_Validators{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.Validators = &StakeAuthorization_DenyList{v}
iNdEx = postIndex
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field AuthorizationType", wireType)
}
m.AuthorizationType = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.AuthorizationType |= AuthorizationType(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipAuthz(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAuthz
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *StakeAuthorization_Validators) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Validators: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Validators: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAuthz
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAuthz
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAuthz
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = append(m.Address, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAuthz(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAuthz
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipAuthz(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAuthz
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAuthz
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAuthz
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthAuthz
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupAuthz
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthAuthz
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthAuthz = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowAuthz = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupAuthz = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -0,0 +1,282 @@
package types_test
import (
"testing"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/require"
)
var (
coin100 = sdk.NewInt64Coin("steak", 100)
coin50 = sdk.NewInt64Coin("steak", 50)
delAddr = sdk.AccAddress("_____delegator _____")
val1 = sdk.ValAddress("_____validator1_____")
val2 = sdk.ValAddress("_____validator2_____")
val3 = sdk.ValAddress("_____validator3_____")
)
func TestAuthzAuthorizations(t *testing.T) {
// verify MethodName
delAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100)
require.Equal(t, delAuth.MethodName(), stakingtypes.TypeDelegate)
// error both allow & deny list
_, err := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100)
require.Error(t, err)
// verify MethodName
undelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100)
require.Equal(t, undelAuth.MethodName(), stakingtypes.TypeUndelegate)
// verify MethodName
beginRedelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100)
require.Equal(t, beginRedelAuth.MethodName(), stakingtypes.TypeBeginRedelegate)
validators1_2 := []string{val1.String(), val2.String()}
testCases := []struct {
msg string
allowed []sdk.ValAddress
denied []sdk.ValAddress
msgType stakingtypes.AuthorizationType
limit *sdk.Coin
srvMsg sdk.ServiceMsg
expectErr bool
isDelete bool
updatedAuthorization *stakingtypes.StakeAuthorization
}{
{
"delegate: expect 0 remaining coins",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
&coin100,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val1, coin100),
false,
true,
nil,
},
{
"delegate: verify remaining coins",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
&coin100,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val1, coin50),
false,
false,
&stakingtypes.StakeAuthorization{
Validators: &stakingtypes.StakeAuthorization_AllowList{
AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2},
}, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE},
},
{
"delegate: testing with invalid validator",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
&coin100,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val3, coin100),
true,
false,
nil,
},
{
"delegate: testing delegate without spent limit",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
nil,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val2, coin100),
false,
false,
&stakingtypes.StakeAuthorization{
Validators: &stakingtypes.StakeAuthorization_AllowList{
AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2},
}, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE},
},
{
"delegate: fail validator denied",
[]sdk.ValAddress{},
[]sdk.ValAddress{val1},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
nil,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val1, coin100),
true,
false,
nil,
},
{
"undelegate: expect 0 remaining coins",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin100),
false,
true,
nil,
},
{
"undelegate: verify remaining coins",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin50),
false,
false,
&stakingtypes.StakeAuthorization{
Validators: &stakingtypes.StakeAuthorization_AllowList{
AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2},
}, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE},
},
{
"undelegate: testing with invalid validator",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val3, coin100),
true,
false,
nil,
},
{
"undelegate: testing delegate without spent limit",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
nil,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val2, coin100),
false,
false,
&stakingtypes.StakeAuthorization{
Validators: &stakingtypes.StakeAuthorization_AllowList{
AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2},
}, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE},
},
{
"undelegate: fail cannot undelegate, permission denied",
[]sdk.ValAddress{},
[]sdk.ValAddress{val1},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin100),
true,
false,
nil,
},
{
"redelegate: expect 0 remaining coins",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin100),
false,
true,
nil,
},
{
"redelegate: verify remaining coins",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val1, coin50),
false,
false,
&stakingtypes.StakeAuthorization{
Validators: &stakingtypes.StakeAuthorization_AllowList{
AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2},
}, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE},
},
{
"redelegate: testing with invalid validator",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val3, coin100),
true,
false,
nil,
},
{
"redelegate: testing delegate without spent limit",
[]sdk.ValAddress{val1, val2},
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
nil,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val2, coin100),
false,
false,
&stakingtypes.StakeAuthorization{
Validators: &stakingtypes.StakeAuthorization_AllowList{
AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2},
}, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE},
},
{
"redelegate: fail cannot undelegate, permission denied",
[]sdk.ValAddress{},
[]sdk.ValAddress{val1},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val1, coin100),
true,
false,
nil,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.msg, func(t *testing.T) {
delAuth, err := stakingtypes.NewStakeAuthorization(tc.allowed, tc.denied, tc.msgType, tc.limit)
require.NoError(t, err)
updated, del, err := delAuth.Accept(tc.srvMsg, tmproto.Header{})
if tc.expectErr {
require.Error(t, err)
require.Equal(t, tc.isDelete, del)
} else {
require.NoError(t, err)
require.Equal(t, tc.isDelete, del)
if tc.updatedAuthorization != nil {
require.Equal(t, tc.updatedAuthorization.String(), updated.String())
}
}
})
}
}
func createSrvMsgUndelegate(methodName string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) sdk.ServiceMsg {
msg := stakingtypes.NewMsgUndelegate(delAddr, valAddr, amount)
return sdk.ServiceMsg{
MethodName: methodName,
Request: msg,
}
}
func createSrvMsgReDelegate(methodName string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) sdk.ServiceMsg {
msg := stakingtypes.NewMsgBeginRedelegate(delAddr, valAddr, valAddr, amount)
return sdk.ServiceMsg{
MethodName: methodName,
Request: msg,
}
}
func createSrvMsgDelegate(methodName string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) sdk.ServiceMsg {
msg := stakingtypes.NewMsgDelegate(delAddr, valAddr, amount)
return sdk.ServiceMsg{
MethodName: methodName,
Request: msg,
}
}

File diff suppressed because it is too large Load Diff