diff --git a/proto/cosmos/msg_authorization/v1beta1/genesis.proto b/proto/cosmos/msg_authorization/v1beta1/genesis.proto new file mode 100644 index 000000000000..9eadaf8ba414 --- /dev/null +++ b/proto/cosmos/msg_authorization/v1beta1/genesis.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package cosmos.msg_authorization.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmos/msg_authorization/v1beta1/tx.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/msg_authorization/types"; + +// GenesisState defines the msg_authorization module's genesis state. +message GenesisState { + repeated MsgGrantAuthorization authorization = 1 [(gogoproto.nullable) = false]; +} diff --git a/proto/cosmos/msg_authorization/v1beta1/msg_authorization.proto b/proto/cosmos/msg_authorization/v1beta1/msg_authorization.proto new file mode 100644 index 000000000000..b705f3ce8710 --- /dev/null +++ b/proto/cosmos/msg_authorization/v1beta1/msg_authorization.proto @@ -0,0 +1,44 @@ +syntax = "proto3"; +package cosmos.msg_authorization.v1beta1; + +import "cosmos/base/v1beta1/coin.proto"; +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/protobuf/any.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/msg_authorization/types"; + +// SendAuthorization allows the grantee to spend up to spend_limit coins from +// the granter's account. +message SendAuthorization{ + option (gogoproto.equal) = true; + option (gogoproto.goproto_getters) = false; + 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", + (gogoproto.moretags) = "yaml:\"spend_limit\"" + ]; +} + +// GenericAuthorization gives the grantee unrestricted permissions to execute +// the provide method on behalf of the granter's account. +message GenericAuthorization{ + option (gogoproto.equal) = true; + option (gogoproto.goproto_getters) = false; + option (cosmos_proto.implements_interface) = "Authorization"; + + string method_name = 1[ + (gogoproto.customname)="MessageName" + ]; +} + +// TODO +message AuthorizationGrant{ + option (gogoproto.goproto_getters) = false; + google.protobuf.Any authorization = 1 [ + (cosmos_proto.accepts_interface) = "Authorization" + ]; + int64 expiration = 2; +} diff --git a/proto/cosmos/msg_authorization/v1beta1/query.proto b/proto/cosmos/msg_authorization/v1beta1/query.proto new file mode 100644 index 000000000000..f6726d6af8e3 --- /dev/null +++ b/proto/cosmos/msg_authorization/v1beta1/query.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; +package cosmos.msg_authorization.v1beta1; + +import "gogoproto/gogo.proto"; +import "google/protobuf/any.proto"; +import "google/api/annotations.proto"; +import "cosmos_proto/cosmos.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/msg_authorization/types"; + +// Query defines the gRPC querier service. +service Query { + // Returns any `Authorization` (or `nil`), with the expiration time, granted to the grantee by the granter for the provided msg type. + rpc Authorization(QueryAuthorizationRequest) returns (QueryAuthorizationResponse) { + option (google.api.http).get = "/cosmos/msgauth/v1beta1/granters/{granter_addr}/grantees/{grantee_addr}/{msg_type}"; + } + +} + +// QueryAuthorizationRequest is the request type for the Query/Authorization RPC method. +message QueryAuthorizationRequest { + option (gogoproto.equal) = false; + option (gogoproto.goproto_getters) = false; + + string granter_addr = 1; + string grantee_addr = 2; + + string msg_type = 3; +} + +// QueryAuthorizationResponse is the response type for the Query/Authorization RPC method. +message QueryAuthorizationResponse { + // account defines the account of the corresponding address. + google.protobuf.Any authorization = 1 [(cosmos_proto.accepts_interface) = "Authorization"]; +} diff --git a/proto/cosmos/msg_authorization/v1beta1/tx.proto b/proto/cosmos/msg_authorization/v1beta1/tx.proto new file mode 100644 index 000000000000..55a6844733d3 --- /dev/null +++ b/proto/cosmos/msg_authorization/v1beta1/tx.proto @@ -0,0 +1,83 @@ +syntax = "proto3"; +package cosmos.msg_authorization.v1beta1; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/any.proto"; +import "cosmos/base/abci/v1beta1/abci.proto"; +option go_package = "github.com/cosmos/cosmos-sdk/x/msg_authorization/types"; +option (gogoproto.equal_all) = true; + + +// Msg defines the msg_authorization Msg service. +service Msg { + // GrantAuthorization grants the provided authorization to the grantee on the granter's + // account with the provided expiration time. + rpc GrantAuthorization(MsgGrantAuthorization) returns (MsgGrantAuthorizationResponse); + // ExecAuthorized attempts to execute the provided messages using + // authorizations granted to the grantee. Each message should have only + // one signer corresponding to the granter of the authorization. + rpc ExecAuthorized(MsgExecAuthorized) returns (MsgExecAuthorizedResponse); + // RevokeAuthorization revokes any authorization corresponding to the provided method name on the + // granter's account that has been granted to the grantee. + rpc RevokeAuthorization(MsgRevokeAuthorization) returns (MsgRevokeAuthorizationResponse); +} + +// MsgGrantAuthorization grants the provided authorization to the grantee on the granter's +// account with the provided expiration time. +message MsgGrantAuthorization{ + option (gogoproto.equal) = true; + option (gogoproto.goproto_getters) = false; + option (gogoproto.goproto_stringer) = false; + + string granter = 1; + string grantee = 2; + + google.protobuf.Any authorization = 3 [ + (cosmos_proto.accepts_interface) = "Authorization" + ]; + google.protobuf.Timestamp expiration = 4 [ + (gogoproto.nullable) = false, + (gogoproto.stdtime) = true + ]; +} + + +// MsgExecAuthorizedResponse defines the Msg/MsgExecAuthorizedResponse response type. +message MsgExecAuthorizedResponse { + option (gogoproto.equal) = false; + + cosmos.base.abci.v1beta1.Result result = 1; + } + +// MsgExecAuthorized attempts to execute the provided messages using +// authorizations granted to the grantee. Each message should have only +// one signer corresponding to the granter of the authorization. +message MsgExecAuthorized { + option (gogoproto.goproto_getters) = false; + option (gogoproto.goproto_stringer) = false; + + string grantee = 1; + repeated google.protobuf.Any msgs = 2 [ + (cosmos_proto.accepts_interface) = "github.com/cosmos/cosmos-sdk/types.Msg", + (gogoproto.moretags) = "yaml:\"msgs\"" + ]; +} + +// MsgGrantAuthorizationResponse defines the Msg/MsgGrantAuthorization response type. +message MsgGrantAuthorizationResponse { } + +// MsgRevokeAuthorization revokes any authorization with the provided sdk.Msg type on the +// granter's account with that has been granted to the grantee. +message MsgRevokeAuthorization{ + option (gogoproto.goproto_getters) = false; + option (gogoproto.goproto_stringer) = false; + + string granter = 1; + string grantee = 2; + string authorization_msg_type = 3 [(gogoproto.moretags) = "yaml:\"authorization_msg_type\""]; +} + +// MsgRevokeAuthorizationResponse defines the Msg/MsgRevokeAuthorizationResponse response type. +message MsgRevokeAuthorizationResponse { } diff --git a/simapp/app.go b/simapp/app.go index 5c3412f36003..3662df75bf2e 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -40,6 +40,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/capability" capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + "github.com/cosmos/cosmos-sdk/x/crisis" crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" @@ -83,6 +84,10 @@ import ( upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + msgauth "github.com/cosmos/cosmos-sdk/x/msg_authorization" + msgauthkeeper "github.com/cosmos/cosmos-sdk/x/msg_authorization/keeper" + msgauthtypes "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + // unnamed import of statik for swagger UI support _ "github.com/cosmos/cosmos-sdk/client/docs/statik" ) @@ -114,6 +119,7 @@ var ( upgrade.AppModuleBasic{}, evidence.AppModuleBasic{}, transfer.AppModuleBasic{}, + msgauth.AppModuleBasic{}, vesting.AppModuleBasic{}, ) @@ -164,6 +170,7 @@ type SimApp struct { CrisisKeeper crisiskeeper.Keeper UpgradeKeeper upgradekeeper.Keeper ParamsKeeper paramskeeper.Keeper + MsgAuthKeeper msgauthkeeper.Keeper IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly EvidenceKeeper evidencekeeper.Keeper TransferKeeper ibctransferkeeper.Keeper @@ -211,6 +218,7 @@ func NewSimApp( minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, + msgauthtypes.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) @@ -276,6 +284,12 @@ func NewSimApp( appCodec, keys[ibchost.StoreKey], app.StakingKeeper, scopedIBCKeeper, ) + // TODO: Add rest of the modules' routes(at the moment only bank routers added). + msgAuthRouter := msgauthtypes.NewRouter() + msgAuthRouter.AddRoute(banktypes.RouterKey, bank.NewHandler(app.BankKeeper)) + + app.MsgAuthKeeper = msgauthkeeper.NewKeeper(keys[msgauthtypes.StoreKey], appCodec, msgAuthRouter) + // register the proposal types govRouter := govtypes.NewRouter() govRouter.AddRoute(govtypes.RouterKey, govtypes.ProposalHandler). @@ -334,6 +348,7 @@ func NewSimApp( evidence.NewAppModule(app.EvidenceKeeper), ibc.NewAppModule(app.IBCKeeper), params.NewAppModule(app.ParamsKeeper), + msgauth.NewAppModule(appCodec, app.MsgAuthKeeper, app.AccountKeeper, app.BankKeeper), transferModule, ) @@ -355,7 +370,7 @@ func NewSimApp( app.mm.SetOrderInitGenesis( capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, - ibchost.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, ibctransfertypes.ModuleName, + ibchost.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, msgauthtypes.ModuleName, ibctransfertypes.ModuleName, ) app.mm.RegisterInvariants(&app.CrisisKeeper) @@ -380,6 +395,7 @@ func NewSimApp( slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), params.NewAppModule(app.ParamsKeeper), evidence.NewAppModule(app.EvidenceKeeper), + msgauth.NewAppModule(appCodec, app.MsgAuthKeeper, app.AccountKeeper, app.BankKeeper), ibc.NewAppModule(app.IBCKeeper), transferModule, ) diff --git a/x/msg_authorization/client/cli/cli_test.go b/x/msg_authorization/client/cli/cli_test.go new file mode 100644 index 000000000000..66f61e957317 --- /dev/null +++ b/x/msg_authorization/client/cli/cli_test.go @@ -0,0 +1,469 @@ +// +build norace + +package cli_test + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/gogo/protobuf/proto" + "github.com/spf13/viper" + + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "github.com/cosmos/cosmos-sdk/testutil/network" + sdk "github.com/cosmos/cosmos-sdk/types" + bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" + banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/client/cli" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + "github.com/stretchr/testify/suite" + + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + tmcli "github.com/tendermint/tendermint/libs/cli" +) + +type IntegrationTestSuite struct { + suite.Suite + + cfg network.Config + network *network.Network + grantee sdk.AccAddress +} + +func (s *IntegrationTestSuite) SetupSuite() { + s.T().Log("setting up integration test suite") + + cfg := network.DefaultConfig() + cfg.NumValidators = 1 + + s.cfg = cfg + s.network = network.New(s.T(), cfg) + + val := s.network.Validators[0] + + // Create new account in the keyring. + info, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) + + // Send some funds to the new account. + _, err = banktestutil.MsgSendExec( + val.ClientCtx, + val.Address, + newAddr, + sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(200))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + 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) + s.grantee = newAddr + + _, err = s.network.WaitForHeight(1) + s.Require().NoError(err) +} + +func (s *IntegrationTestSuite) TearDownSuite() { + s.T().Log("tearing down integration test suite") + s.network.Cleanup() +} + +var typeMsgSend = types.SendAuthorization{}.MethodName() + +func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() { + val := s.network.Validators[0] + grantee := s.grantee + + twoHours := 60 * 2 // In seconds + pastHour := 60 * -1 // In seconds + + testCases := []struct { + name string + args []string + respType proto.Message + expectedCode uint32 + expectErr bool + expiration int + }{ + { + "Invalid granter Address", + []string{ + "grantee_addr", + typeMsgSend, + "100steak", + fmt.Sprintf("--%s=%s", flags.FlagFrom, "granter"), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), + }, + nil, + 0, + true, + twoHours, + }, + { + "Invalid grantee Address", + []string{ + "grantee_addr", + typeMsgSend, + "100steak", + fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), + }, + nil, 0, + true, + twoHours, + }, + { + "Invalid expiration time", + []string{ + grantee.String(), + typeMsgSend, + "100steak", + fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + fmt.Sprintf("--%s=%d", cli.FlagExpiration, pastHour), + }, + nil, 0, + true, + pastHour, + }, + { + "Valid tx", + []string{ + grantee.String(), + typeMsgSend, + "100steak", + 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=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + }, + &sdk.TxResponse{}, 0, + false, + twoHours, + }, + } + + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + clientCtx := val.ClientCtx + viper.Set(cli.FlagExpiration, tc.expiration) + + out, err := execGrantSendAuthorization( + val, + tc.args, + ) + if tc.expectErr { + s.Require().Error(err) + } else { + s.Require().NoError(err) + s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + txResp := tc.respType.(*sdk.TxResponse) + s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + } + }) + } + +} + +func (s *IntegrationTestSuite) TestQueryAuthorizations() { + val := s.network.Validators[0] + + grantee := s.grantee + twoHours := 60 * 2 // In seconds + viper.Set(cli.FlagExpiration, twoHours) + + _, err := execGrantSendAuthorization( + val, + []string{ + grantee.String(), + typeMsgSend, + "100steak", + 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{ + "authorization", + val.Address.String(), + "invalid grantee", + typeMsgSend, + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, + true, + "", + }, + { + "Error: Invalid granter", + []string{ + "authorization", + "invalid granter", + grantee.String(), + typeMsgSend, + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, + true, + "", + }, + { + "no authorization found", + []string{ + "authorization", + val.Address.String(), + grantee.String(), + "typeMsgSend", + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, + true, + "", + }, + { + "Valid txn (json)", + []string{ + "authorization", + val.Address.String(), + grantee.String(), + typeMsgSend, + fmt.Sprintf("--%s=json", tmcli.OutputFlag), + }, + false, + `{"@type":"/cosmos.msg_authorization.v1beta1.SendAuthorization","spend_limit":[{"denom":"steak","amount":"100"}]}`, + }, + } + for _, tc := range testCases { + tc := tc + + s.Run(tc.name, func() { + cmd := cli.GetQueryCmd() + 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().Equal(tc.expectedOutput, strings.TrimSpace(out.String())) + } + }) + } +} + +func execGrantSendAuthorization(val *network.Validator, args []string) (testutil.BufferWriter, error) { + cmd := cli.NewCmdGrantAuthorization() + clientCtx := val.ClientCtx + return clitestutil.ExecTestCLICmd(clientCtx, cmd, args) +} + +func (s *IntegrationTestSuite) TestCmdRevokeAuthorizations() { + val := s.network.Validators[0] + + grantee := s.grantee + twoHours := 60 * 2 // In seconds + + viper.Set(cli.FlagExpiration, twoHours) + + _, err := execGrantSendAuthorization( + val, + []string{ + grantee.String(), + typeMsgSend, + "100steak", + 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 + respType proto.Message + expectedCode uint32 + expectErr bool + }{ + { + "invalid grantee address", + []string{ + "invlid grantee", + typeMsgSend, + fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + }, + nil, + 0, + true, + }, + { + "invalid granter address", + []string{ + grantee.String(), + typeMsgSend, + fmt.Sprintf("--%s=%s", flags.FlagFrom, "granter"), + fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), + }, + nil, + 0, + true, + }, + { + "Valid tx", + []string{ + grantee.String(), + typeMsgSend, + fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + }, + &sdk.TxResponse{}, 0, + false, + }, + } + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + cmd := cli.NewCmdRevokeAuthorization() + 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().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + + txResp := tc.respType.(*sdk.TxResponse) + s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + } + }) + } +} + +func (s *IntegrationTestSuite) TestNewExecAuthorized() { + val := s.network.Validators[0] + + grantee := s.grantee + + now := time.Now() + twoHours := now.Add(time.Minute * time.Duration(120)).Unix() + + viper.Set(cli.FlagExpiration, twoHours) + _, err := execGrantSendAuthorization( + val, + []string{ + grantee.String(), + typeMsgSend, + fmt.Sprintf("12%stoken", val.Moniker), + 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", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + }, + ) + s.Require().NoError(err) + tokens := sdk.NewCoins( + sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(12)), + ) + normalGeneratedTx, err := bankcli.MsgSendExec( + val.ClientCtx, + val.Address, + grantee, + tokens, + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + 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.FlagGenerateOnly), + ) + s.Require().NoError(err) + execMsg, cleanup1 := testutil.WriteToNewTempFile(s.T(), normalGeneratedTx.String()) + defer cleanup1() + testCases := []struct { + name string + args []string + respType proto.Message + expectedCode uint32 + 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", + []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), + }, + &sdk.TxResponse{}, + 0, + false, + }, + } + + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + + cmd := cli.NewCmdSendAs() + 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().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String()) + txResp := tc.respType.(*sdk.TxResponse) + s.Require().Equal(tc.expectedCode, txResp.Code, out.String()) + } + }) + } +} + +func TestIntegrationTestSuite(t *testing.T) { + suite.Run(t, new(IntegrationTestSuite)) +} diff --git a/x/msg_authorization/client/cli/flags.go b/x/msg_authorization/client/cli/flags.go new file mode 100644 index 000000000000..a77534c3551f --- /dev/null +++ b/x/msg_authorization/client/cli/flags.go @@ -0,0 +1,3 @@ +package cli + +const FlagExpiration = "expiration" diff --git a/x/msg_authorization/client/cli/query.go b/x/msg_authorization/client/cli/query.go new file mode 100644 index 000000000000..f86b5bde1526 --- /dev/null +++ b/x/msg_authorization/client/cli/query.go @@ -0,0 +1,75 @@ +package cli + +import ( + "context" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + "github.com/spf13/cobra" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd() *cobra.Command { + authorizationQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the msg authorization module", + Long: "", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + authorizationQueryCmd.AddCommand( + GetCmdQueryAuthorization(), + ) + + return authorizationQueryCmd +} + +// GetCmdQueryAuthorization implements the query authorizations command. +func GetCmdQueryAuthorization() *cobra.Command { + cmd := &cobra.Command{ + Use: "authorization [granter-addr] [grantee-addr] [msg-type]", + Args: cobra.ExactArgs(3), + Short: "query authorization for a granter-grantee pair", + Long: "query authorization for a granter-grantee pair", + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + granterAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + granteeAddr, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + msgAuthorized := args[2] + + res, err := queryClient.Authorization( + context.Background(), + &types.QueryAuthorizationRequest{ + GranterAddr: granterAddr.String(), + GranteeAddr: granteeAddr.String(), + MsgType: msgAuthorized, + }, + ) + if err != nil { + return err + } + + return clientCtx.PrintOutput(res.Authorization) + }, + } + flags.AddQueryFlagsToCmd(cmd) + return cmd +} diff --git a/x/msg_authorization/client/cli/tx.go b/x/msg_authorization/client/cli/tx.go new file mode 100644 index 000000000000..5678570403aa --- /dev/null +++ b/x/msg_authorization/client/cli/tx.go @@ -0,0 +1,160 @@ +package cli + +import ( + "errors" + "time" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd() *cobra.Command { + AuthorizationTxCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Authorization transactions subcommands", + Long: "Authorize and revoke access to execute transactions on behalf of your address", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + AuthorizationTxCmd.AddCommand( + NewCmdGrantAuthorization(), + NewCmdRevokeAuthorization(), + NewCmdSendAs(), + ) + + return AuthorizationTxCmd +} + +func NewCmdGrantAuthorization() *cobra.Command { + cmd := &cobra.Command{ + Use: "grant [grantee_address] [msg-type] [limit] --from=[granter]", + Short: "Grant authorization to an address", + Long: "Grant authorization to an address to execute a transaction on your behalf", + Args: cobra.RangeArgs(2, 3), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } + grantee, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + msgType := args[1] + + var authorization types.Authorization + switch msgType { + case (types.SendAuthorization{}.MethodName()): + limit, err := sdk.ParseCoins(args[2]) + if err != nil { + return err + } + authorization = &types.SendAuthorization{ + SpendLimit: limit, + } + case (types.GenericAuthorization{}.MethodName()): + authorization = types.NewGenericAuthorization(msgType) + default: + return errors.New("invalid authorization type") + } + + period := time.Duration(viper.GetInt64(FlagExpiration)) * time.Second + + msg, err := types.NewMsgGrantAuthorization(clientCtx.GetFromAddress(), grantee, authorization, time.Now().Add(period)) + if err != nil { + return err + } + if err := msg.ValidateBasic(); err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + + }, + } + flags.AddTxFlagsToCmd(cmd) + cmd.Flags().Int64(FlagExpiration, int64(3600*24*365), "The second unit of time duration which the authorization is active for the user; Default is a year") + return cmd +} + +func NewCmdRevokeAuthorization() *cobra.Command { + cmd := &cobra.Command{ + Use: "revoke [grantee_address] [msg_type] --from=[granter_address]", + Short: "revoke authorization", + Long: "revoke authorization from an address for a transaction", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } + + grantee, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + granter := clientCtx.GetFromAddress() + + msgAuthorized := args[1] + + msg := types.NewMsgRevokeAuthorization(granter, grantee, msgAuthorized) + if err := msg.ValidateBasic(); err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + flags.AddTxFlagsToCmd(cmd) + return cmd +} + +func NewCmdSendAs() *cobra.Command { + cmd := &cobra.Command{ + Use: "exec [msg_tx_json] --from [grantee]", + Short: "execute tx on behalf of granter account", + Long: "execute tx on behalf of granter account", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } + grantee := clientCtx.GetFromAddress() + + if offline, _ := cmd.Flags().GetBool(flags.FlagOffline); offline { + return errors.New("cannot broadcast tx during offline mode") + } + + stdTx, err := authclient.ReadTxFromFile(clientCtx, args[0]) + if err != nil { + return err + } + msg := types.NewMsgExecAuthorized(grantee, stdTx.GetMsgs()) + + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/msg_authorization/client/rest/grpc_query_test.go b/x/msg_authorization/client/rest/grpc_query_test.go new file mode 100644 index 000000000000..87ad45940741 --- /dev/null +++ b/x/msg_authorization/client/rest/grpc_query_test.go @@ -0,0 +1,136 @@ +// +build norace + +package rest_test + +import ( + "fmt" + "testing" + + "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" + banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/suite" + + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/testutil/network" + "github.com/cosmos/cosmos-sdk/types/rest" + msgauthtestutil "github.com/cosmos/cosmos-sdk/x/msg_authorization/client/testutil" + types "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +type IntegrationTestSuite struct { + suite.Suite + cfg network.Config + network *network.Network + grantee sdk.AccAddress +} + +var typeMsgSend = types.SendAuthorization{}.MethodName() + +func (s *IntegrationTestSuite) SetupSuite() { + s.T().Log("setting up integration test suite") + + cfg := network.DefaultConfig() + + cfg.NumValidators = 1 + s.cfg = cfg + s.network = network.New(s.T(), cfg) + + val := s.network.Validators[0] + // Create new account in the keyring. + info, _, err := val.ClientCtx.Keyring.NewMnemonic("grantee", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) + s.Require().NoError(err) + newAddr := sdk.AccAddress(info.GetPubKey().Address()) + + // Send some funds to the new account. + _, err = banktestutil.MsgSendExec( + val.ClientCtx, + val.Address, + newAddr, + sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(200))), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + 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) + + // grant authorization + _, err = msgauthtestutil.MsgGrantAuthorizationExec(val.ClientCtx, val.Address.String(), newAddr.String(), typeMsgSend, "100stake") + s.Require().NoError(err) + + s.grantee = newAddr + _, err = s.network.WaitForHeight(1) + s.Require().NoError(err) +} + +func (s *IntegrationTestSuite) TearDownSuite() { + s.T().Log("tearing down integration test suite") + s.network.Cleanup() +} + +func (s *IntegrationTestSuite) TestQueryGRPC() { + val := s.network.Validators[0] + baseURL := val.APIAddress + testCases := []struct { + name string + url string + expectErr bool + respType proto.Message + expected proto.Message + }{ + { + "fail invalid granter address", + fmt.Sprintf("%s/cosmos/msgauth/v1beta1/granters/%s/grantees/%s/%s", baseURL, "abcd", "efgh", "aleem"), + true, + &types.QueryAuthorizationResponse{}, + &types.QueryAuthorizationResponse{ + Authorization: nil, + }, + }, + { + "fail invalid grantee address", + fmt.Sprintf("%s/cosmos/msgauth/v1beta1/granters/%s/grantees/%s/%s", baseURL, val.Address.String(), "efgh", typeMsgSend), + true, + &types.QueryAuthorizationResponse{}, + &types.QueryAuthorizationResponse{ + Authorization: nil, + }, + }, + { + "fail invalid msgtype", + fmt.Sprintf("%s/cosmos/msgauth/v1beta1/granters/%s/grantees/%s/%s", baseURL, val.Address.String(), s.grantee.String(), "invalidMsg"), + true, + &types.QueryAuthorizationResponse{}, + &types.QueryAuthorizationResponse{ + Authorization: nil, + }, + }, + { + "fail invalid msgtype", + fmt.Sprintf("%s/cosmos/msgauth/v1beta1/granters/%s/grantees/%s/%s", baseURL, val.Address.String(), s.grantee.String(), typeMsgSend), + false, + &types.QueryAuthorizationResponse{}, + &types.QueryAuthorizationResponse{ + Authorization: nil, + }, + }, + } + for _, tc := range testCases { + tc := tc + s.Run(tc.name, func() { + resp, err := rest.GetRequest(tc.url) + err = val.ClientCtx.JSONMarshaler.UnmarshalJSON(resp, tc.respType) + + if tc.expectErr { + s.Require().Error(err) + } else { + s.Require().NoError(err) + } + }) + } +} + +func TestIntegrationTestSuite(t *testing.T) { + suite.Run(t, new(IntegrationTestSuite)) +} diff --git a/x/msg_authorization/client/rest/query.go b/x/msg_authorization/client/rest/query.go new file mode 100644 index 000000000000..6f115d36d2db --- /dev/null +++ b/x/msg_authorization/client/rest/query.go @@ -0,0 +1,11 @@ +package rest + +// import ( +// "github.com/cosmos/cosmos-sdk/client/context" +// "github.com/gorilla/mux" +// ) + +// func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { + +// registerTxRoutes(cliCtx, r) +// } diff --git a/x/msg_authorization/client/rest/tx.go b/x/msg_authorization/client/rest/tx.go new file mode 100644 index 000000000000..24b8aba131c9 --- /dev/null +++ b/x/msg_authorization/client/rest/tx.go @@ -0,0 +1,80 @@ +package rest + +// import ( +// "net/http" +// "time" + +// "github.com/gorilla/mux" + +// "github.com/cosmos/cosmos-sdk/client/context" +// sdk "github.com/cosmos/cosmos-sdk/types" +// "github.com/cosmos/cosmos-sdk/types/rest" +// authclient "github.com/cosmos/cosmos-sdk/x/auth/client" +// "github.com/cosmos/cosmos-sdk/x/msg_authorization/internal/types" +// ) + +// func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { +// r.HandleFunc("/msg_authorization/grant", grantHandler(cliCtx)).Methods("POST") +// r.HandleFunc("/msg_authorization/revoke", revokeHandler(cliCtx)).Methods("POST") +// } + +// type GrantRequest struct { +// BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` +// Granter sdk.AccAddress `json:"granter"` +// Grantee sdk.AccAddress `json:"grantee"` +// Authorization types.Authorization `json:"authorization"` +// Expiration time.Time `json:"expiration"` +// } + +// type RevokeRequest struct { +// BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` +// Granter sdk.AccAddress `json:"granter"` +// Grantee sdk.AccAddress `json:"grantee"` +// AuthorizationMsgType string `json:"authorization_msg_type"` +// } + +// func grantHandler(cliCtx context.CLIContext) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { +// var req GrantRequest + +// if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { +// return +// } + +// req.BaseReq = req.BaseReq.Sanitize() +// if !req.BaseReq.ValidateBasic(w) { +// return +// } + +// msg := types.NewMsgGrantAuthorization(req.Granter, req.Grantee, req.Authorization, req.Expiration) +// if err := msg.ValidateBasic(); err != nil { +// rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) +// return +// } + +// authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) +// } +// } + +// func revokeHandler(cliCtx context.CLIContext) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { +// var req RevokeRequest + +// if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { +// return +// } + +// req.BaseReq = req.BaseReq.Sanitize() +// if !req.BaseReq.ValidateBasic(w) { +// return +// } + +// msg := types.NewMsgRevokeAuthorization(req.Granter, req.Grantee, req.AuthorizationMsgType) +// if err := msg.ValidateBasic(); err != nil { +// rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) +// return +// } + +// authclient.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) +// } +// } diff --git a/x/msg_authorization/client/testutil/test_helpers.go b/x/msg_authorization/client/testutil/test_helpers.go new file mode 100644 index 000000000000..571e7c868684 --- /dev/null +++ b/x/msg_authorization/client/testutil/test_helpers.go @@ -0,0 +1,36 @@ +package testutil + +import ( + "fmt" + "time" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/viper" + + msgauthcli "github.com/cosmos/cosmos-sdk/x/msg_authorization/client/cli" +) + +var commonArgs = []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()), +} + +func MsgGrantAuthorizationExec(clientCtx client.Context, granter, grantee, msgName, limit string, extraArgs ...string) (testutil.BufferWriter, error) { + args := []string{ + grantee, + msgName, + limit, + fmt.Sprintf("--%s=%s", flags.FlagFrom, granter), + } + + viper.Set(msgauthcli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()) + + args = append(args, commonArgs...) + return clitestutil.ExecTestCLICmd(clientCtx, msgauthcli.NewCmdGrantAuthorization(), args) + +} diff --git a/x/msg_authorization/exported/keeper.go b/x/msg_authorization/exported/keeper.go new file mode 100644 index 000000000000..b0a0067aec17 --- /dev/null +++ b/x/msg_authorization/exported/keeper.go @@ -0,0 +1,25 @@ +package exported + +import ( + "time" + + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type Keeper interface { + //DispatchActions executes the provided messages via authorization grants from the message signer to the grantee + DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, msgs []sdk.Msg) sdk.Result + + // 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. + Grant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, authorization types.Authorization, expiration time.Time) + + //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 sdk.Msg) + + //Returns any Authorization (or nil), with the expiration time, + // granted to the grantee by the granter for the provided msg type. + GetAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType sdk.Msg) (cap types.Authorization, expiration time.Time) +} diff --git a/x/msg_authorization/genesis.go b/x/msg_authorization/genesis.go new file mode 100644 index 000000000000..36a95df2d741 --- /dev/null +++ b/x/msg_authorization/genesis.go @@ -0,0 +1,46 @@ +package msg_authorization + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/keeper" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +// InitGenesis new msg_authorization genesis +func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, data *types.GenesisState) { + for _, entry := range data.Authorization { + grantee, err := sdk.AccAddressFromBech32(entry.Grantee) + if err != nil { + panic(err) + } + granter, err := sdk.AccAddressFromBech32(entry.Granter) + if err != nil { + panic(err) + } + authorization, ok := entry.Authorization.GetCachedValue().(types.Authorization) + if !ok { + panic("expected authorization") + } + + keeper.Grant(ctx, grantee, granter, authorization, entry.Expiration) + } +} + +// ExportGenesis returns a GenesisState for a given context and keeper. +func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { + var entries []types.MsgGrantAuthorization + keeper.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant types.AuthorizationGrant) bool { + exp := time.Unix(grant.Expiration, 0) + entries = append(entries, types.MsgGrantAuthorization{ + Granter: granter.String(), + Grantee: grantee.String(), + Expiration: exp, + Authorization: grant.Authorization, + }) + return false + }) + + return types.NewGenesisState(entries) +} diff --git a/x/msg_authorization/genesis_test.go b/x/msg_authorization/genesis_test.go new file mode 100644 index 000000000000..bd2477782c54 --- /dev/null +++ b/x/msg_authorization/genesis_test.go @@ -0,0 +1,58 @@ +package msg_authorization_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/suite" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + msgauth "github.com/cosmos/cosmos-sdk/x/msg_authorization" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/keeper" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +type GenesisTestSuite struct { + suite.Suite + + ctx sdk.Context + keeper keeper.Keeper +} + +func (suite *GenesisTestSuite) SetupTest() { + checkTx := false + app := simapp.Setup(checkTx) + + suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 1}) + suite.keeper = app.MsgAuthKeeper +} + +var ( + granteePub = secp256k1.GenPrivKey().PubKey() + granterPub = secp256k1.GenPrivKey().PubKey() + granteeAddr = sdk.AccAddress(granteePub.Address()) + granterAddr = sdk.AccAddress(granterPub.Address()) +) + +func (suite *GenesisTestSuite) TestImportExportGenesis() { + coins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1_000))) + + now := suite.ctx.BlockHeader().Time + grant := &types.SendAuthorization{SpendLimit: coins} + suite.keeper.Grant(suite.ctx, granteeAddr, granterAddr, grant, now.Add(time.Hour)) + genesis := msgauth.ExportGenesis(suite.ctx, suite.keeper) + + // Clear keeper + suite.keeper.Revoke(suite.ctx, granteeAddr, granterAddr, grant.MethodName()) + + msgauth.InitGenesis(suite.ctx, suite.keeper, genesis) + newGenesis := msgauth.ExportGenesis(suite.ctx, suite.keeper) + suite.Require().Equal(genesis, newGenesis) +} + +func TestGenesisTestSuite(t *testing.T) { + suite.Run(t, new(GenesisTestSuite)) +} diff --git a/x/msg_authorization/handler.go b/x/msg_authorization/handler.go new file mode 100644 index 000000000000..d4c715bb2c30 --- /dev/null +++ b/x/msg_authorization/handler.go @@ -0,0 +1,27 @@ +package msg_authorization + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +//NewHandler returns a handler for msg_authorization messages. +func NewHandler(k types.MsgServer) sdk.Handler { + return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { + ctx = ctx.WithEventManager(sdk.NewEventManager()) + switch msg := msg.(type) { + case *types.MsgGrantAuthorization: + res, err := k.GrantAuthorization(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgRevokeAuthorization: + res, err := k.RevokeAuthorization(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgExecAuthorized: + res, err := k.ExecAuthorized(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + default: + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized authorization message type: %T", msg) + } + } +} diff --git a/x/msg_authorization/handler_test.go b/x/msg_authorization/handler_test.go new file mode 100644 index 000000000000..0219eb874304 --- /dev/null +++ b/x/msg_authorization/handler_test.go @@ -0,0 +1,26 @@ +package msg_authorization_test + +import ( + "strings" + "testing" + + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + + "github.com/cosmos/cosmos-sdk/testutil/testdata" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + msgauth "github.com/cosmos/cosmos-sdk/x/msg_authorization" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/keeper" +) + +func TestInvalidMsg(t *testing.T) { + k := keeper.Keeper{} + h := msgauth.NewHandler(k) + + res, err := h(sdk.NewContext(nil, tmproto.Header{}, false, nil), testdata.NewTestMsg()) + require.Error(t, err) + require.Nil(t, res) + require.True(t, strings.Contains(err.Error(), "unrecognized authorization message type")) +} diff --git a/x/msg_authorization/keeper/grpc_query.go b/x/msg_authorization/keeper/grpc_query.go new file mode 100644 index 000000000000..009e2fec64a9 --- /dev/null +++ b/x/msg_authorization/keeper/grpc_query.go @@ -0,0 +1,65 @@ +package keeper + +import ( + "context" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + proto "github.com/gogo/protobuf/proto" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +var _ types.QueryServer = Keeper{} + +// Authorization implements the Query/Authorization gRPC method +func (k Keeper) Authorization(c context.Context, req *types.QueryAuthorizationRequest) (*types.QueryAuthorizationResponse, error) { + if req == nil { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + if req.GranterAddr == "" { + return nil, status.Errorf(codes.InvalidArgument, "invalid granter addr") + } + + if req.GranteeAddr == "" { + return nil, status.Errorf(codes.InvalidArgument, "invalid grantee addr") + } + + if req.MsgType == "" { + return nil, status.Errorf(codes.InvalidArgument, "invalid msg-type") + } + + granterAddr, err := sdk.AccAddressFromBech32(req.GranterAddr) + + if err != nil { + return nil, err + } + granteeAddr, err := sdk.AccAddressFromBech32(req.GranteeAddr) + + if err != nil { + return nil, err + } + ctx := sdk.UnwrapSDKContext(c) + + authorization, _ := k.GetAuthorization(ctx, granteeAddr, granterAddr, req.MsgType) + if authorization == nil { + return nil, status.Errorf(codes.NotFound, "no authorization found for %s type", req.MsgType) + } + + msg, ok := authorization.(proto.Message) + if !ok { + return nil, status.Errorf(codes.Internal, "can't protomarshal %T", msg) + } + + authorizationAny, err := codectypes.NewAnyWithValue(msg) + if err != nil { + return nil, status.Errorf(codes.Internal, err.Error()) + } + + return &types.QueryAuthorizationResponse{Authorization: authorizationAny}, nil + +} diff --git a/x/msg_authorization/keeper/grpc_query_test.go b/x/msg_authorization/keeper/grpc_query_test.go new file mode 100644 index 000000000000..5f8d76670fd3 --- /dev/null +++ b/x/msg_authorization/keeper/grpc_query_test.go @@ -0,0 +1,88 @@ +package keeper_test + +import ( + gocontext "context" + "fmt" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +func (suite *TestSuite) TestGRPCQueryAuthorization() { + app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs + var ( + req *types.QueryAuthorizationRequest + expAuthorization types.Authorization + ) + testCases := []struct { + msg string + malleate func() + expPass bool + postTest func(res *types.QueryAuthorizationResponse) + }{ + { + "fail invalid granter addr", + func() { + req = &types.QueryAuthorizationRequest{} + }, + false, + func(res *types.QueryAuthorizationResponse) {}, + }, + { + "fail invalid grantee addr", + func() { + req = &types.QueryAuthorizationRequest{ + GranterAddr: addrs[0].String(), + } + }, + false, + func(res *types.QueryAuthorizationResponse) {}, + }, + { + "fail invalid msg-type", + func() { + req = &types.QueryAuthorizationRequest{ + GranterAddr: addrs[0].String(), + GranteeAddr: addrs[1].String(), + } + }, + false, + func(res *types.QueryAuthorizationResponse) {}, + }, + { + "Succcess", + func() { + now := ctx.BlockHeader().Time + newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) + expAuthorization = &types.SendAuthorization{SpendLimit: newCoins} + app.MsgAuthKeeper.Grant(ctx, addrs[0], addrs[1], expAuthorization, now.Add(time.Hour)) + req = &types.QueryAuthorizationRequest{ + GranterAddr: addrs[1].String(), + GranteeAddr: addrs[0].String(), + MsgType: expAuthorization.MethodName(), + } + }, + true, + func(res *types.QueryAuthorizationResponse) { + var auth types.Authorization + err := suite.app.InterfaceRegistry().UnpackAny(res.Authorization, &auth) + suite.Require().NoError(err) + suite.Require().NotNil(auth) + suite.Require().Equal(auth.String(), expAuthorization.String()) + }, + }, + } + for _, testCase := range testCases { + suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { + testCase.malleate() + result, err := queryClient.Authorization(gocontext.Background(), req) + if testCase.expPass { + suite.Require().NoError(err) + } else { + suite.Require().Error(err) + } + testCase.postTest(result) + }) + } +} diff --git a/x/msg_authorization/keeper/keeper.go b/x/msg_authorization/keeper/keeper.go new file mode 100644 index 000000000000..5f358a2ce8bd --- /dev/null +++ b/x/msg_authorization/keeper/keeper.go @@ -0,0 +1,181 @@ +package keeper + +import ( + "bytes" + "fmt" + "time" + + proto "github.com/gogo/protobuf/proto" + + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + "github.com/tendermint/tendermint/libs/log" +) + +type Keeper struct { + storeKey sdk.StoreKey + cdc codec.BinaryMarshaler + router types.Router +} + +// NewKeeper constructs a message authorization Keeper +func NewKeeper(storeKey sdk.StoreKey, cdc codec.BinaryMarshaler, router types.Router) Keeper { + + // It is vital to seal the msg_authorization proposal router here as to not allow + // further handlers to be registered after the keeper is created since this + // could create invalid or non-deterministic behavior. + router.Seal() + + return Keeper{ + storeKey: storeKey, + cdc: cdc, + router: router, + } +} + +// Logger returns a module-specific logger. +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} + +// Router returns the msg_authorization Keeper's Router +func (k Keeper) Router() types.Router { + return k.router +} + +// getAuthorizationGrant returns grant between granter and grantee for the given msg type +func (k Keeper) getAuthorizationGrant(ctx sdk.Context, actor []byte) (grant types.AuthorizationGrant, found bool) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(actor) + if bz == nil { + return grant, false + } + k.cdc.MustUnmarshalBinaryBare(bz, &grant) + return grant, true +} + +func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, updated types.Authorization) { + actor := types.GetActorAuthorizationKey(grantee, granter, updated.MethodName()) + grant, found := k.getAuthorizationGrant(ctx, actor) + if !found { + return + } + + msg, ok := updated.(proto.Message) + if !ok { + panic(fmt.Errorf("cannot proto marshal %T", updated)) + } + + any, err := codectypes.NewAnyWithValue(msg) + if err != nil { + panic(err) + } + + grant.Authorization = any + store := ctx.KVStore(k.storeKey) + store.Set(actor, k.cdc.MustMarshalBinaryBare(&grant)) +} + +// DispatchActions attempts to execute the provided messages via authorization +// grants from the message signer to the grantee. +func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, msgs []sdk.Msg) (*sdk.Result, error) { + var msgResult *sdk.Result + var err error + for _, msg := range msgs { + signers := msg.GetSigners() + if len(signers) != 1 { + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "authorization can be given to msg with only one signer") + } + granter := signers[0] + if !bytes.Equal(granter, grantee) { + authorization, _ := k.GetAuthorization(ctx, grantee, granter, proto.MessageName(msg)) + if authorization == nil { + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "authorization not found") + } + allow, updated, del := authorization.Accept(msg, ctx.BlockHeader()) + if !allow { + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "authorization not found") + } + if del { + k.Revoke(ctx, grantee, granter, msg.Type()) + } else if updated != nil { + k.update(ctx, grantee, granter, updated) + } + } + handler := k.router.GetRoute(msg.Route()) + + if handler == nil { + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized message route: %s", msg.Route()) + } + + msgResult, err = handler(ctx, msg) + if err != nil { + return nil, sdkerrors.Wrapf(err, "failed to execute message; message %s", proto.MessageName(msg)) + } + } + + return msgResult, nil +} + +// 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 +// overwrites that. +func (k Keeper) Grant(ctx sdk.Context, grantee, granter sdk.AccAddress, authorization types.Authorization, expiration time.Time) { + store := ctx.KVStore(k.storeKey) + + grant, err := types.NewAuthorizationGrant(authorization, expiration.Unix()) + if err != nil { + panic(err) + } + + bz := k.cdc.MustMarshalBinaryBare(&grant) + actor := types.GetActorAuthorizationKey(grantee, granter, authorization.MethodName()) + store.Set(actor, bz) +} + +// Revoke method revokes any authorization for the provided message type granted to the grantee by the granter. +func (k Keeper) Revoke(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) error { + store := ctx.KVStore(k.storeKey) + actor := types.GetActorAuthorizationKey(grantee, granter, msgType) + _, found := k.getAuthorizationGrant(ctx, actor) + if !found { + return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "authorization not found") + } + store.Delete(actor) + + return nil +} + +// GetAuthorization Returns any `Authorization` (or `nil`), with the expiration time, +// granted to the grantee by the granter for the provided msg type. +func (k Keeper) GetAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) (cap types.Authorization, expiration int64) { + grant, found := k.getAuthorizationGrant(ctx, types.GetActorAuthorizationKey(grantee, granter, msgType)) + if !found { + return nil, 0 + } + if grant.Expiration != 0 && grant.Expiration < (ctx.BlockHeader().Time.Unix()) { + k.Revoke(ctx, grantee, granter, msgType) + return nil, 0 + } + + return grant.GetAuthorization(), grant.Expiration +} + +// IterateGrants iterates over all authorization grants +func (k Keeper) IterateGrants(ctx sdk.Context, + handler func(granterAddr sdk.AccAddress, granteeAddr sdk.AccAddress, grant types.AuthorizationGrant) bool) { + store := ctx.KVStore(k.storeKey) + iter := sdk.KVStorePrefixIterator(store, types.GrantKey) + defer iter.Close() + for ; iter.Valid(); iter.Next() { + var grant types.AuthorizationGrant + granterAddr, granteeAddr := types.ExtractAddressesFromGrantKey(iter.Key()) + k.cdc.MustUnmarshalBinaryBare(iter.Value(), &grant) + if handler(granterAddr, granteeAddr, grant) { + break + } + } +} diff --git a/x/msg_authorization/keeper/keeper_test.go b/x/msg_authorization/keeper/keeper_test.go new file mode 100644 index 000000000000..91f48822056d --- /dev/null +++ b/x/msg_authorization/keeper/keeper_test.go @@ -0,0 +1,204 @@ +package keeper_test + +import ( + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/baseapp" + proto "github.com/gogo/protobuf/proto" + + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + "github.com/stretchr/testify/suite" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmtime "github.com/tendermint/tendermint/types/time" +) + +type TestSuite struct { + suite.Suite + + app *simapp.SimApp + ctx sdk.Context + addrs []sdk.AccAddress + queryClient types.QueryClient +} + +func (s *TestSuite) SetupTest() { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + now := tmtime.Now() + ctx = ctx.WithBlockHeader(tmproto.Header{Time: now}) + queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry()) + types.RegisterQueryServer(queryHelper, app.MsgAuthKeeper) + queryClient := types.NewQueryClient(queryHelper) + s.queryClient = queryClient + + s.app = app + s.ctx = ctx + s.queryClient = queryClient + s.addrs = simapp.AddTestAddrsIncremental(app, ctx, 3, sdk.NewInt(30000000)) + +} + +func (s *TestSuite) TestKeeper() { + app, ctx, addrs := s.app, s.ctx, s.addrs + + granterAddr := addrs[0] + granteeAddr := addrs[1] + recipientAddr := addrs[2] + err := app.BankKeeper.SetBalances(ctx, granterAddr, sdk.NewCoins(sdk.NewInt64Coin("steak", 10000))) + s.Require().Nil(err) + s.Require().True(app.BankKeeper.GetBalance(ctx, granterAddr, "steak").IsEqual(sdk.NewCoin("steak", sdk.NewInt(10000)))) + + s.T().Log("verify that no authorization returns nil") + authorization, expiration := app.MsgAuthKeeper.GetAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().Nil(authorization) + s.Require().Zero(expiration) + now := s.ctx.BlockHeader().Time + s.Require().NotNil(now) + + newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) + s.T().Log("verify if expired authorization is rejected") + x := &types.SendAuthorization{SpendLimit: newCoins} + app.MsgAuthKeeper.Grant(ctx, granterAddr, granteeAddr, x, now.Add(-1*time.Hour)) + authorization, _ = app.MsgAuthKeeper.GetAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().Nil(authorization) + + s.T().Log("verify if authorization is accepted") + x = &types.SendAuthorization{SpendLimit: newCoins} + app.MsgAuthKeeper.Grant(ctx, granteeAddr, granterAddr, x, now.Add(time.Hour)) + authorization, _ = app.MsgAuthKeeper.GetAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().NotNil(authorization) + s.Require().Equal(authorization.MethodName(), proto.MessageName(&banktypes.MsgSend{})) + + s.T().Log("verify fetching authorization with wrong msg type fails") + authorization, _ = app.MsgAuthKeeper.GetAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgMultiSend{})) + s.Require().Nil(authorization) + + s.T().Log("verify fetching authorization with wrong grantee fails") + authorization, _ = app.MsgAuthKeeper.GetAuthorization(ctx, recipientAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().Nil(authorization) + + s.T().Log("verify revoke fails with wrong information") + err = app.MsgAuthKeeper.Revoke(ctx, recipientAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().Error(err) + authorization, _ = app.MsgAuthKeeper.GetAuthorization(ctx, recipientAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().Nil(authorization) + + s.T().Log("verify revoke executes with correct information") + err = app.MsgAuthKeeper.Revoke(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().NoError(err) + authorization, _ = app.MsgAuthKeeper.GetAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().Nil(authorization) + +} + +func (s *TestSuite) TestKeeperIter() { + app, ctx, addrs := s.app, s.ctx, s.addrs + + granterAddr := addrs[0] + granteeAddr := addrs[1] + + err := app.BankKeeper.SetBalances(ctx, granterAddr, sdk.NewCoins(sdk.NewInt64Coin("steak", 10000))) + s.Require().Nil(err) + s.Require().True(app.BankKeeper.GetBalance(ctx, granterAddr, "steak").IsEqual(sdk.NewCoin("steak", sdk.NewInt(10000)))) + + s.T().Log("verify that no authorization returns nil") + authorization, expiration := app.MsgAuthKeeper.GetAuthorization(ctx, granteeAddr, granterAddr, "Abcd") + s.Require().Nil(authorization) + s.Require().Zero(expiration) + now := s.ctx.BlockHeader().Time + s.Require().NotNil(now) + + newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) + s.T().Log("verify if expired authorization is rejected") + x := &types.SendAuthorization{SpendLimit: newCoins} + app.MsgAuthKeeper.Grant(ctx, granteeAddr, granterAddr, x, now.Add(-1*time.Hour)) + authorization, _ = app.MsgAuthKeeper.GetAuthorization(ctx, granteeAddr, granterAddr, "abcd") + s.Require().Nil(authorization) + + app.MsgAuthKeeper.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant types.AuthorizationGrant) bool { + s.Require().Equal(granter, granterAddr) + s.Require().Equal(grantee, granteeAddr) + return true + }) + +} + +func (s *TestSuite) TestKeeperFees() { + app, addrs := s.app, s.addrs + + granterAddr := addrs[0] + granteeAddr := addrs[1] + recipientAddr := addrs[2] + err := app.BankKeeper.SetBalances(s.ctx, granterAddr, sdk.NewCoins(sdk.NewInt64Coin("steak", 10000))) + s.Require().Nil(err) + s.Require().True(app.BankKeeper.GetBalance(s.ctx, granterAddr, "steak").IsEqual(sdk.NewCoin("steak", sdk.NewInt(10000)))) + + now := s.ctx.BlockHeader().Time + s.Require().NotNil(now) + + smallCoin := sdk.NewCoins(sdk.NewInt64Coin("steak", 20)) + someCoin := sdk.NewCoins(sdk.NewInt64Coin("steak", 123)) + + msgs := types.NewMsgExecAuthorized(granteeAddr, []sdk.Msg{ + &banktypes.MsgSend{ + Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)), + FromAddress: granterAddr.String(), + ToAddress: recipientAddr.String(), + }, + }) + + s.T().Log("verify dispatch fails with invalid authorization") + executeMsgs, err := msgs.GetMsgs() + s.Require().NoError(err) + result, err := app.MsgAuthKeeper.DispatchActions(s.ctx, granteeAddr, executeMsgs) + + s.Require().Nil(result) + s.Require().NotNil(err) + + s.T().Log("verify dispatch executes with correct information") + // grant authorization + app.MsgAuthKeeper.Grant(s.ctx, granteeAddr, granterAddr, &types.SendAuthorization{SpendLimit: smallCoin}, now) + authorization, expiration := app.MsgAuthKeeper.GetAuthorization(s.ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().NotNil(authorization) + s.Require().NotZero(expiration) + s.Require().Equal(authorization.MethodName(), proto.MessageName(&banktypes.MsgSend{})) + + executeMsgs, err = msgs.GetMsgs() + s.Require().NoError(err) + + result, err = app.MsgAuthKeeper.DispatchActions(s.ctx, granteeAddr, executeMsgs) + s.Require().NotNil(result) + s.Require().Nil(err) + + authorization, _ = app.MsgAuthKeeper.GetAuthorization(s.ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().NotNil(authorization) + + s.T().Log("verify dispatch fails with overlimit") + // grant authorization + + msgs = types.NewMsgExecAuthorized(granteeAddr, []sdk.Msg{ + &banktypes.MsgSend{ + Amount: someCoin, + FromAddress: granterAddr.String(), + ToAddress: recipientAddr.String(), + }, + }) + + executeMsgs, err = msgs.GetMsgs() + s.Require().NoError(err) + + result, err = app.MsgAuthKeeper.DispatchActions(s.ctx, granteeAddr, executeMsgs) + s.Require().Nil(result) + s.Require().NotNil(err) + + authorization, _ = app.MsgAuthKeeper.GetAuthorization(s.ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgSend{})) + s.Require().NotNil(authorization) +} + +func TestTestSuite(t *testing.T) { + suite.Run(t, new(TestSuite)) +} diff --git a/x/msg_authorization/keeper/msg_server.go b/x/msg_authorization/keeper/msg_server.go new file mode 100644 index 000000000000..65f670cec3e3 --- /dev/null +++ b/x/msg_authorization/keeper/msg_server.go @@ -0,0 +1,84 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +var _ types.MsgServer = Keeper{} + +// GrantAuthorization implements the MsgServer.GrantAuthorization method. +func (k Keeper) GrantAuthorization(goCtx context.Context, msg *types.MsgGrantAuthorization) (*types.MsgGrantAuthorizationResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) + if err != nil { + return nil, err + } + granter, err := sdk.AccAddressFromBech32(msg.Granter) + if err != nil { + return nil, err + } + authorization := msg.GetAuthorization() + k.Grant(ctx, grantee, granter, authorization, msg.Expiration) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventGrantAuthorization, + sdk.NewAttribute(types.AttributeKeyGrantType, authorization.MethodName()), + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(types.AttributeKeyGranterAddress, msg.Granter), + sdk.NewAttribute(types.AttributeKeyGranteeAddress, msg.Grantee), + ), + ) + + return &types.MsgGrantAuthorizationResponse{}, nil +} + +// RevokeAuthorization implements the MsgServer.RevokeAuthorization method. +func (k Keeper) RevokeAuthorization(goCtx context.Context, msg *types.MsgRevokeAuthorization) (*types.MsgRevokeAuthorizationResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) + if err != nil { + return nil, err + } + granter, err := sdk.AccAddressFromBech32(msg.Granter) + if err != nil { + return nil, err + } + + err = k.Revoke(ctx, grantee, granter, msg.AuthorizationMsgType) + if err != nil { + return nil, err + } + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventRevokeAuthorization, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(types.AttributeKeyGrantType, msg.AuthorizationMsgType), + sdk.NewAttribute(types.AttributeKeyGranterAddress, msg.Granter), + sdk.NewAttribute(types.AttributeKeyGranteeAddress, msg.Grantee), + ), + ) + + return &types.MsgRevokeAuthorizationResponse{}, nil +} + +// ExecAuthorized implements the MsgServer.ExecAuthorized method. +func (k Keeper) ExecAuthorized(goCtx context.Context, msg *types.MsgExecAuthorized) (*types.MsgExecAuthorizedResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) + if err != nil { + return nil, err + } + msgs, err := msg.GetMsgs() + if err != nil { + return nil, err + } + result, err := k.DispatchActions(ctx, grantee, msgs) + if err != nil { + return nil, err + } + return &types.MsgExecAuthorizedResponse{Result: result}, nil +} diff --git a/x/msg_authorization/keeper/querier.go b/x/msg_authorization/keeper/querier.go new file mode 100644 index 000000000000..f457318011ef --- /dev/null +++ b/x/msg_authorization/keeper/querier.go @@ -0,0 +1,50 @@ +package keeper + +import ( + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +// NewQuerier returns a new sdk.Keeper instance. +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { + switch path[0] { + case types.QueryAuthorization: + return queryAuthorization(ctx, req, k, legacyQuerierCdc) + + default: + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint: %s", types.ModuleName, path[0]) + } + } +} + +func queryAuthorization(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { + var params types.QueryAuthorizationRequest + + if err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) + } + + granter, err := sdk.AccAddressFromBech32(params.GranterAddr) + if err != nil { + return nil, err + } + + grantee, err := sdk.AccAddressFromBech32(params.GranteeAddr) + if err != nil { + return nil, err + } + + balance, _ := k.GetAuthorization(ctx, granter, grantee, params.MsgType) + + bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, balance) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + + return bz, nil +} diff --git a/x/msg_authorization/module.go b/x/msg_authorization/module.go new file mode 100644 index 000000000000..3a837e47dab6 --- /dev/null +++ b/x/msg_authorization/module.go @@ -0,0 +1,199 @@ +package msg_authorization + +import ( + "context" + "encoding/json" + "fmt" + "math/rand" + + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + + "github.com/cosmos/cosmos-sdk/x/msg_authorization/client/cli" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/simulation" + "github.com/gogo/protobuf/grpc" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + sdkclient "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/keeper" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} +) + +// AppModuleBasic defines the basic application module used by the msg_authorization module. +type AppModuleBasic struct { + cdc codec.Marshaler +} + +// Name returns the msg_authorization module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterQueryService registers a gRPC query service to respond to the +// module-specific gRPC queries. +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +// RegisterLegacyAminoCodec registers the msg_authorization module's types for the given codec. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// RegisterInterfaces registers the msg_authorization module's interface types +func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + +// DefaultGenesis returns default genesis state as raw bytes for the msg_authorization +// module. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} + +// ValidateGenesis performs genesis state validation for the msg_authorization module. +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(data) +} + +// RegisterRESTRoutes registers the REST routes for the msg_authorization module. +func (AppModuleBasic) RegisterRESTRoutes(clientCtx sdkclient.Context, r *mux.Router) { + // rest.RegisterRoutes(clientCtx, r) +} + +// RegisterGRPCRoutes registers the gRPC Gateway routes for the msg_authorization module. +func (AppModuleBasic) RegisterGRPCRoutes(clientCtx sdkclient.Context, mux *runtime.ServeMux) { + types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) +} + +//GetQueryCmd returns the cli query commands for the msg_authorization module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// GetTxCmd returns the transaction commands for the msg_authorization module +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// AppModule implements the sdk.AppModule interface +type AppModule struct { + AppModuleBasic + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Marshaler, keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{cdc: cdc}, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + } +} + +// Name returns the msg_authorization module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterInvariants does nothing, there are no invariants to enforce +func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// Route returns the message routing key for the staking module. +func (am AppModule) Route() sdk.Route { + return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper)) +} + +func (am AppModule) NewHandler() sdk.Handler { + return NewHandler(am.keeper) +} + +// QuerierRoute returns the route we respond to for abci queries +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// LegacyQuerierHandler returns the msg_authorization module sdk.Querier. +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return keeper.NewQuerier(am.keeper, legacyQuerierCdc) +} + +// RegisterQueryService registers a GRPC query service to respond to the +// module-specific GRPC queries. +func (am AppModule) RegisterQueryService(server grpc.Server) { + types.RegisterQueryServer(server, am.keeper) +} + +// InitGenesis performs genesis initialization for the msg_authorization module. It returns +// no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + cdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, am.keeper, &genesisState) + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the exported genesis state as raw bytes for the msg_authorization +// module. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { + gs := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(gs) +} + +func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { + +} + +// EndBlock does nothing +func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// GenerateGenesisState creates a randomized GenState of the msg_authorization module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) {} + +// ProposalContents returns all the evidence content functions used to +// simulate governance proposals. +func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { + return nil +} + +// RandomizedParams creates randomized msg_authorization param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { + return nil +} + +// RegisterStoreDecoder registers a decoder for evidence module's types +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[types.StoreKey] = simulation.NewDecodeStore(am.cdc) +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { + return simulation.WeightedOperations( + simState.AppParams, simState.Cdc, + am.accountKeeper, am.bankKeeper, am.keeper, + ) +} diff --git a/x/msg_authorization/simulation/decoder.go b/x/msg_authorization/simulation/decoder.go new file mode 100644 index 000000000000..eec218ba59a1 --- /dev/null +++ b/x/msg_authorization/simulation/decoder.go @@ -0,0 +1,27 @@ +package simulation + +import ( + "bytes" + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types/kv" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +// NewDecodeStore returns a decoder function closure that umarshals the KVPair's +// Value to the corresponding msg_authorization type. +func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB kv.Pair) string { + return func(kvA, kvB kv.Pair) string { + switch { + case bytes.Equal(kvA.Key[:1], types.GrantKey): + var grantA, grantB types.AuthorizationGrant + cdc.MustUnmarshalBinaryBare(kvA.Value, &grantA) + cdc.MustUnmarshalBinaryBare(kvB.Value, &grantB) + fmt.Println(grantA) + return fmt.Sprintf("%v\n%v", grantA, grantB) + default: + panic(fmt.Sprintf("invalid msg_authorization key %X", kvA.Key)) + } + } +} diff --git a/x/msg_authorization/simulation/decoder_test.go b/x/msg_authorization/simulation/decoder_test.go new file mode 100644 index 000000000000..a222db381a5b --- /dev/null +++ b/x/msg_authorization/simulation/decoder_test.go @@ -0,0 +1,50 @@ +package simulation_test + +import ( + "fmt" + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/types/kv" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/simulation" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" +) + +func TestDecodeStore(t *testing.T) { + cdc, _ := simapp.MakeCodecs() + dec := simulation.NewDecodeStore(cdc) + + grant, _ := types.NewAuthorizationGrant(types.NewSendAuthorization(sdk.NewCoins(sdk.NewInt64Coin("foo", 123))), time.Now().Unix()) + grantBz, err := cdc.MarshalBinaryBare(&grant) + require.NoError(t, err) + kvPairs := kv.Pairs{ + Pairs: []kv.Pair{ + {Key: []byte(types.GrantKey), Value: grantBz}, + {Key: []byte{0x99}, Value: []byte{0x99}}, + }, + } + + tests := []struct { + name string + expectedLog string + }{ + {"Grant", fmt.Sprintf("%v\n%v", grant, grant)}, + {"other", ""}, + } + + for i, tt := range tests { + i, tt := i, tt + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, dec(kvPairs.Pairs[i], kvPairs.Pairs[i]), tt.name) + } + }) + } +} diff --git a/x/msg_authorization/simulation/operations.go b/x/msg_authorization/simulation/operations.go new file mode 100644 index 000000000000..ba4359bbb6e5 --- /dev/null +++ b/x/msg_authorization/simulation/operations.go @@ -0,0 +1,259 @@ +package simulation + +import ( + "math/rand" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp/helpers" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + banktype "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/keeper" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// Simulation operation weights constants +const ( + OpWeightMsgGrantAuthorization = "op_weight_msg_grant_authorization" + OpWeightRevokeAuthorization = "op_weight_msg_revoke_authorization" + OpWeightExecAuthorized = "op_weight_msg_execute_authorized" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations( + appParams simtypes.AppParams, cdc codec.JSONMarshaler, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, +) simulation.WeightedOperations { + + var ( + weightMsgGrantAuthorization int + weightRevokeAuthorization int + weightExecAuthorized int + ) + + appParams.GetOrGenerate(cdc, OpWeightMsgGrantAuthorization, &weightMsgGrantAuthorization, nil, + func(_ *rand.Rand) { + weightMsgGrantAuthorization = simappparams.DefaultWeightMsgDelegate + }, + ) + + appParams.GetOrGenerate(cdc, OpWeightRevokeAuthorization, &weightRevokeAuthorization, nil, + func(_ *rand.Rand) { + weightRevokeAuthorization = simappparams.DefaultWeightMsgUndelegate + }, + ) + + appParams.GetOrGenerate(cdc, OpWeightExecAuthorized, &weightExecAuthorized, nil, + func(_ *rand.Rand) { + weightExecAuthorized = simappparams.DefaultWeightMsgSend + }, + ) + + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsgGrantAuthorization, + SimulateMsgGrantAuthorization(ak, bk, k), + ), + simulation.NewWeightedOperation( + weightRevokeAuthorization, + SimulateMsgRevokeAuthorization(ak, bk, k), + ), + simulation.NewWeightedOperation( + weightExecAuthorized, + SimulateMsgExecuteAuthorized(ak, bk, k), + ), + } +} + +// SimulateMsgGrantAuthorization generates a MsgGrantAuthorization with random values. +// nolint: funlen +func SimulateMsgGrantAuthorization(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + + granter, _ := simtypes.RandomAcc(r, accs) + grantee, _ := simtypes.RandomAcc(r, accs) + + account := ak.GetAccount(ctx, granter.Address) + + spendableCoins := bk.SpendableCoins(ctx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, ctx, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgGrantAuthorization, err.Error()), nil, err + } + + msg, err := types.NewMsgGrantAuthorization(granter.Address, grantee.Address, + types.NewSendAuthorization(spendableCoins.Sub(fees)), ctx.BlockTime().Add(30*time.Hour)) + + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgGrantAuthorization, err.Error()), nil, err + } + txGen := simappparams.MakeEncodingConfig().TxConfig + tx, err := helpers.GenTx( + txGen, + []sdk.Msg{msg}, + fees, + helpers.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + granter.PrivKey, + ) + + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgGrantAuthorization, "unable to generate mock tx"), nil, err + } + + _, _, err = app.Deliver(txGen.TxEncoder(), tx) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to deliver tx"), nil, err + } + return simtypes.NewOperationMsg(msg, true, ""), nil, err + } +} + +// SimulateMsgRevokeAuthorization generates a MsgRevokeAuthorization with random values. +// nolint: funlen +func SimulateMsgRevokeAuthorization(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + + hasGrant := false + var targetGrant types.AuthorizationGrant + var granterAddr sdk.AccAddress + var granteeAddr sdk.AccAddress + k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant types.AuthorizationGrant) bool { + targetGrant = grant + granterAddr = granter + granteeAddr = grantee + hasGrant = true + return true + }) + + if !hasGrant { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgRevokeAuthorization, "no grants"), nil, nil + } + + granter, ok := simtypes.FindAccount(accs, granterAddr) + if !ok { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgRevokeAuthorization, "Account not found"), nil, nil + } + account := ak.GetAccount(ctx, granter.Address) + + spendableCoins := bk.SpendableCoins(ctx, account.GetAddress()) + fees, err := simtypes.RandomFees(r, ctx, spendableCoins) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgRevokeAuthorization, "fee error"), nil, err + } + auth := targetGrant.GetAuthorization() + msg := types.NewMsgRevokeAuthorization(granterAddr, granteeAddr, auth.MethodName()) + + txGen := simappparams.MakeEncodingConfig().TxConfig + tx, err := helpers.GenTx( + txGen, + []sdk.Msg{&msg}, + fees, + helpers.DefaultGenTxGas, + chainID, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + granter.PrivKey, + ) + + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgRevokeAuthorization, err.Error()), nil, err + } + + _, _, err = app.Deliver(txGen.TxEncoder(), tx) + return simtypes.NewOperationMsg(&msg, true, ""), nil, err + } +} + +// SimulateMsgExecuteAuthorized generates a MsgExecuteAuthorized with random values. +// nolint: funlen +func SimulateMsgExecuteAuthorized(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { + return func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + + hasGrant := false + var targetGrant types.AuthorizationGrant + var granterAddr sdk.AccAddress + var granteeAddr sdk.AccAddress + k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant types.AuthorizationGrant) bool { + targetGrant = grant + granterAddr = granter + granteeAddr = grantee + hasGrant = true + return true + }) + + if !hasGrant { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, "Not found"), nil, nil + } + + grantee, _ := simtypes.FindAccount(accs, granteeAddr) + granterAccount := ak.GetAccount(ctx, granterAddr) + granteeAccount := ak.GetAccount(ctx, granteeAddr) + + granterspendableCoins := bk.SpendableCoins(ctx, granterAccount.GetAddress()) + if granterspendableCoins.Empty() { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, "no coins"), nil, nil + } + + if targetGrant.Expiration < ctx.BlockHeader().Time.Unix() { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, "grant expired"), nil, nil + } + + granteespendableCoins := bk.SpendableCoins(ctx, granteeAccount.GetAddress()) + fees, err := simtypes.RandomFees(r, ctx, granteespendableCoins) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, "fee error"), nil, err + } + sendCoins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(10))) + + execMsg := banktype.NewMsgSend( + granterAddr, + granteeAddr, + sendCoins, + ) + + msg := types.NewMsgExecAuthorized(grantee.Address, []sdk.Msg{execMsg}) + sendGrant := targetGrant.Authorization.GetCachedValue().(*types.SendAuthorization) + allow, _, _ := sendGrant.Accept(execMsg, ctx.BlockHeader()) + if !allow { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, "not allowed"), nil, nil + } + + txGen := simappparams.MakeEncodingConfig().TxConfig + tx, err := helpers.GenTx( + txGen, + []sdk.Msg{&msg}, + fees, + helpers.DefaultGenTxGas, + chainID, + []uint64{granteeAccount.GetAccountNumber()}, + []uint64{granteeAccount.GetSequence()}, + grantee.PrivKey, + ) + + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, err.Error()), nil, err + } + _, _, err = app.Deliver(txGen.TxEncoder(), tx) + if err != nil { + if strings.Contains(err.Error(), "insufficient fee") { + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, "insufficient fee"), nil, nil + } + return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgExecDelegated, err.Error()), nil, err + } + + return simtypes.NewOperationMsg(&msg, true, "success"), nil, nil + } +} diff --git a/x/msg_authorization/simulation/operations_test.go b/x/msg_authorization/simulation/operations_test.go new file mode 100644 index 000000000000..fc4de89e3f6d --- /dev/null +++ b/x/msg_authorization/simulation/operations_test.go @@ -0,0 +1,157 @@ +package simulation_test + +import ( + "math/rand" + "testing" + "time" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/simapp" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/simulation" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + "github.com/stretchr/testify/suite" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" +) + +type SimTestSuite struct { + suite.Suite + + ctx sdk.Context + app *simapp.SimApp +} + +func (suite *SimTestSuite) SetupTest() { + checkTx := false + app := simapp.Setup(checkTx) + suite.app = app + suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{}) +} + +func (suite *SimTestSuite) TestWeightedOperations() { + cdc := suite.app.AppCodec() + appParams := make(simtypes.AppParams) + + weightesOps := simulation.WeightedOperations(appParams, cdc, suite.app.AccountKeeper, + suite.app.BankKeeper, suite.app.MsgAuthKeeper, + ) + + // setup 3 accounts + s := rand.NewSource(1) + r := rand.New(s) + accs := suite.getTestingAccounts(r, 3) + + expected := []struct { + weight int + opMsgRoute string + opMsgName string + }{ + {simappparams.DefaultWeightMsgDelegate, types.ModuleName, types.TypeMsgGrantAuthorization}, + {simappparams.DefaultWeightMsgUndelegate, types.ModuleName, types.TypeMsgRevokeAuthorization}, + {simappparams.DefaultWeightMsgSend, types.ModuleName, types.TypeMsgExecDelegated}, + } + + for i, w := range weightesOps { + operationMsg, _, _ := w.Op()(r, suite.app.BaseApp, suite.ctx, accs, "") + // the following checks are very much dependent from the ordering of the output given + // by WeightedOperations. if the ordering in WeightedOperations changes some tests + // will fail + suite.Require().Equal(expected[i].weight, w.Weight(), "weight should be the same") + suite.Require().Equal(expected[i].opMsgRoute, operationMsg.Route, "route should be the same") + suite.Require().Equal(expected[i].opMsgName, operationMsg.Name, "operation Msg name should be the same") + } +} + +func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account { + accounts := simtypes.RandomAccounts(r, n) + + initAmt := sdk.TokensFromConsensusPower(200000) + initCoins := sdk.NewCoins(sdk.NewCoin("foo", initAmt)) + + // add coins to the accounts + for _, account := range accounts { + acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, account.Address) + suite.app.AccountKeeper.SetAccount(suite.ctx, acc) + err := suite.app.BankKeeper.SetBalances(suite.ctx, account.Address, initCoins) + suite.Require().NoError(err) + } + + return accounts +} + +func (suite *SimTestSuite) TestSimulateRevokeAuthorization() { + // setup 3 accounts + s := rand.NewSource(1) + r := rand.New(s) + accounts := suite.getTestingAccounts(r, 3) + + // begin a new block + suite.app.BeginBlock(abci.RequestBeginBlock{ + Header: tmproto.Header{ + Height: suite.app.LastBlockHeight() + 1, + AppHash: suite.app.LastCommitID().Hash, + }}) + + initAmt := sdk.TokensFromConsensusPower(200000) + initCoins := sdk.NewCoins(sdk.NewCoin("foo", initAmt)) + + granter := accounts[0] + grantee := accounts[1] + authorization := types.NewSendAuthorization(initCoins) + + suite.app.MsgAuthKeeper.Grant(suite.ctx, grantee.Address, granter.Address, authorization, time.Now().Add(30*time.Hour)) + + // execute operation + op := simulation.SimulateMsgRevokeAuthorization(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.MsgAuthKeeper) + operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") + suite.Require().NoError(err) + + var msg types.MsgRevokeAuthorization + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + + suite.Require().True(operationMsg.OK) + suite.Require().Equal(granter.Address.String(), msg.Granter) + suite.Require().Equal(grantee.Address.String(), msg.Grantee) + suite.Require().Equal(types.SendAuthorization{}.MethodName(), msg.AuthorizationMsgType) + suite.Require().Len(futureOperations, 0) + +} + +func (suite *SimTestSuite) TestSimulateExecAuthorization() { + // setup 3 accounts + s := rand.NewSource(1) + r := rand.New(s) + accounts := suite.getTestingAccounts(r, 3) + + // begin a new block + suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) + + initAmt := sdk.TokensFromConsensusPower(200000) + initCoins := sdk.NewCoins(sdk.NewCoin("foo", initAmt)) + + granter := accounts[0] + grantee := accounts[1] + authorization := types.NewSendAuthorization(initCoins) + + suite.app.MsgAuthKeeper.Grant(suite.ctx, grantee.Address, granter.Address, authorization, time.Now().Add(30*time.Hour)) + + // execute operation + op := simulation.SimulateMsgExecuteAuthorized(suite.app.AccountKeeper, suite.app.BankKeeper, suite.app.MsgAuthKeeper) + operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") + suite.Require().NoError(err) + + var msg types.MsgExecAuthorized + types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + + suite.Require().True(operationMsg.OK) + suite.Require().Equal(grantee.Address.String(), msg.Grantee) + suite.Require().Len(futureOperations, 0) + +} + +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} diff --git a/x/msg_authorization/types/authorizations.go b/x/msg_authorization/types/authorizations.go new file mode 100644 index 000000000000..7adec8fdd13d --- /dev/null +++ b/x/msg_authorization/types/authorizations.go @@ -0,0 +1,58 @@ +package types + +import ( + "fmt" + + types "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/gogo/protobuf/proto" + tmproto "github.com/tendermint/tendermint/proto/tendermint/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.Msg, block tmproto.Header) (allow bool, updated Authorization, delete bool) +} + +// NewAuthorizationGrant returns new AuthrizationGrant +func NewAuthorizationGrant(authorization Authorization, expiration int64) (AuthorizationGrant, error) { + auth := AuthorizationGrant{ + Expiration: expiration, + } + msg, ok := authorization.(proto.Message) + if !ok { + return AuthorizationGrant{}, fmt.Errorf("cannot proto marshal %T", authorization) + } + + any, err := types.NewAnyWithValue(msg) + if err != nil { + return AuthorizationGrant{}, err + } + + auth.Authorization = any + + return auth, nil +} + +var ( + _ types.UnpackInterfacesMessage = &AuthorizationGrant{} +) + +func (auth AuthorizationGrant) UnpackInterfaces(unpacker types.AnyUnpacker) error { + var authorization Authorization + return unpacker.UnpackAny(auth.Authorization, &authorization) +} + +func (auth AuthorizationGrant) GetAuthorization() Authorization { + authorization, ok := auth.Authorization.GetCachedValue().(Authorization) + if !ok { + return nil + } + return authorization +} diff --git a/x/msg_authorization/types/codec.go b/x/msg_authorization/types/codec.go new file mode 100644 index 000000000000..0df8701f8cdc --- /dev/null +++ b/x/msg_authorization/types/codec.go @@ -0,0 +1,56 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + types "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// RegisterLegacyAminoCodec registers concrete types and interfaces on the given codec. +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterInterface((*Authorization)(nil), nil) + cdc.RegisterConcrete(&MsgGrantAuthorization{}, "cosmos-sdk/MsgGrantAuthorization", nil) + cdc.RegisterConcrete(&MsgRevokeAuthorization{}, "cosmos-sdk/MsgRevokeAuthorization", nil) + cdc.RegisterConcrete(&MsgExecAuthorized{}, "cosmos-sdk/MsgExecAuthorized", nil) + cdc.RegisterConcrete(SendAuthorization{}, "cosmos-sdk/SendAuthorization", nil) + cdc.RegisterConcrete(GenericAuthorization{}, "cosmos-sdk/GenericAuthorization", nil) +} + +// RegisterInterfaces registers the interfaces types with the interface registry +func RegisterInterfaces(registry types.InterfaceRegistry) { + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgGrantAuthorization{}, + &MsgRevokeAuthorization{}, + &MsgExecAuthorized{}, + ) + + // registry.RegisterImplementations((*Authorization)(nil), + // &SendAuthorization{}, + // &GenericAuthorization{}, + // ) + + registry.RegisterInterface( + "cosmos.msg_authorization.v1beta1.Authorization", + (*Authorization)(nil), + &SendAuthorization{}, + &GenericAuthorization{}, + ) +} + +var ( + amino = codec.NewLegacyAmino() + + // ModuleCdc references the global x/msg_authorization module codec. Note, the codec should + // ONLY be used in certain instances of tests and for JSON encoding as Amino is + // still used for that purpose. + // + // The actual codec used for serialization should be provided to x/msg_authorization and + // defined at the application level. + ModuleCdc = codec.NewAminoCodec(amino) +) + +func init() { + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) +} diff --git a/x/msg_authorization/types/errors.go b/x/msg_authorization/types/errors.go new file mode 100644 index 000000000000..3c1b4f2009de --- /dev/null +++ b/x/msg_authorization/types/errors.go @@ -0,0 +1,12 @@ +package types + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// x/msg_authorization module sentinel errors +var ( + ErrInvalidGranter = sdkerrors.Register(ModuleName, 1, "invalid granter address") + ErrInvalidGrantee = sdkerrors.Register(ModuleName, 2, "invalid grantee address") + ErrInvalidExpirationTime = sdkerrors.Register(ModuleName, 3, "expiration time of authorization should be more than current time") +) diff --git a/x/msg_authorization/types/events.go b/x/msg_authorization/types/events.go new file mode 100644 index 000000000000..4e89919ec067 --- /dev/null +++ b/x/msg_authorization/types/events.go @@ -0,0 +1,14 @@ +package types + +// msg_authorization module events +const ( + EventGrantAuthorization = "grant-authorization" + EventRevokeAuthorization = "revoke-authorization" + EventExecuteAuthorization = "execute-authorization" + + AttributeKeyGrantType = "grant-type" + AttributeKeyGranteeAddress = "grantee" + AttributeKeyGranterAddress = "granter" + + AttributeValueCategory = ModuleName +) diff --git a/x/msg_authorization/types/expected_keepers.go b/x/msg_authorization/types/expected_keepers.go new file mode 100644 index 000000000000..ef7869dd2c7d --- /dev/null +++ b/x/msg_authorization/types/expected_keepers.go @@ -0,0 +1,16 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// AccountKeeper defines the expected account keeper (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI +} + +// BankKeeper defines the expected interface needed to retrieve account balances. +type BankKeeper interface { + SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins +} diff --git a/x/msg_authorization/types/generic_authorization.go b/x/msg_authorization/types/generic_authorization.go new file mode 100644 index 000000000000..72c743ade7c5 --- /dev/null +++ b/x/msg_authorization/types/generic_authorization.go @@ -0,0 +1,24 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" +) + +var ( + _ Authorization = &GenericAuthorization{} +) + +func NewGenericAuthorization(methodName string) *GenericAuthorization { + return &GenericAuthorization{ + MessageName: methodName, + } +} + +func (cap GenericAuthorization) MethodName() string { + return cap.MessageName +} + +func (cap GenericAuthorization) Accept(msg sdk.Msg, block tmproto.Header) (allow bool, updated Authorization, delete bool) { + return true, &cap, false +} diff --git a/x/msg_authorization/types/genesis.go b/x/msg_authorization/types/genesis.go new file mode 100644 index 000000000000..61af4ebd10d8 --- /dev/null +++ b/x/msg_authorization/types/genesis.go @@ -0,0 +1,35 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec/types" +) + +// NewGenesisState creates new GenesisState object +func NewGenesisState(entries []MsgGrantAuthorization) *GenesisState { + return &GenesisState{ + Authorization: entries, + } +} + +// ValidateGenesis check the given genesis state has no integrity issues +func ValidateGenesis(data GenesisState) error { + return nil +} + +// +func DefaultGenesisState() *GenesisState { + return &GenesisState{} +} + +var _ types.UnpackInterfacesMessage = GenesisState{} + +// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces +func (data GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { + for _, authorization := range data.Authorization { + err := authorization.UnpackInterfaces(unpacker) + if err != nil { + return err + } + } + return nil +} diff --git a/x/msg_authorization/types/genesis.pb.go b/x/msg_authorization/types/genesis.pb.go new file mode 100644 index 000000000000..e0a48e0c373d --- /dev/null +++ b/x/msg_authorization/types/genesis.pb.go @@ -0,0 +1,336 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/msg_authorization/v1beta1/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" + proto "github.com/gogo/protobuf/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 + +// GenesisState defines the msg_authorization module's genesis state. +type GenesisState struct { + Authorization []MsgGrantAuthorization `protobuf:"bytes,1,rep,name=authorization,proto3" json:"authorization"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_a25b8e20483fe49f, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.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 *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetAuthorization() []MsgGrantAuthorization { + if m != nil { + return m.Authorization + } + return nil +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "cosmos.msg_authorization.v1beta1.GenesisState") +} + +func init() { + proto.RegisterFile("cosmos/msg_authorization/v1beta1/genesis.proto", fileDescriptor_a25b8e20483fe49f) +} + +var fileDescriptor_a25b8e20483fe49f = []byte{ + // 218 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4b, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0xcf, 0x2d, 0x4e, 0x8f, 0x4f, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, 0xca, 0xac, 0x4a, + 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, + 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x80, 0xa8, 0xd7, 0xc3, + 0x50, 0xaf, 0x07, 0x55, 0x2f, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xac, 0x0f, 0x62, 0x41, + 0xf4, 0x49, 0x69, 0x12, 0xb4, 0xa7, 0xa4, 0x02, 0xa2, 0x54, 0xa9, 0x98, 0x8b, 0xc7, 0x1d, 0x62, + 0x67, 0x70, 0x49, 0x62, 0x49, 0xaa, 0x50, 0x32, 0x17, 0x2f, 0x8a, 0x0e, 0x09, 0x46, 0x05, 0x66, + 0x0d, 0x6e, 0x23, 0x73, 0x3d, 0x42, 0x4e, 0xd1, 0xf3, 0x2d, 0x4e, 0x77, 0x2f, 0x4a, 0xcc, 0x2b, + 0x71, 0x44, 0x96, 0x75, 0x62, 0x39, 0x71, 0x4f, 0x9e, 0x21, 0x08, 0xd5, 0x4c, 0xa7, 0x80, 0x13, + 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, + 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x32, 0x4b, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, + 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0x7a, 0x02, 0x42, 0xe9, 0x16, 0xa7, 0x64, 0xeb, 0x57, 0x60, + 0xf1, 0x51, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0xd8, 0x37, 0xc6, 0x80, 0x00, 0x00, 0x00, + 0xff, 0xff, 0xa6, 0xa9, 0x12, 0x7f, 0x62, 0x01, 0x00, 0x00, +} + +func (m *GenesisState) 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 *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Authorization) > 0 { + for iNdEx := len(m.Authorization) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Authorization[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Authorization) > 0 { + for _, e := range m.Authorization { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) 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 ErrIntOverflowGenesis + } + 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: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authorization", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authorization = append(m.Authorization, MsgGrantAuthorization{}) + if err := m.Authorization[len(m.Authorization)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/msg_authorization/types/keys.go b/x/msg_authorization/types/keys.go new file mode 100644 index 000000000000..2dce1d62a98c --- /dev/null +++ b/x/msg_authorization/types/keys.go @@ -0,0 +1,42 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + // ModuleName is the module name constant used in many places + ModuleName = "msgauth" + + // StoreKey is the store key string for msg_authorization + StoreKey = ModuleName + + // RouterKey is the message route for msg_authorization + RouterKey = ModuleName + + // QuerierRoute is the querier route for msg_authorization + QuerierRoute = ModuleName +) + +// Keys for msg_authorization store +// Items are stored with the following key: values +// +// - 0x01: Grant + +var ( + // Keys for store prefixes + GrantKey = []byte{0x01} // prefix for each key +) + +// GetActorAuthorizationKey - return authorization store key +func GetActorAuthorizationKey(grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) []byte { + return append(append(append(GrantKey, granter.Bytes()...), grantee.Bytes()...), []byte(msgType)...) + +} + +// extractAddressesFromGrantKey - split granter & grantee address from the authorization key +func ExtractAddressesFromGrantKey(key []byte) (granterAddr, granteeAddr sdk.AccAddress) { + granterAddr = sdk.AccAddress(key[1 : sdk.AddrLen+1]) + granteeAddr = sdk.AccAddress(key[sdk.AddrLen+1 : sdk.AddrLen*2+1]) + return granterAddr, granteeAddr +} diff --git a/x/msg_authorization/types/keys_test.go b/x/msg_authorization/types/keys_test.go new file mode 100644 index 000000000000..d406fdef18ba --- /dev/null +++ b/x/msg_authorization/types/keys_test.go @@ -0,0 +1,21 @@ +package types + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/require" +) + +var granter = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) +var grantee = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) +var msgType = banktypes.MsgSend{}.Type() + +func TestGrantkey(t *testing.T) { + actor := GetActorAuthorizationKey(grantee, granter, msgType) + granter1, grantee1 := ExtractAddressesFromGrantKey(actor) + require.Equal(t, granter, granter1) + require.Equal(t, grantee, grantee1) +} diff --git a/x/msg_authorization/types/msg_authorization.pb.go b/x/msg_authorization/types/msg_authorization.pb.go new file mode 100644 index 000000000000..50c82df12c15 --- /dev/null +++ b/x/msg_authorization/types/msg_authorization.pb.go @@ -0,0 +1,772 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/msg_authorization/v1beta1/msg_authorization.proto + +package types + +import ( + fmt "fmt" + types1 "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" + 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" yaml:"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_34394388a9210393, []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 + +// GenericAuthorization gives the grantee unrestricted permissions to execute +// the provide method on behalf of the granter's account. +type GenericAuthorization struct { + MessageName string `protobuf:"bytes,1,opt,name=method_name,json=methodName,proto3" json:"method_name,omitempty"` +} + +func (m *GenericAuthorization) Reset() { *m = GenericAuthorization{} } +func (m *GenericAuthorization) String() string { return proto.CompactTextString(m) } +func (*GenericAuthorization) ProtoMessage() {} +func (*GenericAuthorization) Descriptor() ([]byte, []int) { + return fileDescriptor_34394388a9210393, []int{1} +} +func (m *GenericAuthorization) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenericAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenericAuthorization.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 *GenericAuthorization) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenericAuthorization.Merge(m, src) +} +func (m *GenericAuthorization) XXX_Size() int { + return m.Size() +} +func (m *GenericAuthorization) XXX_DiscardUnknown() { + xxx_messageInfo_GenericAuthorization.DiscardUnknown(m) +} + +var xxx_messageInfo_GenericAuthorization proto.InternalMessageInfo + +// TODO +type AuthorizationGrant struct { + Authorization *types1.Any `protobuf:"bytes,1,opt,name=authorization,proto3" json:"authorization,omitempty"` + Expiration int64 `protobuf:"varint,2,opt,name=expiration,proto3" json:"expiration,omitempty"` +} + +func (m *AuthorizationGrant) Reset() { *m = AuthorizationGrant{} } +func (m *AuthorizationGrant) String() string { return proto.CompactTextString(m) } +func (*AuthorizationGrant) ProtoMessage() {} +func (*AuthorizationGrant) Descriptor() ([]byte, []int) { + return fileDescriptor_34394388a9210393, []int{2} +} +func (m *AuthorizationGrant) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AuthorizationGrant) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AuthorizationGrant.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 *AuthorizationGrant) XXX_Merge(src proto.Message) { + xxx_messageInfo_AuthorizationGrant.Merge(m, src) +} +func (m *AuthorizationGrant) XXX_Size() int { + return m.Size() +} +func (m *AuthorizationGrant) XXX_DiscardUnknown() { + xxx_messageInfo_AuthorizationGrant.DiscardUnknown(m) +} + +var xxx_messageInfo_AuthorizationGrant proto.InternalMessageInfo + +func init() { + proto.RegisterType((*SendAuthorization)(nil), "cosmos.msg_authorization.v1beta1.SendAuthorization") + proto.RegisterType((*GenericAuthorization)(nil), "cosmos.msg_authorization.v1beta1.GenericAuthorization") + proto.RegisterType((*AuthorizationGrant)(nil), "cosmos.msg_authorization.v1beta1.AuthorizationGrant") +} + +func init() { + proto.RegisterFile("cosmos/msg_authorization/v1beta1/msg_authorization.proto", fileDescriptor_34394388a9210393) +} + +var fileDescriptor_34394388a9210393 = []byte{ + // 417 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x31, 0x8f, 0xd3, 0x30, + 0x1c, 0xc5, 0x63, 0x0e, 0x21, 0xe1, 0xe8, 0x84, 0x2e, 0xea, 0x70, 0xbd, 0xc1, 0x89, 0x32, 0x65, + 0x39, 0x87, 0x3b, 0x24, 0x84, 0xba, 0x5d, 0x90, 0xb8, 0x85, 0x43, 0x28, 0x6c, 0x2c, 0x91, 0x93, + 0x98, 0xd4, 0xa2, 0xb6, 0xa3, 0xd8, 0x45, 0x17, 0x46, 0x26, 0xd8, 0xf8, 0x08, 0x37, 0xb3, 0xc2, + 0x87, 0xa8, 0x98, 0x2a, 0x26, 0xa6, 0x82, 0xd2, 0x85, 0x99, 0x4f, 0x80, 0x12, 0xa7, 0xa8, 0xa1, + 0xa8, 0x53, 0xec, 0xff, 0xcb, 0x7b, 0xff, 0x9f, 0x5e, 0x02, 0x1f, 0x65, 0x52, 0x71, 0xa9, 0x42, + 0xae, 0x8a, 0x84, 0xcc, 0xf5, 0x54, 0x56, 0xec, 0x2d, 0xd1, 0x4c, 0x8a, 0xf0, 0xcd, 0x59, 0x4a, + 0x35, 0x39, 0xdb, 0x55, 0x70, 0x59, 0x49, 0x2d, 0x1d, 0xcf, 0x38, 0xf1, 0xae, 0xde, 0x3b, 0x4f, + 0x50, 0x9f, 0x9d, 0x12, 0x45, 0xff, 0xc6, 0x65, 0x92, 0xf5, 0x09, 0x27, 0x63, 0xa3, 0x27, 0xdd, + 0x2d, 0xec, 0xe3, 0x8c, 0x34, 0x2a, 0x64, 0x21, 0xcd, 0xbc, 0x3d, 0x6d, 0x0c, 0x85, 0x94, 0xc5, + 0x8c, 0x86, 0xdd, 0x2d, 0x9d, 0xbf, 0x0a, 0x89, 0xa8, 0x8d, 0xe4, 0x7f, 0x06, 0xf0, 0xe8, 0x05, + 0x15, 0xf9, 0xc5, 0x36, 0x89, 0xf3, 0x0e, 0x40, 0x5b, 0x95, 0x54, 0xe4, 0xc9, 0x8c, 0x71, 0xa6, + 0x8f, 0x81, 0x77, 0x10, 0xd8, 0xe7, 0x63, 0xdc, 0xef, 0x6a, 0xc1, 0x36, 0xb4, 0xf8, 0xb1, 0x64, + 0x22, 0x7a, 0xb2, 0x58, 0xb9, 0xd6, 0xef, 0x95, 0xeb, 0xd4, 0x84, 0xcf, 0x26, 0xfe, 0x96, 0xd7, + 0xff, 0xf4, 0xc3, 0x0d, 0x0a, 0xa6, 0xa7, 0xf3, 0x14, 0x67, 0x92, 0xf7, 0xb8, 0xfd, 0xe3, 0x54, + 0xe5, 0xaf, 0x43, 0x5d, 0x97, 0x54, 0x75, 0x31, 0x2a, 0x86, 0x9d, 0xf3, 0x69, 0x6b, 0x9c, 0x8c, + 0xdf, 0xdf, 0xb8, 0xd6, 0xaf, 0x1b, 0x17, 0x7c, 0xfb, 0x72, 0x7a, 0x38, 0xe0, 0xf3, 0x33, 0x38, + 0xba, 0xa4, 0x82, 0x56, 0x2c, 0x1b, 0x72, 0xdf, 0x87, 0x36, 0xa7, 0x7a, 0x2a, 0xf3, 0x44, 0x10, + 0x4e, 0x8f, 0x81, 0x07, 0x82, 0xbb, 0xd1, 0xbd, 0x66, 0xe5, 0xda, 0x57, 0x54, 0x29, 0x52, 0xd0, + 0x67, 0x84, 0xd3, 0x18, 0x9a, 0x77, 0xda, 0xf3, 0xbe, 0x25, 0x1f, 0x00, 0x74, 0x06, 0x93, 0xcb, + 0x8a, 0x08, 0xed, 0x5c, 0xc1, 0xc3, 0xc1, 0x67, 0xeb, 0xb6, 0xd8, 0xe7, 0x23, 0x6c, 0x4a, 0xc6, + 0x9b, 0x92, 0xf1, 0x85, 0xa8, 0xa3, 0xa3, 0xaf, 0xff, 0xc6, 0xc6, 0x43, 0xb7, 0x83, 0x20, 0xa4, + 0xd7, 0x25, 0xab, 0x4c, 0xd6, 0x2d, 0x0f, 0x04, 0x07, 0xf1, 0xd6, 0x64, 0x72, 0xbb, 0x05, 0x8c, + 0x9e, 0x2f, 0x1a, 0x04, 0x96, 0x0d, 0x02, 0x3f, 0x1b, 0x04, 0x3e, 0xae, 0x91, 0xb5, 0x5c, 0x23, + 0xeb, 0xfb, 0x1a, 0x59, 0x2f, 0x1f, 0xee, 0xed, 0xf6, 0xfa, 0x3f, 0x3f, 0x68, 0xd7, 0x77, 0x7a, + 0xa7, 0xe3, 0x7c, 0xf0, 0x27, 0x00, 0x00, 0xff, 0xff, 0xa9, 0xf8, 0x49, 0xcf, 0xc9, 0x02, 0x00, + 0x00, +} + +func (this *SendAuthorization) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*SendAuthorization) + if !ok { + that2, ok := that.(SendAuthorization) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.SpendLimit) != len(that1.SpendLimit) { + return false + } + for i := range this.SpendLimit { + if !this.SpendLimit[i].Equal(&that1.SpendLimit[i]) { + return false + } + } + return true +} +func (this *GenericAuthorization) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*GenericAuthorization) + if !ok { + that2, ok := that.(GenericAuthorization) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.MessageName != that1.MessageName { + return false + } + return true +} +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 = encodeVarintMsgAuthorization(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *GenericAuthorization) 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 *GenericAuthorization) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenericAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.MessageName) > 0 { + i -= len(m.MessageName) + copy(dAtA[i:], m.MessageName) + i = encodeVarintMsgAuthorization(dAtA, i, uint64(len(m.MessageName))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *AuthorizationGrant) 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 *AuthorizationGrant) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AuthorizationGrant) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Expiration != 0 { + i = encodeVarintMsgAuthorization(dAtA, i, uint64(m.Expiration)) + i-- + dAtA[i] = 0x10 + } + if m.Authorization != nil { + { + size, err := m.Authorization.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMsgAuthorization(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintMsgAuthorization(dAtA []byte, offset int, v uint64) int { + offset -= sovMsgAuthorization(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 + sovMsgAuthorization(uint64(l)) + } + } + return n +} + +func (m *GenericAuthorization) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.MessageName) + if l > 0 { + n += 1 + l + sovMsgAuthorization(uint64(l)) + } + return n +} + +func (m *AuthorizationGrant) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Authorization != nil { + l = m.Authorization.Size() + n += 1 + l + sovMsgAuthorization(uint64(l)) + } + if m.Expiration != 0 { + n += 1 + sovMsgAuthorization(uint64(m.Expiration)) + } + return n +} + +func sovMsgAuthorization(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozMsgAuthorization(x uint64) (n int) { + return sovMsgAuthorization(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 ErrIntOverflowMsgAuthorization + } + 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 ErrIntOverflowMsgAuthorization + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMsgAuthorization + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMsgAuthorization + } + 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 := skipMsgAuthorization(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsgAuthorization + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsgAuthorization + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GenericAuthorization) 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 ErrIntOverflowMsgAuthorization + } + 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: GenericAuthorization: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenericAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MessageName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsgAuthorization + } + 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 ErrInvalidLengthMsgAuthorization + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthMsgAuthorization + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MessageName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipMsgAuthorization(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsgAuthorization + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsgAuthorization + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AuthorizationGrant) 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 ErrIntOverflowMsgAuthorization + } + 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: AuthorizationGrant: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AuthorizationGrant: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authorization", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsgAuthorization + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMsgAuthorization + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMsgAuthorization + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Authorization == nil { + m.Authorization = &types1.Any{} + } + if err := m.Authorization.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Expiration", wireType) + } + m.Expiration = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsgAuthorization + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Expiration |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipMsgAuthorization(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsgAuthorization + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsgAuthorization + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipMsgAuthorization(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, ErrIntOverflowMsgAuthorization + } + 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, ErrIntOverflowMsgAuthorization + } + 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, ErrIntOverflowMsgAuthorization + } + 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, ErrInvalidLengthMsgAuthorization + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupMsgAuthorization + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthMsgAuthorization + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthMsgAuthorization = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowMsgAuthorization = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupMsgAuthorization = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/msg_authorization/types/msgs.go b/x/msg_authorization/types/msgs.go new file mode 100644 index 000000000000..eadf9f112cb5 --- /dev/null +++ b/x/msg_authorization/types/msgs.go @@ -0,0 +1,243 @@ +package types + +import ( + "fmt" + "time" + + types "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/gogo/protobuf/proto" + "gopkg.in/yaml.v2" +) + +// msg_authorization message types +const ( + TypeMsgGrantAuthorization = "grant_authorization" + TypeMsgRevokeAuthorization = "revoke_authorization" + TypeMsgExecDelegated = "exec_delegated" +) + +var ( + _ sdk.Msg = &MsgGrantAuthorization{} + _ sdk.Msg = &MsgRevokeAuthorization{} + _ sdk.Msg = &MsgExecAuthorized{} + + _ types.UnpackInterfacesMessage = &MsgGrantAuthorization{} + _ types.UnpackInterfacesMessage = &MsgExecAuthorized{} +) + +// NewMsgGrantAuthorization creates a new MsgGrantAuthorization +//nolint:interfacer +func NewMsgGrantAuthorization(granter sdk.AccAddress, grantee sdk.AccAddress, authorization Authorization, expiration time.Time) (*MsgGrantAuthorization, error) { + m := &MsgGrantAuthorization{ + Granter: granter.String(), + Grantee: grantee.String(), + Expiration: expiration, + } + err := m.SetAuthorization(authorization) + if err != nil { + return nil, err + } + return m, nil +} + +// Route implements Msg +func (msg MsgGrantAuthorization) Route() string { return RouterKey } + +// Type implements Msg +func (msg MsgGrantAuthorization) Type() string { return TypeMsgGrantAuthorization } + +// GetSigners implements Msg +func (msg MsgGrantAuthorization) GetSigners() []sdk.AccAddress { + granter, err := sdk.AccAddressFromBech32(msg.Granter) + if err != nil { + panic(err) + } + return []sdk.AccAddress{granter} +} + +// GetSignBytes implements Msg +func (msg MsgGrantAuthorization) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(&msg) + return sdk.MustSortJSON(bz) +} + +// ValidateBasic implements Msg +func (msg MsgGrantAuthorization) ValidateBasic() error { + if msg.Granter == "" { + return sdkerrors.Wrap(ErrInvalidGranter, "missing granter address") + } + if msg.Grantee == "" { + return sdkerrors.Wrap(ErrInvalidGrantee, "missing grantee address") + } + if msg.Expiration.Unix() < time.Now().Unix() { + return sdkerrors.Wrap(ErrInvalidExpirationTime, "Time can't be in the past") + } + + return nil +} + +func (msg *MsgGrantAuthorization) GetAuthorization() Authorization { + authorization, ok := msg.Authorization.GetCachedValue().(Authorization) + if !ok { + return nil + } + return authorization +} + +func (msg *MsgGrantAuthorization) SetAuthorization(authorization Authorization) error { + m, ok := authorization.(proto.Message) + if !ok { + return fmt.Errorf("can't proto marshal %T", m) + } + any, err := types.NewAnyWithValue(m) + if err != nil { + return err + } + msg.Authorization = any + return nil +} + +func (msg MsgExecAuthorized) UnpackInterfaces(unpacker types.AnyUnpacker) error { + for _, x := range msg.Msgs { + var msgExecAuthorized sdk.Msg + err := unpacker.UnpackAny(x, &msgExecAuthorized) + if err != nil { + return err + } + } + + return nil +} + +// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces +func (msg MsgGrantAuthorization) UnpackInterfaces(unpacker types.AnyUnpacker) error { + var authorization Authorization + return unpacker.UnpackAny(msg.Authorization, &authorization) +} + +// String implements the Stringer interface +func (msg MsgGrantAuthorization) String() string { + out, _ := yaml.Marshal(msg) + return string(out) +} + +// NewMsgRevokeAuthorization creates a new MsgRevokeAuthorization +//nolint:interfacer +func NewMsgRevokeAuthorization(granter sdk.AccAddress, grantee sdk.AccAddress, authorizationMsgType string) MsgRevokeAuthorization { + return MsgRevokeAuthorization{ + Granter: granter.String(), + Grantee: grantee.String(), + AuthorizationMsgType: authorizationMsgType, + } +} + +// Route implements Msg +func (msg MsgRevokeAuthorization) Route() string { return RouterKey } + +// Type implements Msg +func (msg MsgRevokeAuthorization) Type() string { return TypeMsgRevokeAuthorization } + +// GetSigners implements Msg +func (msg MsgRevokeAuthorization) GetSigners() []sdk.AccAddress { + granter, err := sdk.AccAddressFromBech32(msg.Granter) + if err != nil { + panic(err) + } + return []sdk.AccAddress{granter} +} + +// GetSignBytes implements Msg +func (msg MsgRevokeAuthorization) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(&msg) + return sdk.MustSortJSON(bz) +} + +// ValidateBasic implements Msg +func (msg MsgRevokeAuthorization) ValidateBasic() error { + if msg.Granter == "" { + return sdkerrors.Wrap(ErrInvalidGranter, "missing granter address") + } + if msg.Grantee == "" { + return sdkerrors.Wrap(ErrInvalidGrantee, "missing grantee address") + } + return nil +} + +// String implements the Stringer interface +func (msg MsgRevokeAuthorization) String() string { + out, _ := yaml.Marshal(msg) + return string(out) +} + +// NewMsgExecAuthorized creates a new MsgExecAuthorized +//nolint:interfacer +func NewMsgExecAuthorized(grantee sdk.AccAddress, msgs []sdk.Msg) MsgExecAuthorized { + msgsAny := make([]*types.Any, len(msgs)) + for i, msg := range msgs { + msg1, ok := msg.(proto.Message) + if !ok { + panic(fmt.Errorf("cannot proto marshal %T", msg1)) + } + + any, err := types.NewAnyWithValue(msg1) + if err != nil { + panic(err) + } + + msgsAny[i] = any + } + return MsgExecAuthorized{ + Grantee: grantee.String(), + Msgs: msgsAny, + } +} + +// GetMsgs Unpacks any messages +func (msg MsgExecAuthorized) GetMsgs() ([]sdk.Msg, error) { + msgs := make([]sdk.Msg, len(msg.Msgs)) + for i, msgAny := range msg.Msgs { + msg1, ok := msgAny.GetCachedValue().(sdk.Msg) + if !ok { + return nil, fmt.Errorf("cannot proto marshal %T", msg1) + } + msgs[i] = msg1 + } + return msgs, nil +} + +// Route implements Msg +func (msg MsgExecAuthorized) Route() string { return RouterKey } + +// Type implements Msg +func (msg MsgExecAuthorized) Type() string { return TypeMsgExecDelegated } + +// GetSigners implements Msg +func (msg MsgExecAuthorized) GetSigners() []sdk.AccAddress { + grantee, err := sdk.AccAddressFromBech32(msg.Grantee) + if err != nil { + panic(err) + } + return []sdk.AccAddress{grantee} +} + +// GetSignBytes implements Msg +func (msg MsgExecAuthorized) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(&msg) + return sdk.MustSortJSON(bz) +} + +// ValidateBasic implements Msg +func (msg MsgExecAuthorized) ValidateBasic() error { + if msg.Grantee == "" { + return sdkerrors.Wrap(ErrInvalidGranter, "missing grantee address") + } + return nil +} + +// String implements the Stringer interface +func (msg MsgExecAuthorized) String() string { + out, _ := yaml.Marshal(msg) + return string(out) +} diff --git a/x/msg_authorization/types/msgs_test.go b/x/msg_authorization/types/msgs_test.go new file mode 100644 index 000000000000..c589ec2892f7 --- /dev/null +++ b/x/msg_authorization/types/msgs_test.go @@ -0,0 +1,135 @@ +package types_test + +import ( + "fmt" + "testing" + "time" + + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/msg_authorization/types" + "github.com/stretchr/testify/require" +) + +var ( + coinsPos = sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) + granter = sdk.AccAddress("_______granter______") + grantee = sdk.AccAddress("_______grantee______") +) + +func TestMsgExecAuthorized(t *testing.T) { + tests := []struct { + title string + grantee sdk.AccAddress + msgs []sdk.Msg + expectPass bool + }{ + {"nil grantee address", nil, []sdk.Msg{}, false}, + {"valid test", grantee, []sdk.Msg{}, true}, + {"valid test: msg type", grantee, []sdk.Msg{&banktypes.MsgSend{ + Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)), + FromAddress: granter.String(), + ToAddress: grantee.String(), + }}, true}, + } + for i, tc := range tests { + msg := types.NewMsgExecAuthorized(tc.grantee, tc.msgs) + if tc.expectPass { + require.NoError(t, msg.ValidateBasic(), "test: %v", i) + } else { + require.Error(t, msg.ValidateBasic(), "test: %v", i) + } + } +} +func TestMsgRevokeAuthorization(t *testing.T) { + tests := []struct { + title string + granter, grantee sdk.AccAddress + msgType string + expectPass bool + }{ + {"nil Granter address", nil, grantee, "hello", false}, + {"nil Grantee address", granter, nil, "hello", false}, + {"nil Granter and Grantee address", nil, nil, "hello", false}, + {"valid test case", granter, grantee, "hello", true}, + } + for i, tc := range tests { + msg := types.NewMsgRevokeAuthorization(tc.granter, tc.grantee, tc.msgType) + if tc.expectPass { + require.NoError(t, msg.ValidateBasic(), "test: %v", i) + } else { + require.Error(t, msg.ValidateBasic(), "test: %v", i) + } + } +} + +func TestMsgGrantAuthorization(t *testing.T) { + tests := []struct { + title string + granter, grantee sdk.AccAddress + authorization types.Authorization + expiration time.Time + expectErr bool + expectPass bool + }{ + {"nil granter address", nil, grantee, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, + {"nil grantee address", granter, nil, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false}, + {"nil granter and grantee address", nil, nil, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, 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}, + {"past time", granter, grantee, &types.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false}, + } + for i, tc := range tests { + msg, err := types.NewMsgGrantAuthorization( + tc.granter, tc.grantee, tc.authorization, tc.expiration, + ) + if !tc.expectErr { + require.NoError(t, err) + } else { + continue + } + if tc.expectPass { + require.NoError(t, msg.ValidateBasic(), "test: %v", i) + } else { + require.Error(t, msg.ValidateBasic(), "test: %v", i) + } + } +} + +func TestMsgGrantAuthorizationGetSignBytes(t *testing.T) { + period := time.Now().AddDate(0, 1, 0) + expected := fmt.Sprintf( + `{"type":"cosmos-sdk/MsgGrantAuthorization","value":{"authorization":{"type":"cosmos-sdk/SendAuthorization","value":{"spend_limit":[{"amount":"100","denom":"steak"}]}},"expiration":"%s","grantee":"cosmos1ta047h6lta0kwunpde6x2e2lta047h6l22453t","granter":"cosmos1ta047h6lta0kwunpde6x2ujlta047h6l3ksxz2"}}`, + period.UTC().Format(time.RFC3339Nano)) + msg, err := types.NewMsgGrantAuthorization( + granter, grantee, &types.SendAuthorization{SpendLimit: coinsPos}, period, + ) + require.NoError(t, err) + res := msg.GetSignBytes() + require.Equal(t, expected, string(res)) +} + +func TestMsgRevokeAuthorizationGetSignBytes(t *testing.T) { + expected := `{"type":"cosmos-sdk/MsgRevokeAuthorization","value":{"authorization_msg_type":"cosmos.bank.v1beta1.MsgSend","grantee":"cosmos1ta047h6lta0kwunpde6x2e2lta047h6l22453t","granter":"cosmos1ta047h6lta0kwunpde6x2ujlta047h6l3ksxz2"}}` + msg := types.NewMsgRevokeAuthorization( + granter, grantee, types.SendAuthorization{}.MethodName(), + ) + res := msg.GetSignBytes() + require.Equal(t, expected, string(res)) +} + +func TestMsgExecAuthorizedGetSignBytes(t *testing.T) { + expected := `{"type":"cosmos-sdk/MsgExecAuthorized","value":{"grantee":"cosmos1ta047h6lta0kwunpde6x2e2lta047h6l22453t","msgs":[{"amount":[{"amount":"2","denom":"steak"}],"from_address":"cosmos1ta047h6lta0kwunpde6x2ujlta047h6l3ksxz2","to_address":"cosmos1ta047h6lta0kwunpde6x2e2lta047h6l22453t"}]}}` + msg := types.NewMsgExecAuthorized( + grantee, []sdk.Msg{ + &banktypes.MsgSend{ + Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)), + FromAddress: granter.String(), + ToAddress: grantee.String(), + }, + }, + ) + res := msg.GetSignBytes() + require.Equal(t, expected, string(res)) +} diff --git a/x/msg_authorization/types/querier.go b/x/msg_authorization/types/querier.go new file mode 100644 index 000000000000..fbd32f2dae7a --- /dev/null +++ b/x/msg_authorization/types/querier.go @@ -0,0 +1,6 @@ +package types + +// Querier path constants +const ( + QueryAuthorization = "authorization" +) diff --git a/x/msg_authorization/types/query.pb.go b/x/msg_authorization/types/query.pb.go new file mode 100644 index 000000000000..7a36abffe1e2 --- /dev/null +++ b/x/msg_authorization/types/query.pb.go @@ -0,0 +1,692 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/msg_authorization/v1beta1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + types "github.com/cosmos/cosmos-sdk/codec/types" + _ "github.com/gogo/protobuf/gogoproto" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/proto" + _ "github.com/regen-network/cosmos-proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + 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 + +// QueryAuthorizationRequest is the request type for the Query/Authorization RPC method. +type QueryAuthorizationRequest struct { + GranterAddr string `protobuf:"bytes,1,opt,name=granter_addr,json=granterAddr,proto3" json:"granter_addr,omitempty"` + GranteeAddr string `protobuf:"bytes,2,opt,name=grantee_addr,json=granteeAddr,proto3" json:"grantee_addr,omitempty"` + MsgType string `protobuf:"bytes,3,opt,name=msg_type,json=msgType,proto3" json:"msg_type,omitempty"` +} + +func (m *QueryAuthorizationRequest) Reset() { *m = QueryAuthorizationRequest{} } +func (m *QueryAuthorizationRequest) String() string { return proto.CompactTextString(m) } +func (*QueryAuthorizationRequest) ProtoMessage() {} +func (*QueryAuthorizationRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e28514a6a1d72ff8, []int{0} +} +func (m *QueryAuthorizationRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAuthorizationRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAuthorizationRequest.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 *QueryAuthorizationRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAuthorizationRequest.Merge(m, src) +} +func (m *QueryAuthorizationRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryAuthorizationRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAuthorizationRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAuthorizationRequest proto.InternalMessageInfo + +// QueryAuthorizationResponse is the response type for the Query/Authorization RPC method. +type QueryAuthorizationResponse struct { + // account defines the account of the corresponding address. + Authorization *types.Any `protobuf:"bytes,1,opt,name=authorization,proto3" json:"authorization,omitempty"` +} + +func (m *QueryAuthorizationResponse) Reset() { *m = QueryAuthorizationResponse{} } +func (m *QueryAuthorizationResponse) String() string { return proto.CompactTextString(m) } +func (*QueryAuthorizationResponse) ProtoMessage() {} +func (*QueryAuthorizationResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e28514a6a1d72ff8, []int{1} +} +func (m *QueryAuthorizationResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAuthorizationResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAuthorizationResponse.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 *QueryAuthorizationResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAuthorizationResponse.Merge(m, src) +} +func (m *QueryAuthorizationResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryAuthorizationResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAuthorizationResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAuthorizationResponse proto.InternalMessageInfo + +func (m *QueryAuthorizationResponse) GetAuthorization() *types.Any { + if m != nil { + return m.Authorization + } + return nil +} + +func init() { + proto.RegisterType((*QueryAuthorizationRequest)(nil), "cosmos.msg_authorization.v1beta1.QueryAuthorizationRequest") + proto.RegisterType((*QueryAuthorizationResponse)(nil), "cosmos.msg_authorization.v1beta1.QueryAuthorizationResponse") +} + +func init() { + proto.RegisterFile("cosmos/msg_authorization/v1beta1/query.proto", fileDescriptor_e28514a6a1d72ff8) +} + +var fileDescriptor_e28514a6a1d72ff8 = []byte{ + // 405 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x49, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0xcf, 0x2d, 0x4e, 0x8f, 0x4f, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, 0xca, 0xac, 0x4a, + 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x2c, 0x4d, + 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x80, 0xa8, 0xd6, 0xc3, 0x50, 0xad, + 0x07, 0x55, 0x2d, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xac, 0x0f, 0x62, 0x41, 0xf4, 0x49, + 0x49, 0xa6, 0xe7, 0xe7, 0xa7, 0xe7, 0xa4, 0xea, 0x83, 0x79, 0x49, 0xa5, 0x69, 0xfa, 0x89, 0x79, + 0x50, 0x23, 0xa5, 0x64, 0xa0, 0x52, 0x89, 0x05, 0x99, 0xfa, 0x89, 0x79, 0x79, 0xf9, 0x25, 0x60, + 0xf3, 0x8a, 0x61, 0x1a, 0x21, 0x16, 0xc6, 0x43, 0x4c, 0x84, 0xda, 0x0e, 0xe6, 0x28, 0xb5, 0x31, + 0x72, 0x49, 0x06, 0x82, 0xdc, 0xe6, 0x88, 0xec, 0x90, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, + 0x21, 0x45, 0x2e, 0x9e, 0xf4, 0xa2, 0xc4, 0xbc, 0x92, 0xd4, 0xa2, 0xf8, 0xc4, 0x94, 0x94, 0x22, + 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x6e, 0xa8, 0x98, 0x63, 0x4a, 0x4a, 0x11, 0x42, 0x49, + 0x2a, 0x44, 0x09, 0x13, 0xb2, 0x92, 0x54, 0xb0, 0x12, 0x49, 0x2e, 0x0e, 0x90, 0x57, 0x4b, 0x2a, + 0x0b, 0x52, 0x25, 0x98, 0xc1, 0xd2, 0xec, 0xb9, 0xc5, 0xe9, 0x21, 0x95, 0x05, 0xa9, 0x56, 0x1c, + 0x1d, 0x0b, 0xe4, 0x19, 0x5e, 0x2c, 0x90, 0x67, 0x50, 0xca, 0xe6, 0x92, 0xc2, 0xe6, 0x8e, 0xe2, + 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0x21, 0x5f, 0x2e, 0x5e, 0x94, 0x90, 0x02, 0xbb, 0x84, 0xdb, 0x48, + 0x44, 0x0f, 0xe2, 0x6f, 0x3d, 0x58, 0x90, 0xe8, 0x39, 0xe6, 0x55, 0x3a, 0x09, 0x9e, 0xda, 0xa2, + 0xcb, 0x8b, 0x6a, 0x0e, 0xaa, 0x6e, 0xa3, 0x0f, 0x8c, 0x5c, 0xac, 0x60, 0xdb, 0x84, 0x9e, 0x31, + 0x72, 0xa1, 0x2a, 0x15, 0xb2, 0xd6, 0x23, 0x14, 0x3d, 0x7a, 0x38, 0x03, 0x4c, 0xca, 0x86, 0x3c, + 0xcd, 0x10, 0x5f, 0x2a, 0x45, 0x35, 0x5d, 0x7e, 0x32, 0x99, 0x29, 0x44, 0x28, 0x48, 0x1f, 0x91, + 0x9e, 0x40, 0x86, 0xc0, 0x53, 0x11, 0x34, 0xe0, 0x8b, 0xf5, 0xab, 0x91, 0xa3, 0xa5, 0x16, 0x2a, + 0x9e, 0x0a, 0x17, 0x4f, 0x85, 0x8a, 0x57, 0xc3, 0xc2, 0xbd, 0xd6, 0x29, 0xe0, 0xc4, 0x23, 0x39, + 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, + 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xcc, 0xd2, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, + 0xf3, 0x73, 0x61, 0xf6, 0x42, 0x28, 0xdd, 0xe2, 0x94, 0x6c, 0xfd, 0x0a, 0x2c, 0x89, 0x1a, 0x64, + 0x62, 0x71, 0x12, 0x1b, 0x38, 0xd0, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x09, 0xf1, 0x6b, + 0x5c, 0xfd, 0x02, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Returns any `Authorization` (or `nil`), with the expiration time, granted to the grantee by the granter for the provided msg type. + Authorization(ctx context.Context, in *QueryAuthorizationRequest, opts ...grpc.CallOption) (*QueryAuthorizationResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Authorization(ctx context.Context, in *QueryAuthorizationRequest, opts ...grpc.CallOption) (*QueryAuthorizationResponse, error) { + out := new(QueryAuthorizationResponse) + err := c.cc.Invoke(ctx, "/cosmos.msg_authorization.v1beta1.Query/Authorization", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Returns any `Authorization` (or `nil`), with the expiration time, granted to the grantee by the granter for the provided msg type. + Authorization(context.Context, *QueryAuthorizationRequest) (*QueryAuthorizationResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Authorization(ctx context.Context, req *QueryAuthorizationRequest) (*QueryAuthorizationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Authorization not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Authorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAuthorizationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Authorization(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.msg_authorization.v1beta1.Query/Authorization", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Authorization(ctx, req.(*QueryAuthorizationRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.msg_authorization.v1beta1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Authorization", + Handler: _Query_Authorization_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/msg_authorization/v1beta1/query.proto", +} + +func (m *QueryAuthorizationRequest) 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 *QueryAuthorizationRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAuthorizationRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.MsgType) > 0 { + i -= len(m.MsgType) + copy(dAtA[i:], m.MsgType) + i = encodeVarintQuery(dAtA, i, uint64(len(m.MsgType))) + i-- + dAtA[i] = 0x1a + } + if len(m.GranteeAddr) > 0 { + i -= len(m.GranteeAddr) + copy(dAtA[i:], m.GranteeAddr) + i = encodeVarintQuery(dAtA, i, uint64(len(m.GranteeAddr))) + i-- + dAtA[i] = 0x12 + } + if len(m.GranterAddr) > 0 { + i -= len(m.GranterAddr) + copy(dAtA[i:], m.GranterAddr) + i = encodeVarintQuery(dAtA, i, uint64(len(m.GranterAddr))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryAuthorizationResponse) 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 *QueryAuthorizationResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAuthorizationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Authorization != nil { + { + size, err := m.Authorization.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryAuthorizationRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.GranterAddr) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.GranteeAddr) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.MsgType) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryAuthorizationResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Authorization != nil { + l = m.Authorization.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryAuthorizationRequest) 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 ErrIntOverflowQuery + } + 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: QueryAuthorizationRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAuthorizationRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GranterAddr", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.GranterAddr = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GranteeAddr", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.GranteeAddr = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MsgType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAuthorizationResponse) 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 ErrIntOverflowQuery + } + 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: QueryAuthorizationResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAuthorizationResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authorization", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Authorization == nil { + m.Authorization = &types.Any{} + } + if err := m.Authorization.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(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, ErrIntOverflowQuery + } + 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, ErrIntOverflowQuery + } + 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, ErrIntOverflowQuery + } + 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, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/msg_authorization/types/query.pb.gw.go b/x/msg_authorization/types/query.pb.gw.go new file mode 100644 index 000000000000..56015e77b1b5 --- /dev/null +++ b/x/msg_authorization/types/query.pb.gw.go @@ -0,0 +1,228 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: cosmos/msg_authorization/v1beta1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage + +func request_Query_Authorization_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAuthorizationRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["granter_addr"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "granter_addr") + } + + protoReq.GranterAddr, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "granter_addr", err) + } + + val, ok = pathParams["grantee_addr"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "grantee_addr") + } + + protoReq.GranteeAddr, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "grantee_addr", err) + } + + val, ok = pathParams["msg_type"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_type") + } + + protoReq.MsgType, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_type", err) + } + + msg, err := client.Authorization(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Authorization_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAuthorizationRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["granter_addr"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "granter_addr") + } + + protoReq.GranterAddr, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "granter_addr", err) + } + + val, ok = pathParams["grantee_addr"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "grantee_addr") + } + + protoReq.GranteeAddr, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "grantee_addr", err) + } + + val, ok = pathParams["msg_type"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_type") + } + + protoReq.MsgType, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_type", err) + } + + msg, err := server.Authorization(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Authorization_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Authorization_0(rctx, inboundMarshaler, server, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Authorization_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Authorization_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Authorization_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Authorization_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Authorization_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 1, 0, 4, 1, 5, 6, 1, 0, 4, 1, 5, 7}, []string{"cosmos", "msgauth", "v1beta1", "granters", "granter_addr", "grantees", "grantee_addr", "msg_type"}, "", runtime.AssumeColonVerbOpt(true))) +) + +var ( + forward_Query_Authorization_0 = runtime.ForwardResponseMessage +) diff --git a/x/msg_authorization/types/router.go b/x/msg_authorization/types/router.go new file mode 100644 index 000000000000..baae9daa406e --- /dev/null +++ b/x/msg_authorization/types/router.go @@ -0,0 +1,72 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var _ Router = &router{} + +// Router implements a governance Handler router. +// +// TODO: Use generic router (ref #3976). +type Router interface { + AddRoute(r string, h sdk.Handler) (rtr Router) + HasRoute(r string) bool + GetRoute(path string) (h sdk.Handler) + Seal() +} + +type router struct { + routes map[string]sdk.Handler + sealed bool +} + +// NewRouter creates a new Router interface instance +func NewRouter() Router { + return &router{ + routes: make(map[string]sdk.Handler), + } +} + +// Seal seals the router which prohibits any subsequent route handlers to be +// added. Seal will panic if called more than once. +func (rtr *router) Seal() { + if rtr.sealed { + panic("router already sealed") + } + rtr.sealed = true +} + +// AddRoute adds a governance handler for a given path. It returns the Router +// so AddRoute calls can be linked. It will panic if the router is sealed. +func (rtr *router) AddRoute(path string, h sdk.Handler) Router { + if rtr.sealed { + panic("router sealed; cannot add route handler") + } + + if !sdk.IsAlphaNumeric(path) { + panic("route expressions can only contain alphanumeric characters") + } + if rtr.HasRoute(path) { + panic(fmt.Sprintf("route %s has already been initialized", path)) + } + + rtr.routes[path] = h + return rtr +} + +// HasRoute returns true if the router has a path registered or false otherwise. +func (rtr *router) HasRoute(path string) bool { + return rtr.routes[path] != nil +} + +// GetRoute returns a sdk.Handler for a given path. +func (rtr *router) GetRoute(path string) sdk.Handler { + if !rtr.HasRoute(path) { + panic(fmt.Sprintf("route \"%s\" does not exist", path)) + } + + return rtr.routes[path] +} diff --git a/x/msg_authorization/types/send_authorization.go b/x/msg_authorization/types/send_authorization.go new file mode 100644 index 000000000000..5242586627e0 --- /dev/null +++ b/x/msg_authorization/types/send_authorization.go @@ -0,0 +1,40 @@ +package types + +import ( + "reflect" + + sdk "github.com/cosmos/cosmos-sdk/types" + bank "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/gogo/protobuf/proto" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" +) + +var ( + _ Authorization = &SendAuthorization{} +) + +func NewSendAuthorization(spendLimit sdk.Coins) *SendAuthorization { + return &SendAuthorization{ + SpendLimit: spendLimit, + } +} + +func (authorization SendAuthorization) MethodName() string { + return proto.MessageName(&bank.MsgSend{}) +} + +func (authorization SendAuthorization) Accept(msg sdk.Msg, block tmproto.Header) (allow bool, updated Authorization, delete bool) { + if reflect.TypeOf(msg) == reflect.TypeOf(&bank.MsgSend{}) { + msg := msg.(*bank.MsgSend) + limitLeft, isNegative := authorization.SpendLimit.SafeSub(msg.Amount) + if isNegative { + return false, nil, false + } + if limitLeft.IsZero() { + return true, nil, true + } + + return true, &SendAuthorization{SpendLimit: limitLeft}, false + } + return false, nil, false +} diff --git a/x/msg_authorization/types/tx.pb.go b/x/msg_authorization/types/tx.pb.go new file mode 100644 index 000000000000..36a84c6cc783 --- /dev/null +++ b/x/msg_authorization/types/tx.pb.go @@ -0,0 +1,1706 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/msg_authorization/v1beta1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + types "github.com/cosmos/cosmos-sdk/codec/types" + types1 "github.com/cosmos/cosmos-sdk/types" + _ "github.com/gogo/protobuf/gogoproto" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/proto" + github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" + _ "github.com/golang/protobuf/ptypes/timestamp" + _ "github.com/regen-network/cosmos-proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" + time "time" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// 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 + +// MsgGrantAuthorization grants the provided authorization to the grantee on the granter's +// account with the provided expiration time. +type MsgGrantAuthorization struct { + Granter string `protobuf:"bytes,1,opt,name=granter,proto3" json:"granter,omitempty"` + Grantee string `protobuf:"bytes,2,opt,name=grantee,proto3" json:"grantee,omitempty"` + Authorization *types.Any `protobuf:"bytes,3,opt,name=authorization,proto3" json:"authorization,omitempty"` + Expiration time.Time `protobuf:"bytes,4,opt,name=expiration,proto3,stdtime" json:"expiration"` +} + +func (m *MsgGrantAuthorization) Reset() { *m = MsgGrantAuthorization{} } +func (*MsgGrantAuthorization) ProtoMessage() {} +func (*MsgGrantAuthorization) Descriptor() ([]byte, []int) { + return fileDescriptor_7ededd1bbd56a4f0, []int{0} +} +func (m *MsgGrantAuthorization) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgGrantAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgGrantAuthorization.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 *MsgGrantAuthorization) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgGrantAuthorization.Merge(m, src) +} +func (m *MsgGrantAuthorization) XXX_Size() int { + return m.Size() +} +func (m *MsgGrantAuthorization) XXX_DiscardUnknown() { + xxx_messageInfo_MsgGrantAuthorization.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgGrantAuthorization proto.InternalMessageInfo + +// MsgExecAuthorizedResponse defines the Msg/MsgExecAuthorizedResponse response type. +type MsgExecAuthorizedResponse struct { + Result *types1.Result `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"` +} + +func (m *MsgExecAuthorizedResponse) Reset() { *m = MsgExecAuthorizedResponse{} } +func (m *MsgExecAuthorizedResponse) String() string { return proto.CompactTextString(m) } +func (*MsgExecAuthorizedResponse) ProtoMessage() {} +func (*MsgExecAuthorizedResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_7ededd1bbd56a4f0, []int{1} +} +func (m *MsgExecAuthorizedResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgExecAuthorizedResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgExecAuthorizedResponse.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 *MsgExecAuthorizedResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgExecAuthorizedResponse.Merge(m, src) +} +func (m *MsgExecAuthorizedResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgExecAuthorizedResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgExecAuthorizedResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgExecAuthorizedResponse proto.InternalMessageInfo + +func (m *MsgExecAuthorizedResponse) GetResult() *types1.Result { + if m != nil { + return m.Result + } + return nil +} + +// MsgExecAuthorized attempts to execute the provided messages using +// authorizations granted to the grantee. Each message should have only +// one signer corresponding to the granter of the authorization. +type MsgExecAuthorized struct { + Grantee string `protobuf:"bytes,1,opt,name=grantee,proto3" json:"grantee,omitempty"` + Msgs []*types.Any `protobuf:"bytes,2,rep,name=msgs,proto3" json:"msgs,omitempty" yaml:"msgs"` +} + +func (m *MsgExecAuthorized) Reset() { *m = MsgExecAuthorized{} } +func (*MsgExecAuthorized) ProtoMessage() {} +func (*MsgExecAuthorized) Descriptor() ([]byte, []int) { + return fileDescriptor_7ededd1bbd56a4f0, []int{2} +} +func (m *MsgExecAuthorized) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgExecAuthorized) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgExecAuthorized.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 *MsgExecAuthorized) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgExecAuthorized.Merge(m, src) +} +func (m *MsgExecAuthorized) XXX_Size() int { + return m.Size() +} +func (m *MsgExecAuthorized) XXX_DiscardUnknown() { + xxx_messageInfo_MsgExecAuthorized.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgExecAuthorized proto.InternalMessageInfo + +// MsgGrantAuthorizationResponse defines the Msg/MsgGrantAuthorization response type. +type MsgGrantAuthorizationResponse struct { +} + +func (m *MsgGrantAuthorizationResponse) Reset() { *m = MsgGrantAuthorizationResponse{} } +func (m *MsgGrantAuthorizationResponse) String() string { return proto.CompactTextString(m) } +func (*MsgGrantAuthorizationResponse) ProtoMessage() {} +func (*MsgGrantAuthorizationResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_7ededd1bbd56a4f0, []int{3} +} +func (m *MsgGrantAuthorizationResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgGrantAuthorizationResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgGrantAuthorizationResponse.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 *MsgGrantAuthorizationResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgGrantAuthorizationResponse.Merge(m, src) +} +func (m *MsgGrantAuthorizationResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgGrantAuthorizationResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgGrantAuthorizationResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgGrantAuthorizationResponse proto.InternalMessageInfo + +// MsgRevokeAuthorization revokes any authorization with the provided sdk.Msg type on the +// granter's account with that has been granted to the grantee. +type MsgRevokeAuthorization struct { + Granter string `protobuf:"bytes,1,opt,name=granter,proto3" json:"granter,omitempty"` + Grantee string `protobuf:"bytes,2,opt,name=grantee,proto3" json:"grantee,omitempty"` + AuthorizationMsgType string `protobuf:"bytes,3,opt,name=authorization_msg_type,json=authorizationMsgType,proto3" json:"authorization_msg_type,omitempty" yaml:"authorization_msg_type"` +} + +func (m *MsgRevokeAuthorization) Reset() { *m = MsgRevokeAuthorization{} } +func (*MsgRevokeAuthorization) ProtoMessage() {} +func (*MsgRevokeAuthorization) Descriptor() ([]byte, []int) { + return fileDescriptor_7ededd1bbd56a4f0, []int{4} +} +func (m *MsgRevokeAuthorization) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRevokeAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRevokeAuthorization.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 *MsgRevokeAuthorization) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRevokeAuthorization.Merge(m, src) +} +func (m *MsgRevokeAuthorization) XXX_Size() int { + return m.Size() +} +func (m *MsgRevokeAuthorization) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRevokeAuthorization.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRevokeAuthorization proto.InternalMessageInfo + +// MsgRevokeAuthorizationResponse defines the Msg/MsgRevokeAuthorizationResponse response type. +type MsgRevokeAuthorizationResponse struct { +} + +func (m *MsgRevokeAuthorizationResponse) Reset() { *m = MsgRevokeAuthorizationResponse{} } +func (m *MsgRevokeAuthorizationResponse) String() string { return proto.CompactTextString(m) } +func (*MsgRevokeAuthorizationResponse) ProtoMessage() {} +func (*MsgRevokeAuthorizationResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_7ededd1bbd56a4f0, []int{5} +} +func (m *MsgRevokeAuthorizationResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRevokeAuthorizationResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRevokeAuthorizationResponse.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 *MsgRevokeAuthorizationResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRevokeAuthorizationResponse.Merge(m, src) +} +func (m *MsgRevokeAuthorizationResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgRevokeAuthorizationResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRevokeAuthorizationResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRevokeAuthorizationResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgGrantAuthorization)(nil), "cosmos.msg_authorization.v1beta1.MsgGrantAuthorization") + proto.RegisterType((*MsgExecAuthorizedResponse)(nil), "cosmos.msg_authorization.v1beta1.MsgExecAuthorizedResponse") + proto.RegisterType((*MsgExecAuthorized)(nil), "cosmos.msg_authorization.v1beta1.MsgExecAuthorized") + proto.RegisterType((*MsgGrantAuthorizationResponse)(nil), "cosmos.msg_authorization.v1beta1.MsgGrantAuthorizationResponse") + proto.RegisterType((*MsgRevokeAuthorization)(nil), "cosmos.msg_authorization.v1beta1.MsgRevokeAuthorization") + proto.RegisterType((*MsgRevokeAuthorizationResponse)(nil), "cosmos.msg_authorization.v1beta1.MsgRevokeAuthorizationResponse") +} + +func init() { + proto.RegisterFile("cosmos/msg_authorization/v1beta1/tx.proto", fileDescriptor_7ededd1bbd56a4f0) +} + +var fileDescriptor_7ededd1bbd56a4f0 = []byte{ + // 599 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0x31, 0x6f, 0xd3, 0x40, + 0x14, 0xf6, 0x35, 0x55, 0x69, 0xaf, 0x14, 0xa9, 0xa6, 0x54, 0x89, 0xa5, 0xda, 0xc6, 0x48, 0xa8, + 0x0c, 0x39, 0xab, 0xa9, 0x04, 0x25, 0x0c, 0xd0, 0x08, 0xc4, 0xe4, 0xc5, 0x8a, 0x84, 0x04, 0x43, + 0x64, 0xa7, 0xc7, 0xd5, 0x6a, 0x9c, 0xb3, 0x7c, 0x4e, 0x95, 0x30, 0x32, 0x31, 0xa1, 0xb2, 0x31, + 0x30, 0x64, 0x64, 0xeb, 0xd2, 0x1f, 0x51, 0x75, 0xea, 0xc8, 0x14, 0x50, 0xb2, 0x74, 0x62, 0xe8, + 0x2f, 0x40, 0x3e, 0x9f, 0x43, 0xdc, 0x18, 0xa8, 0xc2, 0x94, 0xdc, 0xbd, 0xef, 0x7b, 0xf7, 0xbd, + 0xef, 0xbd, 0x67, 0xf8, 0xa0, 0x49, 0x99, 0x4f, 0x99, 0xe9, 0x33, 0xd2, 0x70, 0x3a, 0xd1, 0x3e, + 0x0d, 0xbd, 0x77, 0x4e, 0xe4, 0xd1, 0xb6, 0x79, 0xb8, 0xe5, 0xe2, 0xc8, 0xd9, 0x32, 0xa3, 0x2e, + 0x0a, 0x42, 0x1a, 0x51, 0x59, 0x4f, 0xa0, 0x68, 0x0a, 0x8a, 0x04, 0x54, 0x29, 0x25, 0x88, 0x06, + 0xc7, 0x9b, 0x02, 0xce, 0x0f, 0xca, 0x1a, 0xa1, 0x84, 0x26, 0xf7, 0xf1, 0x3f, 0x71, 0xab, 0x11, + 0x4a, 0x49, 0x0b, 0x9b, 0xfc, 0xe4, 0x76, 0xde, 0x9a, 0x91, 0xe7, 0x63, 0x16, 0x39, 0x7e, 0x20, + 0x00, 0xa5, 0xab, 0x00, 0xa7, 0xdd, 0x13, 0xa1, 0x7b, 0x42, 0xb9, 0xeb, 0x30, 0x6c, 0x3a, 0x6e, + 0xd3, 0x1b, 0x2b, 0x8e, 0x0f, 0x09, 0xc8, 0xf8, 0x09, 0xe0, 0x1d, 0x8b, 0x91, 0x97, 0xa1, 0xd3, + 0x8e, 0x76, 0x27, 0x35, 0xcb, 0x45, 0x78, 0x83, 0xc4, 0xb7, 0x38, 0x2c, 0x02, 0x1d, 0x6c, 0x2e, + 0xd9, 0xe9, 0xf1, 0x77, 0x04, 0x17, 0xe7, 0x26, 0x23, 0x58, 0xb6, 0xe0, 0x4a, 0xa6, 0xf0, 0x62, + 0x41, 0x07, 0x9b, 0xcb, 0x95, 0x35, 0x94, 0xa8, 0x44, 0xa9, 0x4a, 0xb4, 0xdb, 0xee, 0xd5, 0x56, + 0xcf, 0x4e, 0xca, 0x2b, 0x99, 0x37, 0xed, 0x2c, 0x5b, 0x7e, 0x0e, 0x21, 0xee, 0x06, 0x5e, 0x98, + 0xe4, 0x9a, 0xe7, 0xb9, 0x94, 0xa9, 0x5c, 0xf5, 0xd4, 0x92, 0xda, 0xe2, 0xe9, 0x40, 0x93, 0x8e, + 0xbe, 0x6b, 0xc0, 0x9e, 0xe0, 0x55, 0x6f, 0x7e, 0xe8, 0x6b, 0xd2, 0xe7, 0xbe, 0x26, 0x5d, 0xf4, + 0x35, 0x60, 0xbc, 0x81, 0x25, 0x8b, 0x91, 0x17, 0x5d, 0xdc, 0x4c, 0x9f, 0xc6, 0x7b, 0x36, 0x66, + 0x01, 0x6d, 0x33, 0x2c, 0xef, 0xc0, 0x85, 0x10, 0xb3, 0x4e, 0x2b, 0xe2, 0x25, 0x2f, 0x57, 0x74, + 0x24, 0x7a, 0x14, 0x7b, 0x88, 0xb8, 0x6d, 0xc2, 0x43, 0x64, 0x73, 0x9c, 0x2d, 0xf0, 0xd5, 0xf9, + 0x8b, 0xbe, 0x26, 0x19, 0x5f, 0x00, 0x5c, 0x9d, 0xca, 0x3e, 0xe9, 0x17, 0xc8, 0xfa, 0xd5, 0x84, + 0xf3, 0x3e, 0x23, 0xac, 0x38, 0xa7, 0x17, 0xfe, 0x68, 0xd3, 0xe3, 0xcb, 0x81, 0xb6, 0xdc, 0x73, + 0xfc, 0x56, 0xd5, 0x88, 0xb1, 0xc6, 0xd9, 0x49, 0xf9, 0x3e, 0xf1, 0xa2, 0xfd, 0x8e, 0x8b, 0x9a, + 0xd4, 0x17, 0x43, 0x24, 0x7e, 0xca, 0x6c, 0xef, 0xc0, 0x8c, 0x7a, 0x01, 0x66, 0xc8, 0x62, 0xc4, + 0xe6, 0xc9, 0xab, 0x8b, 0x69, 0xfd, 0x86, 0x06, 0x37, 0x72, 0x7b, 0x9d, 0xd6, 0x6f, 0x1c, 0x03, + 0xb8, 0x1e, 0x13, 0xf1, 0x21, 0x3d, 0xc0, 0xff, 0x3f, 0x0e, 0xaf, 0xe0, 0x7a, 0xa6, 0xa1, 0x8d, + 0x78, 0x33, 0x62, 0x79, 0x7c, 0x2e, 0x96, 0x6a, 0x77, 0x2f, 0x07, 0xda, 0x46, 0x52, 0x5a, 0x3e, + 0xce, 0xb0, 0xd7, 0x32, 0x01, 0x8b, 0x91, 0x7a, 0x2f, 0xc0, 0x13, 0x25, 0xe9, 0x50, 0xcd, 0x17, + 0x9c, 0xd6, 0x54, 0x39, 0x2e, 0xc0, 0x82, 0xc5, 0x88, 0xfc, 0x11, 0x40, 0x39, 0x67, 0xcc, 0x1f, + 0xa1, 0x7f, 0x6d, 0x2d, 0xca, 0xf5, 0x4c, 0x79, 0x3a, 0x23, 0x71, 0x3c, 0x6c, 0xef, 0x01, 0xbc, + 0x75, 0x65, 0x52, 0xb6, 0xaf, 0x95, 0x33, 0x4b, 0x52, 0x9e, 0xcc, 0x40, 0x1a, 0x8b, 0xf8, 0x04, + 0xe0, 0xed, 0xbc, 0x76, 0xef, 0x5c, 0x2b, 0x69, 0x0e, 0x53, 0x79, 0x36, 0x2b, 0x33, 0xd5, 0x54, + 0xab, 0x7f, 0x1d, 0xaa, 0xe0, 0x74, 0xa8, 0x82, 0xf3, 0xa1, 0x0a, 0x7e, 0x0c, 0x55, 0x70, 0x34, + 0x52, 0xa5, 0xf3, 0x91, 0x2a, 0x7d, 0x1b, 0xa9, 0xd2, 0xeb, 0x87, 0x7f, 0x1d, 0xfe, 0x6e, 0xce, + 0x87, 0x9a, 0x2f, 0x84, 0xbb, 0xc0, 0xb7, 0x6a, 0xfb, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7d, + 0xa4, 0xb9, 0x7d, 0xd1, 0x05, 0x00, 0x00, +} + +func (this *MsgGrantAuthorization) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*MsgGrantAuthorization) + if !ok { + that2, ok := that.(MsgGrantAuthorization) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Granter != that1.Granter { + return false + } + if this.Grantee != that1.Grantee { + return false + } + if !this.Authorization.Equal(that1.Authorization) { + return false + } + if !this.Expiration.Equal(that1.Expiration) { + return false + } + return true +} +func (this *MsgExecAuthorized) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*MsgExecAuthorized) + if !ok { + that2, ok := that.(MsgExecAuthorized) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Grantee != that1.Grantee { + return false + } + if len(this.Msgs) != len(that1.Msgs) { + return false + } + for i := range this.Msgs { + if !this.Msgs[i].Equal(that1.Msgs[i]) { + return false + } + } + return true +} +func (this *MsgGrantAuthorizationResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*MsgGrantAuthorizationResponse) + if !ok { + that2, ok := that.(MsgGrantAuthorizationResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + return true +} +func (this *MsgRevokeAuthorization) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*MsgRevokeAuthorization) + if !ok { + that2, ok := that.(MsgRevokeAuthorization) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Granter != that1.Granter { + return false + } + if this.Grantee != that1.Grantee { + return false + } + if this.AuthorizationMsgType != that1.AuthorizationMsgType { + return false + } + return true +} +func (this *MsgRevokeAuthorizationResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*MsgRevokeAuthorizationResponse) + if !ok { + that2, ok := that.(MsgRevokeAuthorizationResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + return true +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// MsgClient is the client API for Msg service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type MsgClient interface { + // GrantAuthorization grants the provided authorization to the grantee on the granter's + // account with the provided expiration time. + GrantAuthorization(ctx context.Context, in *MsgGrantAuthorization, opts ...grpc.CallOption) (*MsgGrantAuthorizationResponse, error) + // ExecAuthorized attempts to execute the provided messages using + // authorizations granted to the grantee. Each message should have only + // one signer corresponding to the granter of the authorization. + ExecAuthorized(ctx context.Context, in *MsgExecAuthorized, opts ...grpc.CallOption) (*MsgExecAuthorizedResponse, error) + // RevokeAuthorization revokes any authorization corresponding to the provided method name on the + // granter's account that has been granted to the grantee. + RevokeAuthorization(ctx context.Context, in *MsgRevokeAuthorization, opts ...grpc.CallOption) (*MsgRevokeAuthorizationResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) GrantAuthorization(ctx context.Context, in *MsgGrantAuthorization, opts ...grpc.CallOption) (*MsgGrantAuthorizationResponse, error) { + out := new(MsgGrantAuthorizationResponse) + err := c.cc.Invoke(ctx, "/cosmos.msg_authorization.v1beta1.Msg/GrantAuthorization", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) ExecAuthorized(ctx context.Context, in *MsgExecAuthorized, opts ...grpc.CallOption) (*MsgExecAuthorizedResponse, error) { + out := new(MsgExecAuthorizedResponse) + err := c.cc.Invoke(ctx, "/cosmos.msg_authorization.v1beta1.Msg/ExecAuthorized", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) RevokeAuthorization(ctx context.Context, in *MsgRevokeAuthorization, opts ...grpc.CallOption) (*MsgRevokeAuthorizationResponse, error) { + out := new(MsgRevokeAuthorizationResponse) + err := c.cc.Invoke(ctx, "/cosmos.msg_authorization.v1beta1.Msg/RevokeAuthorization", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // GrantAuthorization grants the provided authorization to the grantee on the granter's + // account with the provided expiration time. + GrantAuthorization(context.Context, *MsgGrantAuthorization) (*MsgGrantAuthorizationResponse, error) + // ExecAuthorized attempts to execute the provided messages using + // authorizations granted to the grantee. Each message should have only + // one signer corresponding to the granter of the authorization. + ExecAuthorized(context.Context, *MsgExecAuthorized) (*MsgExecAuthorizedResponse, error) + // RevokeAuthorization revokes any authorization corresponding to the provided method name on the + // granter's account that has been granted to the grantee. + RevokeAuthorization(context.Context, *MsgRevokeAuthorization) (*MsgRevokeAuthorizationResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) GrantAuthorization(ctx context.Context, req *MsgGrantAuthorization) (*MsgGrantAuthorizationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GrantAuthorization not implemented") +} +func (*UnimplementedMsgServer) ExecAuthorized(ctx context.Context, req *MsgExecAuthorized) (*MsgExecAuthorizedResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ExecAuthorized not implemented") +} +func (*UnimplementedMsgServer) RevokeAuthorization(ctx context.Context, req *MsgRevokeAuthorization) (*MsgRevokeAuthorizationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RevokeAuthorization not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_GrantAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgGrantAuthorization) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).GrantAuthorization(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.msg_authorization.v1beta1.Msg/GrantAuthorization", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).GrantAuthorization(ctx, req.(*MsgGrantAuthorization)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_ExecAuthorized_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgExecAuthorized) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).ExecAuthorized(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.msg_authorization.v1beta1.Msg/ExecAuthorized", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).ExecAuthorized(ctx, req.(*MsgExecAuthorized)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_RevokeAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgRevokeAuthorization) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).RevokeAuthorization(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.msg_authorization.v1beta1.Msg/RevokeAuthorization", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).RevokeAuthorization(ctx, req.(*MsgRevokeAuthorization)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.msg_authorization.v1beta1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GrantAuthorization", + Handler: _Msg_GrantAuthorization_Handler, + }, + { + MethodName: "ExecAuthorized", + Handler: _Msg_ExecAuthorized_Handler, + }, + { + MethodName: "RevokeAuthorization", + Handler: _Msg_RevokeAuthorization_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/msg_authorization/v1beta1/tx.proto", +} + +func (m *MsgGrantAuthorization) 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 *MsgGrantAuthorization) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgGrantAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + n1, err1 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Expiration, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Expiration):]) + if err1 != nil { + return 0, err1 + } + i -= n1 + i = encodeVarintTx(dAtA, i, uint64(n1)) + i-- + dAtA[i] = 0x22 + if m.Authorization != nil { + { + size, err := m.Authorization.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if len(m.Grantee) > 0 { + i -= len(m.Grantee) + copy(dAtA[i:], m.Grantee) + i = encodeVarintTx(dAtA, i, uint64(len(m.Grantee))) + i-- + dAtA[i] = 0x12 + } + if len(m.Granter) > 0 { + i -= len(m.Granter) + copy(dAtA[i:], m.Granter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Granter))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgExecAuthorizedResponse) 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 *MsgExecAuthorizedResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgExecAuthorizedResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Result != nil { + { + size, err := m.Result.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgExecAuthorized) 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 *MsgExecAuthorized) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgExecAuthorized) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Msgs) > 0 { + for iNdEx := len(m.Msgs) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Msgs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Grantee) > 0 { + i -= len(m.Grantee) + copy(dAtA[i:], m.Grantee) + i = encodeVarintTx(dAtA, i, uint64(len(m.Grantee))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgGrantAuthorizationResponse) 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 *MsgGrantAuthorizationResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgGrantAuthorizationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgRevokeAuthorization) 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 *MsgRevokeAuthorization) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRevokeAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AuthorizationMsgType) > 0 { + i -= len(m.AuthorizationMsgType) + copy(dAtA[i:], m.AuthorizationMsgType) + i = encodeVarintTx(dAtA, i, uint64(len(m.AuthorizationMsgType))) + i-- + dAtA[i] = 0x1a + } + if len(m.Grantee) > 0 { + i -= len(m.Grantee) + copy(dAtA[i:], m.Grantee) + i = encodeVarintTx(dAtA, i, uint64(len(m.Grantee))) + i-- + dAtA[i] = 0x12 + } + if len(m.Granter) > 0 { + i -= len(m.Granter) + copy(dAtA[i:], m.Granter) + i = encodeVarintTx(dAtA, i, uint64(len(m.Granter))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgRevokeAuthorizationResponse) 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 *MsgRevokeAuthorizationResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRevokeAuthorizationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgGrantAuthorization) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Granter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Grantee) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.Authorization != nil { + l = m.Authorization.Size() + n += 1 + l + sovTx(uint64(l)) + } + l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Expiration) + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgExecAuthorizedResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Result != nil { + l = m.Result.Size() + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgExecAuthorized) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Grantee) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if len(m.Msgs) > 0 { + for _, e := range m.Msgs { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgGrantAuthorizationResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgRevokeAuthorization) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Granter) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Grantee) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.AuthorizationMsgType) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgRevokeAuthorizationResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgGrantAuthorization) 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 ErrIntOverflowTx + } + 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: MsgGrantAuthorization: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgGrantAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Granter", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + 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 ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Granter = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Grantee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + 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 ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Grantee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authorization", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Authorization == nil { + m.Authorization = &types.Any{} + } + if err := m.Authorization.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Expiration", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Expiration, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgExecAuthorizedResponse) 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 ErrIntOverflowTx + } + 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: MsgExecAuthorizedResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgExecAuthorizedResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Result == nil { + m.Result = &types1.Result{} + } + if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgExecAuthorized) 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 ErrIntOverflowTx + } + 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: MsgExecAuthorized: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgExecAuthorized: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Grantee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + 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 ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Grantee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msgs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Msgs = append(m.Msgs, &types.Any{}) + if err := m.Msgs[len(m.Msgs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgGrantAuthorizationResponse) 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 ErrIntOverflowTx + } + 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: MsgGrantAuthorizationResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgGrantAuthorizationResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgRevokeAuthorization) 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 ErrIntOverflowTx + } + 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: MsgRevokeAuthorization: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgRevokeAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Granter", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + 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 ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Granter = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Grantee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + 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 ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Grantee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AuthorizationMsgType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + 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 ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AuthorizationMsgType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgRevokeAuthorizationResponse) 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 ErrIntOverflowTx + } + 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: MsgRevokeAuthorizationResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgRevokeAuthorizationResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(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, ErrIntOverflowTx + } + 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, ErrIntOverflowTx + } + 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, ErrIntOverflowTx + } + 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, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +)