Remove ServiceMsgs from ADR-031 (#9139)

* wip

* wip

* wip

* wip on refactoring adr 031 type URLs

* Fix msg_service_router

* Fix gov client queries

* Fix some modules tests

* Remove all instances of "*.Msg/*"

* Uncomment code

* Remove commented code

* // simulation.NewWeightedOperation(

* Fix CopyTx

* Fix more tests

* Fix x/gov test

* proto.MessageName->sdk.MsgName

* Fix authz tests

* Use MsgRoute in feegrant and staking/authz

* Fix more tests

* Fix sims?

* Add norace tag

* Add CL

* rebuild rosetta api test data

* Update ADR

* Rename MsgRoute -> MsgTypeURL

* Fix codec registration

* Remove sdk.GetLegacySignBytes

* Update types/tx_msg.go

* Update x/authz/simulation/operations.go

* Move LegacyMsg to legacytx

* Update CHANGELOG.md

Co-authored-by: Aaron Craelius <aaron@regen.network>

* Remove NewAnyWithCustomTypeURL

* Keep support for ServiceMsgs

* Fix TxBody UnpackInterfaces

* Fix test

* Address review

* Remove support for ServiceMsg typeURLs

* Fix lint

* Update changelog

* Fix tests

* Use sdk.MsgTypeURL everywhere

* Fix tests

* Fix rosetta, run make rosetta-data

* Fix rosetta thanks to froydi

* Address reviews

* Fix test

* Remove stray log

* Update CL

Co-authored-by: Aaron Craelius <aaronc@users.noreply.github.com>
Co-authored-by: Alessio Treglia <alessio@tendermint.com>
Co-authored-by: Aaron Craelius <aaron@regen.network>
This commit is contained in:
Amaury
2021-04-30 11:00:47 +00:00
committed by GitHub
co-authored by Aaron Craelius Aaron Craelius Alessio Treglia
parent 6fbded9664
commit dfe3e7a8d7
62 changed files with 428 additions and 903 deletions
+3 -21
View File
@@ -251,19 +251,7 @@ func (s *IntegrationTestSuite) TestCLIQueryTxCmd() {
sendTokens := sdk.NewInt64Coin(s.cfg.BondDenom, 10)
// Send coins, try both with legacy Msg and with Msg service.
// Legacy proto Msg.
legacyTxRes, err := bankcli.LegacyGRPCProtoMsgSend(
val.ClientCtx, val.Moniker,
val.Address,
account2.GetAddress(),
sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))),
sdk.NewCoins(sendTokens),
)
s.Require().NoError(err)
s.Require().NoError(s.network.WaitForNextBlock())
// Service Msg.
// Send coins.
out, err := s.createBankMsg(
val, account2.GetAddress(),
sdk.NewCoins(sendTokens),
@@ -292,16 +280,10 @@ func (s *IntegrationTestSuite) TestCLIQueryTxCmd() {
"",
},
{
"happy case (legacy Msg)",
[]string{legacyTxRes.TxResponse.TxHash, fmt.Sprintf("--%s=json", tmcli.OutputFlag)},
false,
"",
},
{
"happy case (service Msg)",
"happy case",
[]string{txRes.TxHash, fmt.Sprintf("--%s=json", tmcli.OutputFlag)},
false,
"/cosmos.bank.v1beta1.Msg/Send",
"/cosmos.bank.v1beta1.MsgSend",
},
}
+19 -1
View File
@@ -16,6 +16,24 @@ import (
"github.com/cosmos/cosmos-sdk/types/tx/signing"
)
// LegacyMsg defines the old interface a message must fulfill, containing
// Amino signing method and legacy router info.
// Deprecated: Please use `Msg` instead.
type LegacyMsg interface {
sdk.Msg
// Get the canonical byte representation of the Msg.
GetSignBytes() []byte
// Return the message type.
// Must be alphanumeric or empty.
Route() string
// Returns a human-readable string for the message, intended for utilization
// within tags
Type() string
}
// StdSignDoc is replay-prevention structure.
// It includes the result of msg.GetSignBytes(),
// as well as the ChainID (prevent cross chain replay)
@@ -38,7 +56,7 @@ func StdSignBytes(chainID string, accnum, sequence, timeout uint64, fee StdFee,
// If msg is a legacy Msg, then GetSignBytes is implemented.
// If msg is a ServiceMsg, then GetSignBytes has graceful support of
// calling GetSignBytes from its underlying Msg.
msgsBytes = append(msgsBytes, json.RawMessage(msg.GetSignBytes()))
msgsBytes = append(msgsBytes, json.RawMessage(msg.(LegacyMsg).GetSignBytes()))
}
bz, err := legacy.Cdc.MarshalJSON(StdSignDoc{
+1 -19
View File
@@ -29,25 +29,7 @@ func (s *StdTxBuilder) GetTx() authsigning.Tx {
// SetMsgs implements TxBuilder.SetMsgs
func (s *StdTxBuilder) SetMsgs(msgs ...sdk.Msg) error {
stdTxMsgs := make([]sdk.Msg, len(msgs))
for i, msg := range msgs {
switch msg := msg.(type) {
case sdk.ServiceMsg:
// Since ServiceMsg isn't registered with amino, we unpack msg.Request
// into a Msg so that it's handled gracefully for the legacy
// GET /txs/{hash} and /txs endpoints.
sdkMsg, ok := msg.Request.(sdk.Msg)
if !ok {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting %T at %d to implement sdk.Msg", msg.Request, i)
}
stdTxMsgs[i] = sdkMsg
default:
// legacy sdk.Msg
stdTxMsgs[i] = msg
}
}
s.Msgs = stdTxMsgs
s.Msgs = msgs
return nil
}
+1 -6
View File
@@ -204,12 +204,7 @@ func (w *wrapper) SetMsgs(msgs ...sdk.Msg) error {
for i, msg := range msgs {
var err error
switch msg := msg.(type) {
case sdk.ServiceMsg:
anys[i], err = codectypes.NewAnyWithCustomTypeURL(msg.Request, msg.MethodName)
default:
anys[i], err = codectypes.NewAnyWithValue(msg)
}
anys[i], err = codectypes.NewAnyWithValue(msg)
if err != nil {
return err
}
+14 -11
View File
@@ -32,6 +32,8 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
)
var bankMsgSendEventAction = fmt.Sprintf("message.action='%s'", sdk.MsgTypeURL(&banktypes.MsgSend{}))
type IntegrationTestSuite struct {
suite.Suite
@@ -192,7 +194,7 @@ func (s IntegrationTestSuite) TestGetTxEvents_GRPC() {
{
"request with order-by",
&tx.GetTxsEventRequest{
Events: []string{"message.action='/cosmos.bank.v1beta1.Msg/Send'"},
Events: []string{bankMsgSendEventAction},
OrderBy: tx.OrderBy_ORDER_BY_ASC,
},
false, "",
@@ -200,14 +202,14 @@ func (s IntegrationTestSuite) TestGetTxEvents_GRPC() {
{
"without pagination",
&tx.GetTxsEventRequest{
Events: []string{"message.action='/cosmos.bank.v1beta1.Msg/Send'"},
Events: []string{bankMsgSendEventAction},
},
false, "",
},
{
"with pagination",
&tx.GetTxsEventRequest{
Events: []string{"message.action='/cosmos.bank.v1beta1.Msg/Send'"},
Events: []string{bankMsgSendEventAction},
Pagination: &query.PageRequest{
CountTotal: false,
Offset: 0,
@@ -219,7 +221,7 @@ func (s IntegrationTestSuite) TestGetTxEvents_GRPC() {
{
"with multi events",
&tx.GetTxsEventRequest{
Events: []string{"message.action='/cosmos.bank.v1beta1.Msg/Send'", "message.module='bank'"},
Events: []string{bankMsgSendEventAction, "message.module='bank'"},
},
false, "",
},
@@ -262,43 +264,43 @@ func (s IntegrationTestSuite) TestGetTxEvents_GRPCGateway() {
},
{
"without pagination",
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s", val.APIAddress, "message.action='/cosmos.bank.v1beta1.Msg/Send'"),
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s", val.APIAddress, bankMsgSendEventAction),
false,
"",
},
{
"with pagination",
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&pagination.offset=%d&pagination.limit=%d", val.APIAddress, "message.action='/cosmos.bank.v1beta1.Msg/Send'", 0, 10),
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&pagination.offset=%d&pagination.limit=%d", val.APIAddress, bankMsgSendEventAction, 0, 10),
false,
"",
},
{
"valid request: order by asc",
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s&order_by=ORDER_BY_ASC", val.APIAddress, "message.action='/cosmos.bank.v1beta1.Msg/Send'", "message.module='bank'"),
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s&order_by=ORDER_BY_ASC", val.APIAddress, bankMsgSendEventAction, "message.module='bank'"),
false,
"",
},
{
"valid request: order by desc",
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s&order_by=ORDER_BY_DESC", val.APIAddress, "message.action='/cosmos.bank.v1beta1.Msg/Send'", "message.module='bank'"),
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s&order_by=ORDER_BY_DESC", val.APIAddress, bankMsgSendEventAction, "message.module='bank'"),
false,
"",
},
{
"invalid request: invalid order by",
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s&order_by=invalid_order", val.APIAddress, "message.action='/cosmos.bank.v1beta1.Msg/Send'", "message.module='bank'"),
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s&order_by=invalid_order", val.APIAddress, bankMsgSendEventAction, "message.module='bank'"),
true,
"is not a valid tx.OrderBy",
},
{
"expect pass with multiple-events",
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s", val.APIAddress, "message.action='/cosmos.bank.v1beta1.Msg/Send'", "message.module='bank'"),
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s&events=%s", val.APIAddress, bankMsgSendEventAction, "message.module='bank'"),
false,
"",
},
{
"expect pass with escape event",
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s", val.APIAddress, "message.action%3D'%2Fcosmos.bank.v1beta1.Msg%2FSend'"),
fmt.Sprintf("%s/cosmos/tx/v1beta1/txs?events=%s", val.APIAddress, "message.action%3D'/cosmos.bank.v1beta1.MsgSend'"),
false,
"",
},
@@ -584,6 +586,7 @@ func (s IntegrationTestSuite) mkTxBuilder() client.TxBuilder {
)
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetGasLimit(gasLimit)
txBuilder.SetMemo("foobar")
// setup txFactory
txFactory := clienttx.Factory{}.
+2 -12
View File
@@ -60,7 +60,7 @@ func NewCmdGrantAuthorization() *cobra.Command {
Examples:
$ %s tx %s grant cosmos1skjw.. send %s --spend-limit=1000stake --from=cosmos1skl..
$ %s tx %s grant cosmos1skjw.. generic --msg-type=/cosmos.gov.v1beta1.Msg/Vote --from=cosmos1sk..
$ %s tx %s grant cosmos1skjw.. generic --msg-type=/cosmos.gov.v1beta1.MsgVote --from=cosmos1sk..
`, version.AppName, types.ModuleName, bank.SendAuthorization{}.MethodName(), version.AppName, types.ModuleName),
),
Args: cobra.ExactArgs(2),
@@ -254,17 +254,7 @@ Example:
if err != nil {
return err
}
msgs := theTx.GetMsgs()
serviceMsgs := make([]sdk.ServiceMsg, len(msgs))
for i, msg := range msgs {
srvMsg, ok := msg.(sdk.ServiceMsg)
if !ok {
return fmt.Errorf("tx contains %T which is not a sdk.ServiceMsg", msg)
}
serviceMsgs[i] = srvMsg
}
msg := types.NewMsgExecAuthorized(grantee, serviceMsgs)
msg := types.NewMsgExecAuthorized(grantee, theTx.GetMsgs())
svcMsgClientConn := &msgservice.ServiceMsgClientConn{}
msgClient := types.NewMsgClient(svcMsgClientConn)
_, err = msgClient.ExecAuthorized(context.Background(), &msg)
+8 -6
View File
@@ -20,6 +20,7 @@ import (
types "github.com/cosmos/cosmos-sdk/x/authz/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
)
type IntegrationTestSuite struct {
@@ -30,7 +31,7 @@ type IntegrationTestSuite struct {
}
var typeMsgSend = banktypes.SendAuthorization{}.MethodName()
var typeMsgVote = "/cosmos.gov.v1beta1.Msg/Vote"
var typeMsgVote = sdk.MsgTypeURL(&govtypes.MsgVote{})
func (s *IntegrationTestSuite) SetupSuite() {
s.T().Log("setting up integration test suite")
@@ -48,7 +49,7 @@ func (s *IntegrationTestSuite) SetupSuite() {
newAddr := sdk.AccAddress(info.GetPubKey().Address())
// Send some funds to the new account.
_, err = banktestutil.MsgSendExec(
out, err := banktestutil.MsgSendExec(
val.ClientCtx,
val.Address,
newAddr,
@@ -57,9 +58,10 @@ func (s *IntegrationTestSuite) SetupSuite() {
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
)
s.Require().NoError(err)
s.Require().Contains(out.String(), `"code":0`)
// grant authorization
_, err = authztestutil.ExecGrantAuthorization(val, []string{
out, err = authztestutil.ExecGrantAuthorization(val, []string{
newAddr.String(),
"send",
fmt.Sprintf("--%s=100steak", cli.FlagSpendLimit),
@@ -70,6 +72,7 @@ func (s *IntegrationTestSuite) SetupSuite() {
fmt.Sprintf("--%s=%d", cli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()),
})
s.Require().NoError(err)
s.Require().Contains(out.String(), `"code":0`)
s.grantee = newAddr
_, err = s.network.WaitForHeight(1)
@@ -185,10 +188,9 @@ func (s *IntegrationTestSuite) TestQueryAuthorizationsGRPC() {
fmt.Sprintf("%s/cosmos/authz/v1beta1/granters/%s/grantees/%s/grants", baseURL, val.Address.String(), s.grantee.String()),
false,
"",
func() {
},
func() {},
func(authorizations *types.QueryAuthorizationsResponse) {
s.Require().Equal(len(authorizations.Authorizations), 1)
s.Require().Len(authorizations.Authorizations), 1)
},
},
{
+23 -29
View File
@@ -5,25 +5,22 @@ import (
"time"
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"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"
"github.com/cosmos/cosmos-sdk/x/authz/client/cli"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli"
govtestutil "github.com/cosmos/cosmos-sdk/x/gov/client/testutil"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
stakingcli "github.com/cosmos/cosmos-sdk/x/staking/client/cli"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/client/testutil"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
)
type IntegrationTestSuite struct {
@@ -81,7 +78,7 @@ func (s *IntegrationTestSuite) TearDownSuite() {
}
var typeMsgSend = bank.SendAuthorization{}.MethodName()
var typeMsgVote = "/cosmos.gov.v1beta1.Msg/Vote"
var typeMsgVote = sdk.MsgTypeURL(&govtypes.MsgVote{})
func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
val := s.network.Validators[0]
@@ -93,7 +90,6 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
testCases := []struct {
name string
args []string
respType proto.Message
expectedCode uint32
expectErr bool
}{
@@ -107,7 +103,6 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=true", flags.FlagGenerateOnly),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
},
nil,
0,
true,
},
@@ -121,7 +116,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=true", flags.FlagGenerateOnly),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
},
nil, 0,
0,
true,
},
{
@@ -134,7 +129,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=true", flags.FlagGenerateOnly),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, pastHour),
},
nil, 0,
0,
true,
},
{
@@ -149,8 +144,8 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours),
},
nil, 0,
true,
0x1d,
false,
},
{
"failed with error both validators not allowed",
@@ -166,7 +161,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, val.ValAddress.String()),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
nil, 0,
0,
true,
},
{
@@ -182,7 +177,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
0,
false,
},
{
@@ -198,7 +193,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, val.ValAddress.String()),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
0,
false,
},
{
@@ -214,7 +209,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
0,
false,
},
{
@@ -230,7 +225,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, val.ValAddress.String()),
fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
&sdk.TxResponse{}, 0,
0,
false,
},
{
@@ -245,7 +240,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
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,
0,
false,
},
{
@@ -260,7 +255,7 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
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,
0,
false,
},
}
@@ -276,9 +271,9 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() {
if tc.expectErr {
s.Require().Error(err)
} else {
var txResp sdk.TxResponse
s.Require().NoError(err)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), tc.respType), out.String())
txResp := tc.respType.(*sdk.TxResponse)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), &txResp), out.String())
s.Require().Equal(tc.expectedCode, txResp.Code, out.String())
}
})
@@ -427,7 +422,7 @@ func (s *IntegrationTestSuite) TestExecAuthorizationWithExpiration() {
)
s.Require().NoError(err)
// msg vote
voteTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.gov.v1beta1.Msg/Vote","proposal_id":"1","voter":"%s","option":"VOTE_OPTION_YES"}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String())
voteTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.gov.v1beta1.MsgVote","proposal_id":"1","voter":"%s","option":"VOTE_OPTION_YES"}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String())
execMsg := testutil.WriteToNewTempFile(s.T(), voteTx)
// waiting for authorization to expires
@@ -468,7 +463,7 @@ func (s *IntegrationTestSuite) TestNewExecGenericAuthorized() {
s.Require().NoError(err)
// msg vote
voteTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.gov.v1beta1.Msg/Vote","proposal_id":"1","voter":"%s","option":"VOTE_OPTION_YES"}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String())
voteTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.gov.v1beta1.MsgVote","proposal_id":"1","voter":"%s","option":"VOTE_OPTION_YES"}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String())
execMsg := testutil.WriteToNewTempFile(s.T(), voteTx)
testCases := []struct {
@@ -646,7 +641,7 @@ func (s *IntegrationTestSuite) TestExecDelegateAuthorization() {
sdk.NewCoin("stake", sdk.NewInt(50)),
)
delegateTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Delegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
delegateTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.MsgDelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg := testutil.WriteToNewTempFile(s.T(), delegateTx)
@@ -736,7 +731,7 @@ func (s *IntegrationTestSuite) TestExecDelegateAuthorization() {
sdk.NewCoin("stake", sdk.NewInt(50)),
)
delegateTx = fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Delegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
delegateTx = fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.MsgDelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg = testutil.WriteToNewTempFile(s.T(), delegateTx)
@@ -822,7 +817,6 @@ func (s *IntegrationTestSuite) TestExecDelegateAuthorization() {
out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, args)
s.Require().NoError(err)
s.Contains(out.String(), fmt.Sprintf("cannot delegate/undelegate to %s validator", val.ValAddress.String()))
}
func (s *IntegrationTestSuite) TestExecUndelegateAuthorization() {
@@ -865,7 +859,7 @@ func (s *IntegrationTestSuite) TestExecUndelegateAuthorization() {
sdk.NewCoin("stake", sdk.NewInt(50)),
)
undelegateTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Undelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
undelegateTx := fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.MsgUndelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg := testutil.WriteToNewTempFile(s.T(), undelegateTx)
@@ -955,7 +949,7 @@ func (s *IntegrationTestSuite) TestExecUndelegateAuthorization() {
sdk.NewCoin("stake", sdk.NewInt(50)),
)
undelegateTx = fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.Msg/Undelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
undelegateTx = fmt.Sprintf(`{"body":{"messages":[{"@type":"/cosmos.staking.v1beta1.MsgUndelegate","delegator_address":"%s","validator_address":"%s","amount":{"denom":"%s","amount":"%s"}}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}`, val.Address.String(), val.ValAddress.String(),
tokens.GetDenomByIndex(0), tokens[0].Amount)
execMsg = testutil.WriteToNewTempFile(s.T(), undelegateTx)
+1 -1
View File
@@ -15,7 +15,7 @@ type Authorization interface {
// Accept determines whether this grant permits the provided sdk.ServiceMsg to be performed, and if
// so provides an upgraded authorization instance.
Accept(ctx sdk.Context, msg sdk.ServiceMsg) (updated Authorization, delete bool, err error)
Accept(ctx sdk.Context, msg sdk.Msg) (updated Authorization, delete bool, err error)
// ValidateBasic does a simple validation check that
// doesn't require access to any other information.
+13 -10
View File
@@ -73,26 +73,29 @@ func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccA
// 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, serviceMsgs []sdk.ServiceMsg) (*sdk.Result, error) {
func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, msgs []sdk.Msg) (*sdk.Result, error) {
var msgResult *sdk.Result
var err error
for _, serviceMsg := range serviceMsgs {
signers := serviceMsg.GetSigners()
for _, msg := range msgs {
signers := msg.GetSigners()
if len(signers) != 1 {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "authorization can be given to msg with only one signer")
}
granter := signers[0]
if !granter.Equals(grantee) {
authorization, _ := k.GetOrRevokeAuthorization(ctx, grantee, granter, serviceMsg.MethodName)
authorization, _ := k.GetOrRevokeAuthorization(ctx, grantee, granter, sdk.MsgTypeURL(msg))
if authorization == nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "authorization not found")
}
updated, del, err := authorization.Accept(ctx, serviceMsg)
updated, del, err := authorization.Accept(ctx, msg)
if err != nil {
return nil, err
}
if del {
k.Revoke(ctx, grantee, granter, serviceMsg.Type())
err = k.Revoke(ctx, grantee, granter, sdk.MsgTypeURL(msg))
if err != nil {
return nil, err
}
} else if updated != nil {
err = k.update(ctx, grantee, granter, updated)
if err != nil {
@@ -100,15 +103,15 @@ func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, service
}
}
}
handler := k.router.Handler(serviceMsg.Route())
handler := k.router.Handler(msg)
if handler == nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized message route: %s", serviceMsg.Route())
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized message route: %s", sdk.MsgTypeURL(msg))
}
msgResult, err = handler(ctx, serviceMsg.Request)
msgResult, err = handler(ctx, msg)
if err != nil {
return nil, sdkerrors.Wrapf(err, "failed to execute message; message %s", serviceMsg.MethodName)
return nil, sdkerrors.Wrapf(err, "failed to execute message; message %v", msg)
}
}
+16 -27
View File
@@ -4,15 +4,11 @@ import (
"testing"
"time"
proto "github.com/gogo/protobuf/proto"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/stretchr/testify/suite"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz/types"
@@ -42,7 +38,6 @@ func (s *TestSuite) SetupTest() {
s.ctx = ctx
s.queryClient = queryClient
s.addrs = simapp.AddTestAddrsIncremental(app, ctx, 3, sdk.NewInt(30000000))
}
func (s *TestSuite) TestKeeper() {
@@ -76,7 +71,7 @@ func (s *TestSuite) TestKeeper() {
s.Require().Equal(authorization.MethodName(), banktypes.SendAuthorization{}.MethodName())
s.T().Log("verify fetching authorization with wrong msg type fails")
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, proto.MessageName(&banktypes.MsgMultiSend{}))
authorization, _ = app.AuthzKeeper.GetOrRevokeAuthorization(ctx, granteeAddr, granterAddr, sdk.MsgTypeURL(&banktypes.MsgMultiSend{}))
s.Require().Nil(authorization)
s.T().Log("verify fetching authorization with wrong grantee fails")
@@ -139,21 +134,18 @@ func (s *TestSuite) TestKeeperFees() {
smallCoin := sdk.NewCoins(sdk.NewInt64Coin("steak", 20))
someCoin := sdk.NewCoins(sdk.NewInt64Coin("steak", 123))
msgs := types.NewMsgExecAuthorized(granteeAddr, []sdk.ServiceMsg{
{
MethodName: banktypes.SendAuthorization{}.MethodName(),
Request: &banktypes.MsgSend{
Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)),
FromAddress: granterAddr.String(),
ToAddress: recipientAddr.String(),
},
msgs := types.NewMsgExecAuthorized(granteeAddr, []sdk.Msg{
&banktypes.MsgSend{
Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)),
FromAddress: granterAddr.String(),
ToAddress: recipientAddr.String(),
},
})
s.Require().NoError(msgs.UnpackInterfaces(app.AppCodec()))
s.T().Log("verify dispatch fails with invalid authorization")
executeMsgs, err := msgs.GetServiceMsgs()
executeMsgs, err := msgs.GetMessages()
s.Require().NoError(err)
result, err := app.AuthzKeeper.DispatchActions(s.ctx, granteeAddr, executeMsgs)
@@ -169,7 +161,7 @@ func (s *TestSuite) TestKeeperFees() {
s.Require().Equal(authorization.MethodName(), banktypes.SendAuthorization{}.MethodName())
executeMsgs, err = msgs.GetServiceMsgs()
executeMsgs, err = msgs.GetMessages()
s.Require().NoError(err)
result, err = app.AuthzKeeper.DispatchActions(s.ctx, granteeAddr, executeMsgs)
@@ -182,19 +174,16 @@ func (s *TestSuite) TestKeeperFees() {
s.T().Log("verify dispatch fails with overlimit")
// grant authorization
msgs = types.NewMsgExecAuthorized(granteeAddr, []sdk.ServiceMsg{
{
MethodName: banktypes.SendAuthorization{}.MethodName(),
Request: &banktypes.MsgSend{
Amount: someCoin,
FromAddress: granterAddr.String(),
ToAddress: recipientAddr.String(),
},
msgs = types.NewMsgExecAuthorized(granteeAddr, []sdk.Msg{
&banktypes.MsgSend{
Amount: someCoin,
FromAddress: granterAddr.String(),
ToAddress: recipientAddr.String(),
},
})
s.Require().NoError(msgs.UnpackInterfaces(app.AppCodec()))
executeMsgs, err = msgs.GetServiceMsgs()
executeMsgs, err = msgs.GetMessages()
s.Require().NoError(err)
result, err = app.AuthzKeeper.DispatchActions(s.ctx, granteeAddr, executeMsgs)
+2 -2
View File
@@ -24,7 +24,7 @@ func (k Keeper) GrantAuthorization(goCtx context.Context, msg *types.MsgGrantAut
authorization := msg.GetGrantAuthorization()
// If the granted service Msg doesn't exist, we throw an error.
if k.router.Handler(authorization.MethodName()) == nil {
if k.router.HandlerbyTypeURL(authorization.MethodName()) == nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "%s doesn't exist.", authorization.MethodName())
}
@@ -63,7 +63,7 @@ func (k Keeper) ExecAuthorized(goCtx context.Context, msg *types.MsgExecAuthoriz
if err != nil {
return nil, err
}
msgs, err := msg.GetServiceMsgs()
msgs, err := msg.GetMessages()
if err != nil {
return nil, err
}
+13 -14
View File
@@ -20,10 +20,12 @@ import (
)
// authz message types
const (
TypeMsgGrantAuthorization = "/cosmos.authz.v1beta1.Msg/GrantAuthorization"
TypeMsgRevokeAuthorization = "/cosmos.authz.v1beta1.Msg/RevokeAuthorization"
TypeMsgExecDelegated = "/cosmos.authz.v1beta1.Msg/ExecAuthorized"
var (
// TODO Remove `Request` suffix
// https://github.com/cosmos/cosmos-sdk/issues/9114
TypeMsgGrantAuthorization = sdk.MsgTypeURL(&types.MsgGrantAuthorizationRequest{})
TypeMsgRevokeAuthorization = sdk.MsgTypeURL(&types.MsgRevokeAuthorizationRequest{})
TypeMsgExecDelegated = sdk.MsgTypeURL(&types.MsgExecAuthorizedRequest{})
)
// Simulation operation weights constants
@@ -130,7 +132,7 @@ func SimulateMsgGrantAuthorization(ak types.AccountKeeper, bk types.BankKeeper,
_, _, err = app.Deliver(txGen.TxEncoder(), tx)
if err != nil {
return simtypes.NoOpMsg(types.ModuleName, svcMsgClientConn.GetMsgs()[0].Type(), "unable to deliver tx"), nil, err
return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(svcMsgClientConn.GetMsgs()[0]), "unable to deliver tx"), nil, err
}
return simtypes.NewOperationMsg(svcMsgClientConn.GetMsgs()[0], true, "", protoCdc), nil, err
}
@@ -242,16 +244,13 @@ func SimulateMsgExecuteAuthorized(ak types.AccountKeeper, bk types.BankKeeper, k
}
sendCoins := sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(10)))
execMsg := sdk.ServiceMsg{
MethodName: banktype.SendAuthorization{}.MethodName(),
Request: banktype.NewMsgSend(
granterAddr,
granteeAddr,
sendCoins,
),
}
execMsg := banktype.NewMsgSend(
granterAddr,
granteeAddr,
sendCoins,
)
msg := types.NewMsgExecAuthorized(grantee.Address, []sdk.ServiceMsg{execMsg})
msg := types.NewMsgExecAuthorized(grantee.Address, []sdk.Msg{execMsg})
sendGrant := targetGrant.Authorization.GetCachedValue().(*banktype.SendAuthorization)
_, _, err = sendGrant.Accept(ctx, execMsg)
if err != nil {
+1 -1
View File
@@ -11,7 +11,7 @@ import (
// RegisterInterfaces registers the interfaces types with the interface registry
func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterImplementations((*sdk.MsgRequest)(nil),
registry.RegisterImplementations((*sdk.Msg)(nil),
&MsgGrantAuthorizationRequest{},
&MsgRevokeAuthorizationRequest{},
&MsgExecAuthorizedRequest{},
+1 -6
View File
@@ -2,8 +2,6 @@ package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/msgservice"
"github.com/cosmos/cosmos-sdk/x/authz/exported"
)
@@ -24,14 +22,11 @@ func (authorization GenericAuthorization) MethodName() string {
}
// Accept implements Authorization.Accept.
func (authorization GenericAuthorization) Accept(ctx sdk.Context, msg sdk.ServiceMsg) (updated exported.Authorization, delete bool, err error) {
func (authorization GenericAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (updated exported.Authorization, delete bool, err error) {
return &authorization, false, nil
}
// ValidateBasic implements Authorization.ValidateBasic.
func (authorization GenericAuthorization) ValidateBasic() error {
if !msgservice.IsServiceMsg(authorization.MessageName) {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, " %s is not a valid service msg", authorization.MessageName)
}
return nil
}
+1 -5
View File
@@ -10,12 +10,8 @@ import (
)
func TestGenericAuthorization(t *testing.T) {
t.Log("verify ValidateBasic returns error for non-service msg")
authorization := types.NewGenericAuthorization(banktypes.TypeMsgSend)
require.Error(t, authorization.ValidateBasic())
t.Log("verify ValidateBasic returns nil for service msg")
authorization = types.NewGenericAuthorization(banktypes.SendAuthorization{}.MethodName())
authorization := types.NewGenericAuthorization(banktypes.SendAuthorization{}.MethodName())
require.NoError(t, authorization.ValidateBasic())
require.Equal(t, banktypes.SendAuthorization{}.MethodName(), authorization.MessageName)
}
+12 -22
View File
@@ -12,9 +12,9 @@ import (
)
var (
_ sdk.MsgRequest = &MsgGrantAuthorizationRequest{}
_ sdk.MsgRequest = &MsgRevokeAuthorizationRequest{}
_ sdk.MsgRequest = &MsgExecAuthorizedRequest{}
_ sdk.Msg = &MsgGrantAuthorizationRequest{}
_ sdk.Msg = &MsgRevokeAuthorizationRequest{}
_ sdk.Msg = &MsgExecAuthorizedRequest{}
_ types.UnpackInterfacesMessage = &MsgGrantAuthorizationRequest{}
_ types.UnpackInterfacesMessage = &MsgExecAuthorizedRequest{}
@@ -96,7 +96,7 @@ func (msg *MsgGrantAuthorizationRequest) SetAuthorization(authorization exported
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (msg MsgExecAuthorizedRequest) UnpackInterfaces(unpacker types.AnyUnpacker) error {
for _, x := range msg.Msgs {
var msgExecAuthorized sdk.MsgRequest
var msgExecAuthorized sdk.Msg
err := unpacker.UnpackAny(x, &msgExecAuthorized)
if err != nil {
return err
@@ -155,20 +155,15 @@ func (msg MsgRevokeAuthorizationRequest) ValidateBasic() error {
// NewMsgExecAuthorized creates a new MsgExecAuthorized
//nolint:interfacer
func NewMsgExecAuthorized(grantee sdk.AccAddress, msgs []sdk.ServiceMsg) MsgExecAuthorizedRequest {
func NewMsgExecAuthorized(grantee sdk.AccAddress, msgs []sdk.Msg) MsgExecAuthorizedRequest {
msgsAny := make([]*types.Any, len(msgs))
for i, msg := range msgs {
bz, err := proto.Marshal(msg.Request)
any, err := types.NewAnyWithValue(msg)
if err != nil {
panic(err)
}
anyMsg := &types.Any{
TypeUrl: msg.MethodName,
Value: bz,
}
msgsAny[i] = anyMsg
msgsAny[i] = any
}
return MsgExecAuthorizedRequest{
@@ -177,20 +172,15 @@ func NewMsgExecAuthorized(grantee sdk.AccAddress, msgs []sdk.ServiceMsg) MsgExec
}
}
// GetServiceMsgs returns the cache values from the MsgExecAuthorized.Msgs if present.
func (msg MsgExecAuthorizedRequest) GetServiceMsgs() ([]sdk.ServiceMsg, error) {
msgs := make([]sdk.ServiceMsg, len(msg.Msgs))
// GetMessages returns the cache values from the MsgExecAuthorized.Msgs if present.
func (msg MsgExecAuthorizedRequest) GetMessages() ([]sdk.Msg, error) {
msgs := make([]sdk.Msg, len(msg.Msgs))
for i, msgAny := range msg.Msgs {
msgReq, ok := msgAny.GetCachedValue().(sdk.MsgRequest)
msg, ok := msgAny.GetCachedValue().(sdk.Msg)
if !ok {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "messages contains %T which is not a sdk.MsgRequest", msgAny)
}
srvMsg := sdk.ServiceMsg{
MethodName: msgAny.TypeUrl,
Request: msgReq,
}
msgs[i] = srvMsg
msgs[i] = msg
}
return msgs, nil
+8 -11
View File
@@ -23,19 +23,16 @@ func TestMsgExecAuthorized(t *testing.T) {
tests := []struct {
title string
grantee sdk.AccAddress
msgs []sdk.ServiceMsg
msgs []sdk.Msg
expectPass bool
}{
{"nil grantee address", nil, []sdk.ServiceMsg{}, false},
{"zero-messages test: should fail", grantee, []sdk.ServiceMsg{}, false},
{"valid test: msg type", grantee, []sdk.ServiceMsg{
{
MethodName: banktypes.SendAuthorization{}.MethodName(),
Request: &banktypes.MsgSend{
Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)),
FromAddress: granter.String(),
ToAddress: grantee.String(),
},
{"nil grantee address", nil, []sdk.Msg{}, false},
{"zero-messages test: should fail", grantee, []sdk.Msg{}, false},
{"valid test: msg type", grantee, []sdk.Msg{
&banktypes.MsgSend{
Amount: sdk.NewCoins(sdk.NewInt64Coin("steak", 2)),
FromAddress: granter.String(),
ToAddress: grantee.String(),
},
}, true},
}
-61
View File
@@ -1,22 +1,14 @@
package testutil
import (
"context"
"fmt"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/testutil"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/cli"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
func MsgSendExec(clientCtx client.Context, from, to, amount fmt.Stringer, extraArgs ...string) (testutil.BufferWriter, error) {
@@ -32,56 +24,3 @@ func QueryBalancesExec(clientCtx client.Context, address fmt.Stringer, extraArgs
return clitestutil.ExecTestCLICmd(clientCtx, bankcli.GetBalancesCmd(), args)
}
// LegacyGRPCProtoMsgSend is a legacy method to broadcast a legacy proto MsgSend.
//
// Deprecated.
//nolint:interfacer
func LegacyGRPCProtoMsgSend(clientCtx client.Context, keyName string, from, to sdk.Address, fee, amount []sdk.Coin, extraArgs ...string) (*txtypes.BroadcastTxResponse, error) {
// prepare txBuilder with msg
txBuilder := clientCtx.TxConfig.NewTxBuilder()
feeAmount := fee
gasLimit := testdata.NewTestGasLimit()
// This sets a legacy Proto MsgSend.
err := txBuilder.SetMsgs(&types.MsgSend{
FromAddress: from.String(),
ToAddress: to.String(),
Amount: amount,
})
if err != nil {
return nil, err
}
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetGasLimit(gasLimit)
// setup txFactory
txFactory := tx.Factory{}.
WithChainID(clientCtx.ChainID).
WithKeybase(clientCtx.Keyring).
WithTxConfig(clientCtx.TxConfig).
WithSignMode(signing.SignMode_SIGN_MODE_DIRECT)
// Sign Tx.
err = authclient.SignTx(txFactory, clientCtx, keyName, txBuilder, false, true)
if err != nil {
return nil, err
}
txBytes, err := clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx())
if err != nil {
return nil, err
}
// Broadcast the tx via gRPC.
queryClient := txtypes.NewServiceClient(clientCtx)
return queryClient.BroadcastTx(
context.Background(),
&txtypes.BroadcastTxRequest{
Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC,
TxBytes: txBytes,
},
)
}
+1 -60
View File
@@ -383,10 +383,7 @@ func (s *IntegrationTestSuite) TestNewSendTxCmdGenOnly() {
s.Require().NoError(err)
tx, err := s.cfg.TxConfig.TxJSONDecoder()(bz.Bytes())
s.Require().NoError(err)
s.Require().Equal([]sdk.Msg{sdk.ServiceMsg{
MethodName: "/cosmos.bank.v1beta1.Msg/Send",
Request: types.NewMsgSend(from, to, amount),
}}, tx.GetMsgs())
s.Require().Equal([]sdk.Msg{types.NewMsgSend(from, to, amount)}, tx.GetMsgs())
}
func (s *IntegrationTestSuite) TestNewSendTxCmd() {
@@ -473,62 +470,6 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() {
}
}
// TestBankMsgService does a basic test of whether or not service Msg's as defined
// in ADR 031 work in the most basic end-to-end case.
func (s *IntegrationTestSuite) TestBankMsgService() {
val := s.network.Validators[0]
testCases := []struct {
name string
from, to sdk.AccAddress
amount sdk.Coins
args []string
expectErr bool
expectedCode uint32
respType proto.Message
rawLogContains string
}{
{
"valid transaction",
val.Address,
val.Address,
sdk.NewCoins(
sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)),
sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)),
),
[]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(s.cfg.BondDenom, sdk.NewInt(10))).String()),
},
false,
0,
&sdk.TxResponse{},
"/cosmos.bank.v1beta1.Msg/Send", // indicates we are using ServiceMsg and not a regular Msg
},
}
for _, tc := range testCases {
tc := tc
s.Run(tc.name, func() {
clientCtx := val.ClientCtx
bz, err := MsgSendExec(clientCtx, tc.from, tc.to, tc.amount, tc.args...)
if tc.expectErr {
s.Require().Error(err)
} else {
s.Require().NoError(err)
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(bz.Bytes(), tc.respType), bz.String())
txResp := tc.respType.(*sdk.TxResponse)
s.Require().Equal(tc.expectedCode, txResp.Code)
s.Require().Contains(txResp.RawLog, tc.rawLogContains)
}
})
}
}
func NewCoin(denom string, amount sdk.Int) *sdk.Coin {
coin := sdk.NewCoin(denom, amount)
return &coin
+15 -18
View File
@@ -1,8 +1,6 @@
package types
import (
"reflect"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authz "github.com/cosmos/cosmos-sdk/x/authz/exported"
@@ -21,26 +19,25 @@ func NewSendAuthorization(spendLimit sdk.Coins) *SendAuthorization {
// MethodName implements Authorization.MethodName.
func (authorization SendAuthorization) MethodName() string {
return "/cosmos.bank.v1beta1.Msg/Send"
return sdk.MsgTypeURL(&MsgSend{})
}
// Accept implements Authorization.Accept.
func (authorization SendAuthorization) Accept(ctx sdk.Context, msg sdk.ServiceMsg) (updated authz.Authorization, delete bool, err error) {
if reflect.TypeOf(msg.Request) == reflect.TypeOf(&MsgSend{}) {
msg, ok := msg.Request.(*MsgSend)
if ok {
limitLeft, isNegative := authorization.SpendLimit.SafeSub(msg.Amount)
if isNegative {
return nil, false, sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "requested amount is more than spend limit")
}
if limitLeft.IsZero() {
return nil, true, nil
}
return &SendAuthorization{SpendLimit: limitLeft}, false, nil
}
func (authorization SendAuthorization) Accept(_ sdk.Context, msg sdk.Msg) (updated authz.Authorization, delete bool, err error) {
msgSend, ok := msg.(*MsgSend)
if !ok {
return nil, false, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "type mismatch")
}
return nil, false, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "type mismatch")
limitLeft, isNegative := authorization.SpendLimit.SafeSub(msgSend.Amount)
if isNegative {
return nil, false, sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "requested amount is more than spend limit")
}
if limitLeft.IsZero() {
return nil, true, nil
}
return &SendAuthorization{SpendLimit: limitLeft}, false, nil
}
// ValidateBasic implements Authorization.ValidateBasic.
+6 -13
View File
@@ -24,31 +24,24 @@ func TestSendAuthorization(t *testing.T) {
authorization := types.NewSendAuthorization(coins1000)
t.Log("verify authorization returns valid method name")
require.Equal(t, authorization.MethodName(), "/cosmos.bank.v1beta1.Msg/Send")
require.Equal(t, authorization.MethodName(), "/cosmos.bank.v1beta1.MsgSend")
require.NoError(t, authorization.ValidateBasic())
send := types.NewMsgSend(fromAddr, toAddr, coins1000)
srvMsg := sdk.ServiceMsg{
MethodName: "/cosmos.bank.v1beta1.Msg/Send",
Request: send,
}
require.NoError(t, authorization.ValidateBasic())
t.Log("verify updated authorization returns nil")
updated, del, err := authorization.Accept(ctx, srvMsg)
updated, del, err := authorization.Accept(ctx, send)
require.NoError(t, err)
require.True(t, del)
require.Nil(t, updated)
authorization = types.NewSendAuthorization(coins1000)
require.Equal(t, authorization.MethodName(), "/cosmos.bank.v1beta1.Msg/Send")
require.Equal(t, authorization.MethodName(), "/cosmos.bank.v1beta1.MsgSend")
require.NoError(t, authorization.ValidateBasic())
send = types.NewMsgSend(fromAddr, toAddr, coins500)
srvMsg = sdk.ServiceMsg{
MethodName: "/cosmos.bank.v1beta1.Msg/Send",
Request: send,
}
require.NoError(t, authorization.ValidateBasic())
updated, del, err = authorization.Accept(ctx, srvMsg)
updated, del, err = authorization.Accept(ctx, send)
t.Log("verify updated authorization returns remaining spent limit")
require.NoError(t, err)
@@ -58,7 +51,7 @@ func TestSendAuthorization(t *testing.T) {
require.Equal(t, sendAuth.String(), updated.String())
t.Log("expect updated authorization nil after spending remaining amount")
updated, del, err = updated.Accept(ctx, srvMsg)
updated, del, err = updated.Accept(ctx, send)
require.NoError(t, err)
require.True(t, del)
require.Nil(t, updated)
+3 -2
View File
@@ -8,6 +8,7 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
"github.com/cosmos/cosmos-sdk/x/evidence/exported"
"github.com/cosmos/cosmos-sdk/x/evidence/types"
)
@@ -50,8 +51,8 @@ func TestMsgSubmitEvidence(t *testing.T) {
}
for i, tc := range testCases {
require.Equal(t, tc.msg.Route(), types.RouterKey, "unexpected result for tc #%d", i)
require.Equal(t, tc.msg.Type(), types.TypeMsgSubmitEvidence, "unexpected result for tc #%d", i)
require.Equal(t, tc.msg.(legacytx.LegacyMsg).Route(), types.RouterKey, "unexpected result for tc #%d", i)
require.Equal(t, tc.msg.(legacytx.LegacyMsg).Type(), types.TypeMsgSubmitEvidence, "unexpected result for tc #%d", i)
require.Equal(t, tc.expectErr, tc.msg.ValidateBasic() != nil, "unexpected result for tc #%d", i)
if !tc.expectErr {
+1 -1
View File
@@ -58,7 +58,7 @@ Examples:
%s tx %s grant cosmos1skjw... cosmos1skjw... --spend-limit 100stake --expiration 2022-01-30T15:04:05Z or
%s tx %s grant cosmos1skjw... cosmos1skjw... --spend-limit 100stake --period 3600 --period-limit 10stake --expiration 36000 or
%s tx %s grant cosmos1skjw... cosmos1skjw... --spend-limit 100stake --expiration 2022-01-30T15:04:05Z
--allowed-messages "/cosmos.gov.v1beta1.Msg/SubmitProposal,/cosmos.gov.v1beta1.Msg/Vote"
--allowed-messages "/cosmos.gov.v1beta1.MsgSubmitProposal,/cosmos.gov.v1beta1.MsgVote"
`, version.AppName, types.ModuleName, version.AppName, types.ModuleName, version.AppName, types.ModuleName,
),
),
+2 -1
View File
@@ -2,6 +2,7 @@ package testutil
import (
"fmt"
"strings"
"testing"
"time"
@@ -649,7 +650,7 @@ func (s *IntegrationTestSuite) TestFilteredFeeAllowance() {
}
spendLimit := sdk.NewCoin("stake", sdk.NewInt(1000))
allowMsgs := "/cosmos.gov.v1beta1.Msg/SubmitProposal,weighted_vote"
allowMsgs := strings.Join([]string{sdk.MsgTypeURL(&govtypes.MsgSubmitProposal{}), sdk.MsgTypeURL(&govtypes.MsgVoteWeighted{})}, ",")
testCases := []struct {
name string
+1 -1
View File
@@ -52,7 +52,7 @@ func generateRandomAllowances(granter, grantee sdk.AccAddress, r *rand.Rand) typ
filteredAllowance, err := types.NewFeeAllowanceGrant(granter, grantee, &types.AllowedMsgFeeAllowance{
Allowance: basicAllowance.GetAllowance(),
AllowedMessages: []string{"/cosmos.gov.v1beta1.Msg/SubmitProposal"},
AllowedMessages: []string{"/cosmos.gov.v1beta1.MsgSubmitProposal"},
})
if err != nil {
panic(err)
+6 -3
View File
@@ -21,8 +21,11 @@ import (
const (
OpWeightMsgGrantFeeAllowance = "op_weight_msg_grant_fee_allowance"
OpWeightMsgRevokeFeeAllowance = "op_weight_msg_grant_revoke_allowance"
TypeMsgGrantFeeAllowance = "/cosmos.feegrant.v1beta1.Msg/GrantFeeAllowance"
TypeMsgRevokeFeeAllowance = "/cosmos.feegrant.v1beta1.Msg/RevokeFeeAllowance"
)
var (
TypeMsgGrantFeeAllowance = sdk.MsgTypeURL(&types.MsgGrantFeeAllowance{})
TypeMsgRevokeFeeAllowance = sdk.MsgTypeURL(&types.MsgRevokeFeeAllowance{})
)
func WeightedOperations(
@@ -121,7 +124,7 @@ func SimulateMsgGrantFeeAllowance(ak types.AccountKeeper, bk types.BankKeeper, k
_, _, err = app.Deliver(txGen.TxEncoder(), tx)
if err != nil {
return simtypes.NoOpMsg(types.ModuleName, svcMsgClientConn.GetMsgs()[0].Type(), "unable to deliver tx"), nil, err
return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(svcMsgClientConn.GetMsgs()[0]), "unable to deliver tx"), nil, err
}
return simtypes.NewOperationMsg(svcMsgClientConn.GetMsgs()[0], true, "", protoCdc), nil, err
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
// RegisterInterfaces registers the interfaces types with the interface registry
func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterImplementations((*sdk.MsgRequest)(nil),
registry.RegisterImplementations((*sdk.Msg)(nil),
&MsgGrantFeeAllowance{},
&MsgRevokeFeeAllowance{},
)
+1 -1
View File
@@ -80,7 +80,7 @@ func (a *AllowedMsgFeeAllowance) allMsgTypesAllowed(ctx sdk.Context, msgs []sdk.
for _, msg := range msgs {
ctx.GasMeter().ConsumeGas(gasCostPerIteration, "check msg")
if !msgsMap[msg.Type()] {
if !msgsMap[sdk.MsgTypeURL(msg)] {
return false
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
)
var (
_, _ sdk.MsgRequest = &MsgGrantFeeAllowance{}, &MsgRevokeFeeAllowance{}
_, _ sdk.Msg = &MsgGrantFeeAllowance{}, &MsgRevokeFeeAllowance{}
_ types.UnpackInterfacesMessage = &MsgGrantFeeAllowance{}
)
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/network"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
"github.com/cosmos/cosmos-sdk/x/staking/types"
@@ -84,7 +85,7 @@ func (s *IntegrationTestSuite) TestGenTxCmd() {
msgs := tx.GetMsgs()
s.Require().Len(msgs, 1)
s.Require().Equal(types.TypeMsgCreateValidator, msgs[0].Type())
s.Require().Equal(types.TypeMsgCreateValidator, msgs[0].(legacytx.LegacyMsg).Type())
s.Require().Equal([]sdk.AccAddress{val.Address}, msgs[0].GetSigners())
s.Require().Equal(amount, msgs[0].(*types.MsgCreateValidator).Value)
err = tx.ValidateBasic()
+39 -84
View File
@@ -39,14 +39,14 @@ func (p Proposer) String() string {
func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposalParams) ([]byte, error) {
searchResult, err := combineEvents(
clientCtx, defaultPage,
// Query old Msgs
// Query legacy Msgs event action
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgDeposit),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalDeposit, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
},
// Query service Msgs
// Query proto Msgs event action
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeSvcMsgDeposit),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, sdk.MsgTypeURL(&types.MsgDeposit{})),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalDeposit, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
},
)
@@ -58,14 +58,7 @@ func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposal
for _, info := range searchResult.Txs {
for _, msg := range info.GetTx().GetMsgs() {
var depMsg *types.MsgDeposit
if msg.Type() == types.TypeSvcMsgDeposit {
depMsg = msg.(sdk.ServiceMsg).Request.(*types.MsgDeposit)
} else if protoDepMsg, ok := msg.(*types.MsgDeposit); ok {
depMsg = protoDepMsg
}
if depMsg != nil {
if depMsg, ok := msg.(*types.MsgDeposit); ok {
deposits = append(deposits, types.Deposit{
Depositor: depMsg.Depositor,
ProposalId: params.ProposalID,
@@ -95,27 +88,27 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot
// query interrupted either if we collected enough votes or tx indexer run out of relevant txs
for len(votes) < totalLimit {
// Search for both (old) votes and weighted votes.
// Search for both (legacy) votes and weighted votes.
searchResult, err := combineEvents(
clientCtx, nextTxPage,
// Query old Vote Msgs
// Query legacy Vote Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgVote),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
},
// Query Vote service Msgs
// Query Vote proto Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeSvcMsgVote),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, sdk.MsgTypeURL(&types.MsgVote{})),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
},
// Query old VoteWeighted Msgs
// Query legacy VoteWeighted Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgVoteWeighted),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
},
// Query VoteWeighted service Msgs
// Query VoteWeighted proto Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeSvcMsgVoteWeighted),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, sdk.MsgTypeURL(&types.MsgVoteWeighted{})),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
},
)
@@ -125,14 +118,7 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot
for _, info := range searchResult.Txs {
for _, msg := range info.GetTx().GetMsgs() {
var voteMsg *types.MsgVote
if msg.Type() == types.TypeSvcMsgVote {
voteMsg = msg.(sdk.ServiceMsg).Request.(*types.MsgVote)
} else if protoVoteMsg, ok := msg.(*types.MsgVote); ok {
voteMsg = protoVoteMsg
}
if voteMsg != nil {
if voteMsg, ok := msg.(*types.MsgVote); ok {
votes = append(votes, types.Vote{
Voter: voteMsg.Voter,
ProposalId: params.ProposalID,
@@ -140,14 +126,7 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot
})
}
var voteWeightedMsg *types.MsgVoteWeighted
if msg.Type() == types.TypeSvcMsgVoteWeighted {
voteWeightedMsg = msg.(sdk.ServiceMsg).Request.(*types.MsgVoteWeighted)
} else if protoVoteWeightedMsg, ok := msg.(*types.MsgVoteWeighted); ok {
voteWeightedMsg = protoVoteWeightedMsg
}
if voteWeightedMsg != nil {
if voteWeightedMsg, ok := msg.(*types.MsgVoteWeighted); ok {
votes = append(votes, types.Vote{
Voter: voteWeightedMsg.Voter,
ProposalId: params.ProposalID,
@@ -181,27 +160,27 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot
func QueryVoteByTxQuery(clientCtx client.Context, params types.QueryVoteParams) ([]byte, error) {
searchResult, err := combineEvents(
clientCtx, defaultPage,
// Query old Vote Msgs
// Query legacy Vote Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgVote),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, []byte(params.Voter.String())),
},
// Query Vote service Msgs
// Query Vote proto Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeSvcMsgVote),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, sdk.MsgTypeURL(&types.MsgVote{})),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, []byte(params.Voter.String())),
},
// Query old VoteWeighted Msgs
// Query legacy VoteWeighted Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgVoteWeighted),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, []byte(params.Voter.String())),
},
// Query VoteWeighted service Msgs
// Query VoteWeighted proto Msgs
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeSvcMsgVoteWeighted),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, sdk.MsgTypeURL(&types.MsgVoteWeighted{})),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalVote, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, []byte(params.Voter.String())),
},
@@ -212,37 +191,26 @@ func QueryVoteByTxQuery(clientCtx client.Context, params types.QueryVoteParams)
for _, info := range searchResult.Txs {
for _, msg := range info.GetTx().GetMsgs() {
var voteMsg *types.MsgVote
// there should only be a single vote under the given conditions
if msg.Type() == types.TypeSvcMsgVote {
voteMsg = msg.(sdk.ServiceMsg).Request.(*types.MsgVote)
} else if protoVoteMsg, ok := msg.(*types.MsgVote); ok {
voteMsg = protoVoteMsg
}
if voteMsg != nil {
vote := types.Vote{
var vote *types.Vote
if voteMsg, ok := msg.(*types.MsgVote); ok {
vote = &types.Vote{
Voter: voteMsg.Voter,
ProposalId: params.ProposalID,
Options: types.NewNonSplitVoteOption(voteMsg.Option),
}
}
bz, err := clientCtx.JSONMarshaler.MarshalJSON(&vote)
if err != nil {
return nil, err
}
return bz, nil
} else if msg.Type() == types.TypeMsgVoteWeighted {
voteMsg := msg.(*types.MsgVoteWeighted)
vote := types.Vote{
Voter: voteMsg.Voter,
if voteWeightedMsg, ok := msg.(*types.MsgVoteWeighted); ok {
vote = &types.Vote{
Voter: voteWeightedMsg.Voter,
ProposalId: params.ProposalID,
Options: voteMsg.Options,
Options: voteWeightedMsg.Options,
}
}
bz, err := clientCtx.JSONMarshaler.MarshalJSON(&vote)
if vote != nil {
bz, err := clientCtx.JSONMarshaler.MarshalJSON(vote)
if err != nil {
return nil, err
}
@@ -260,15 +228,15 @@ func QueryVoteByTxQuery(clientCtx client.Context, params types.QueryVoteParams)
func QueryDepositByTxQuery(clientCtx client.Context, params types.QueryDepositParams) ([]byte, error) {
searchResult, err := combineEvents(
clientCtx, defaultPage,
// Query old Msgs
// Query legacy Msgs event action
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgDeposit),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalDeposit, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, []byte(params.Depositor.String())),
},
// Query service Msgs
// Query proto Msgs event action
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeSvcMsgDeposit),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, sdk.MsgTypeURL(&types.MsgDeposit{})),
fmt.Sprintf("%s.%s='%s'", types.EventTypeProposalDeposit, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeySender, []byte(params.Depositor.String())),
},
@@ -279,15 +247,8 @@ func QueryDepositByTxQuery(clientCtx client.Context, params types.QueryDepositPa
for _, info := range searchResult.Txs {
for _, msg := range info.GetTx().GetMsgs() {
var depMsg *types.MsgDeposit
// there should only be a single deposit under the given conditions
if msg.Type() == types.TypeSvcMsgDeposit {
depMsg = msg.(sdk.ServiceMsg).Request.(*types.MsgDeposit)
} else if protoDepMsg, ok := msg.(*types.MsgDeposit); ok {
depMsg = protoDepMsg
}
if depMsg != nil {
if depMsg, ok := msg.(*types.MsgDeposit); ok {
deposit := types.Deposit{
Depositor: depMsg.Depositor,
ProposalId: params.ProposalID,
@@ -313,14 +274,14 @@ func QueryProposerByTxQuery(clientCtx client.Context, proposalID uint64) (Propos
searchResult, err := combineEvents(
clientCtx,
defaultPage,
// Query old Msgs
// Query legacy Msgs event action
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeMsgSubmitProposal),
fmt.Sprintf("%s.%s='%s'", types.EventTypeSubmitProposal, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", proposalID))),
},
// Query service Msgs
// Query proto Msgs event action
[]string{
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, types.TypeSvcMsgSubmitProposal),
fmt.Sprintf("%s.%s='%s'", sdk.EventTypeMessage, sdk.AttributeKeyAction, sdk.MsgTypeURL(&types.MsgSubmitProposal{})),
fmt.Sprintf("%s.%s='%s'", types.EventTypeSubmitProposal, types.AttributeKeyProposalID, []byte(fmt.Sprintf("%d", proposalID))),
},
)
@@ -331,13 +292,7 @@ func QueryProposerByTxQuery(clientCtx client.Context, proposalID uint64) (Propos
for _, info := range searchResult.Txs {
for _, msg := range info.GetTx().GetMsgs() {
// there should only be a single proposal under the given conditions
if msg.Type() == types.TypeSvcMsgSubmitProposal {
subMsg := msg.(sdk.ServiceMsg).Request.(*types.MsgSubmitProposal)
return NewProposer(proposalID, subMsg.Proposer), nil
} else if protoSubMsg, ok := msg.(*types.MsgSubmitProposal); ok {
subMsg := protoSubMsg
if subMsg, ok := msg.(*types.MsgSubmitProposal); ok {
return NewProposer(proposalID, subMsg.Proposer), nil
}
}
@@ -367,7 +322,7 @@ func QueryProposalByID(proposalID uint64, clientCtx client.Context, queryRoute s
//
// Tx are indexed in tendermint via their Msgs `Type()`, which can be:
// - via legacy Msgs (amino or proto), their `Type()` is a custom string,
// - via ADR-031 service msgs, their `Type()` is the protobuf FQ method name.
// - via ADR-031 proto msgs, their `Type()` is the protobuf FQ method name.
// In searching for events, we search for both `Type()`s, and we use the
// `combineEvents` function here to merge events.
func combineEvents(clientCtx client.Context, page int, eventGroups ...[]string) (*sdk.SearchTxsResult, error) {
+2 -1
View File
@@ -13,6 +13,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
"github.com/cosmos/cosmos-sdk/x/gov/client/utils"
"github.com/cosmos/cosmos-sdk/x/gov/types"
)
@@ -44,7 +45,7 @@ func (mock TxSearchMock) TxSearch(ctx context.Context, query string, prove bool,
return nil, err
}
for _, msg := range sdkTx.GetMsgs() {
if msg.Type() == msgType {
if msg.(legacytx.LegacyMsg).Type() == msgType {
matchingTxs = append(matchingTxs, tx)
break
}
-6
View File
@@ -18,12 +18,6 @@ const (
TypeMsgVote = "vote"
TypeMsgVoteWeighted = "weighted_vote"
TypeMsgSubmitProposal = "submit_proposal"
// These are used for querying events by action.
TypeSvcMsgDeposit = "/cosmos.gov.v1beta1.Msg/Deposit"
TypeSvcMsgVote = "/cosmos.gov.v1beta1.Msg/Vote"
TypeSvcMsgVoteWeighted = "/cosmos.gov.v1beta1.Msg/VoteWeighted"
TypeSvcMsgSubmitProposal = "/cosmos.gov.v1beta1.Msg/SubmitProposal"
)
var (
+1 -7
View File
@@ -153,28 +153,22 @@ func delegatorTxsHandlerFn(clientCtx client.Context) http.HandlerFunc {
// For each case, we search txs for both:
// - legacy messages: their Type() is a custom string, e.g. "delegate"
// - service Msgs: their Type() is their FQ method name, e.g. "/cosmos.staking.v1beta1.Msg/Delegate"
// - service Msgs: their Type() is their FQ method name, e.g. "/cosmos.staking.v1beta1.MsgDelegate"
// and we combine the results.
switch {
case isBondTx:
actions = append(actions, types.TypeMsgDelegate)
actions = append(actions, types.TypeSvcMsgDelegate)
case isUnbondTx:
actions = append(actions, types.TypeMsgUndelegate)
actions = append(actions, types.TypeSvcMsgUndelegate)
case isRedTx:
actions = append(actions, types.TypeMsgBeginRedelegate)
actions = append(actions, types.TypeSvcMsgBeginRedelegate)
case noQuery:
actions = append(actions, types.TypeMsgDelegate)
actions = append(actions, types.TypeSvcMsgDelegate)
actions = append(actions, types.TypeMsgUndelegate)
actions = append(actions, types.TypeSvcMsgUndelegate)
actions = append(actions, types.TypeMsgBeginRedelegate)
actions = append(actions, types.TypeSvcMsgBeginRedelegate)
default:
w.WriteHeader(http.StatusNoContent)
+5 -9
View File
@@ -12,10 +12,6 @@ const gasCostPerIteration = uint64(10)
var (
_ authz.Authorization = &StakeAuthorization{}
TypeDelegate = "/cosmos.staking.v1beta1.Msg/Delegate"
TypeUndelegate = "/cosmos.staking.v1beta1.Msg/Undelegate"
TypeBeginRedelegate = "/cosmos.staking.v1beta1.Msg/BeginRedelegate"
)
// NewStakeAuthorization creates a new StakeAuthorization object.
@@ -61,11 +57,11 @@ func (authorization StakeAuthorization) ValidateBasic() error {
}
// Accept implements Authorization.Accept.
func (authorization StakeAuthorization) Accept(ctx sdk.Context, msg sdk.ServiceMsg) (updated authz.Authorization, delete bool, err error) {
func (authorization StakeAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (updated authz.Authorization, delete bool, err error) {
var validatorAddress string
var amount sdk.Coin
switch msg := msg.Request.(type) {
switch msg := msg.(type) {
case *MsgDelegate:
validatorAddress = msg.ValidatorAddress
amount = msg.Amount
@@ -142,11 +138,11 @@ func validateAndBech32fy(allowed []sdk.ValAddress, denied []sdk.ValAddress) ([]s
func normalizeAuthzType(authzType AuthorizationType) (string, error) {
switch authzType {
case AuthorizationType_AUTHORIZATION_TYPE_DELEGATE:
return TypeDelegate, nil
return sdk.MsgTypeURL(&MsgDelegate{}), nil
case AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE:
return TypeUndelegate, nil
return sdk.MsgTypeURL(&MsgUndelegate{}), nil
case AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE:
return TypeBeginRedelegate, nil
return sdk.MsgTypeURL(&MsgBeginRedelegate{}), nil
default:
return "", sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "unknown authorization type %T", authzType)
}
+20 -45
View File
@@ -3,9 +3,8 @@ package types_test
import (
"testing"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
@@ -33,7 +32,7 @@ func TestAuthzAuthorizations(t *testing.T) {
// verify MethodName
delAuth, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100)
require.NoError(t, err)
require.Equal(t, delAuth.MethodName(), stakingtypes.TypeDelegate)
require.Equal(t, delAuth.MethodName(), sdk.MsgTypeURL(&stakingtypes.MsgDelegate{}))
// error both allow & deny list
_, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100)
@@ -41,11 +40,11 @@ func TestAuthzAuthorizations(t *testing.T) {
// verify MethodName
undelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100)
require.Equal(t, undelAuth.MethodName(), stakingtypes.TypeUndelegate)
require.Equal(t, undelAuth.MethodName(), sdk.MsgTypeURL(&stakingtypes.MsgUndelegate{}))
// verify MethodName
beginRedelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100)
require.Equal(t, beginRedelAuth.MethodName(), stakingtypes.TypeBeginRedelegate)
require.Equal(t, beginRedelAuth.MethodName(), sdk.MsgTypeURL(&stakingtypes.MsgBeginRedelegate{}))
validators1_2 := []string{val1.String(), val2.String()}
@@ -55,7 +54,7 @@ func TestAuthzAuthorizations(t *testing.T) {
denied []sdk.ValAddress
msgType stakingtypes.AuthorizationType
limit *sdk.Coin
srvMsg sdk.ServiceMsg
srvMsg sdk.Msg
expectErr bool
isDelete bool
updatedAuthorization *stakingtypes.StakeAuthorization
@@ -66,7 +65,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
&coin100,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val1, coin100),
stakingtypes.NewMsgDelegate(delAddr, val1, coin100),
false,
true,
nil,
@@ -77,7 +76,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
&coin100,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val1, coin50),
stakingtypes.NewMsgDelegate(delAddr, val1, coin50),
false,
false,
&stakingtypes.StakeAuthorization{
@@ -91,7 +90,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
&coin100,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val3, coin100),
stakingtypes.NewMsgDelegate(delAddr, val3, coin100),
true,
false,
nil,
@@ -102,7 +101,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
nil,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val2, coin100),
stakingtypes.NewMsgDelegate(delAddr, val2, coin100),
false,
false,
&stakingtypes.StakeAuthorization{
@@ -116,7 +115,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{val1},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
nil,
createSrvMsgDelegate(delAuth.MethodName(), delAddr, val1, coin100),
stakingtypes.NewMsgDelegate(delAddr, val1, coin100),
true,
false,
nil,
@@ -128,7 +127,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin100),
stakingtypes.NewMsgUndelegate(delAddr, val1, coin100),
false,
true,
nil,
@@ -139,7 +138,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin50),
stakingtypes.NewMsgUndelegate(delAddr, val1, coin50),
false,
false,
&stakingtypes.StakeAuthorization{
@@ -153,7 +152,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val3, coin100),
stakingtypes.NewMsgUndelegate(delAddr, val3, coin100),
true,
false,
nil,
@@ -164,7 +163,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
nil,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val2, coin100),
stakingtypes.NewMsgUndelegate(delAddr, val2, coin100),
false,
false,
&stakingtypes.StakeAuthorization{
@@ -178,7 +177,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{val1},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin100),
stakingtypes.NewMsgUndelegate(delAddr, val1, coin100),
true,
false,
nil,
@@ -190,7 +189,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgUndelegate(undelAuth.MethodName(), delAddr, val1, coin100),
stakingtypes.NewMsgUndelegate(delAddr, val1, coin100),
false,
true,
nil,
@@ -201,7 +200,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val1, coin50),
stakingtypes.NewMsgBeginRedelegate(delAddr, val1, val1, coin50),
false,
false,
&stakingtypes.StakeAuthorization{
@@ -215,7 +214,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val3, coin100),
stakingtypes.NewMsgBeginRedelegate(delAddr, val3, val3, coin100),
true,
false,
nil,
@@ -226,7 +225,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
nil,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val2, coin100),
stakingtypes.NewMsgBeginRedelegate(delAddr, val2, val2, coin100),
false,
false,
&stakingtypes.StakeAuthorization{
@@ -240,7 +239,7 @@ func TestAuthzAuthorizations(t *testing.T) {
[]sdk.ValAddress{val1},
stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE,
&coin100,
createSrvMsgReDelegate(undelAuth.MethodName(), delAddr, val1, coin100),
stakingtypes.NewMsgBeginRedelegate(delAddr, val1, val1, coin100),
true,
false,
nil,
@@ -266,27 +265,3 @@ func TestAuthzAuthorizations(t *testing.T) {
})
}
}
func createSrvMsgUndelegate(methodName string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) sdk.ServiceMsg {
msg := stakingtypes.NewMsgUndelegate(delAddr, valAddr, amount)
return sdk.ServiceMsg{
MethodName: methodName,
Request: msg,
}
}
func createSrvMsgReDelegate(methodName string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) sdk.ServiceMsg {
msg := stakingtypes.NewMsgBeginRedelegate(delAddr, valAddr, valAddr, amount)
return sdk.ServiceMsg{
MethodName: methodName,
Request: msg,
}
}
func createSrvMsgDelegate(methodName string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) sdk.ServiceMsg {
msg := stakingtypes.NewMsgDelegate(delAddr, valAddr, amount)
return sdk.ServiceMsg{
MethodName: methodName,
Request: msg,
}
}
-7
View File
@@ -16,13 +16,6 @@ const (
TypeMsgCreateValidator = "create_validator"
TypeMsgDelegate = "delegate"
TypeMsgBeginRedelegate = "begin_redelegate"
// These are used for querying events by action.
TypeSvcMsgUndelegate = "/cosmos.staking.v1beta1.Msg/Undelegate"
TypeSvcMsgEditValidator = "/cosmos.staking.v1beta1.Msg/EditValidator"
TypeSvcMsgCreateValidator = "/cosmos.staking.v1beta1.Msg/CreateValidator"
TypeSvcMsgDelegate = "/cosmos.staking.v1beta1.Msg/Delegate"
TypeSvcMsgBeginRedelegate = "/cosmos.staking.v1beta1.Msg/BeginRedelegate"
)
var (