Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: simulate nested messages #20291

Merged
merged 18 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i

### Features

* (baseapp) [#20291](https://github.com/cosmos/cosmos-sdk/pull/20291) Simulate nested messages.
* (client) [#20690](https://github.com/cosmos/cosmos-sdk/pull/20690) Import mnemonic from file
* (tests) [#20013](https://github.com/cosmos/cosmos-sdk/pull/20013) Introduce system tests to run multi node local testnet in CI
* (runtime) [#19953](https://github.com/cosmos/cosmos-sdk/pull/19953) Implement `core/transaction.Service` in runtime.
Expand Down
162 changes: 162 additions & 0 deletions baseapp/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import (
"testing"
"time"

"github.com/cosmos/cosmos-sdk/codec"

abci "github.com/cometbft/cometbft/abci/types"
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
abci "github.com/cometbft/cometbft/api/cometbft/abci/v1"
cmtprotocrypto "github.com/cometbft/cometbft/api/cometbft/crypto/v1"
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
Expand All @@ -24,6 +27,7 @@ import (
"github.com/cosmos/gogoproto/jsonpb"
"github.com/cosmos/gogoproto/proto"
gogotypes "github.com/cosmos/gogoproto/types"
any "github.com/cosmos/gogoproto/types/any"
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -760,6 +764,164 @@ func TestABCI_FinalizeBlock_MultiMsg(t *testing.T) {
require.Equal(t, int64(2), msgCounter2)
}

func anyMessage(t *testing.T, cdc codec.Codec, msg *baseapptestutil.MsgSend) *any.Any {
t.Helper()
b, err := cdc.Marshal(msg)
require.NoError(t, err)
return &any.Any{
TypeUrl: sdk.MsgTypeURL(msg),
Value: b,
}
}

func TestABCI_Query_SimulateNestedMessagesTx(t *testing.T) {
gasConsumed := uint64(5)
anteOpt := func(bapp *baseapp.BaseApp) {
bapp.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) {
newCtx = ctx.WithGasMeter(storetypes.NewGasMeter(gasConsumed))
return
})
}
suite := NewBaseAppSuite(t, anteOpt)

_, err := suite.baseApp.InitChain(&abci.InitChainRequest{
ConsensusParams: &cmtproto.ConsensusParams{},
})
require.NoError(t, err)

baseapptestutil.RegisterNestedMessagesServer(suite.baseApp.MsgServiceRouter(), NestedMessgesServerImpl{})
baseapptestutil.RegisterSendServer(suite.baseApp.MsgServiceRouter(), SendServerImpl{})

_, _, addr := testdata.KeyTestPubAddr()
_, _, toAddr := testdata.KeyTestPubAddr()
tests := []struct {
name string
message sdk.Msg
wantErr bool
}{
{
name: "ok nested message",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: if you use a map[string]struct{} for the tests spec, you can avoid the name attribute and use the map key instead

JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
message: &baseapptestutil.MsgSend{
From: addr.String(),
To: toAddr.String(),
Amount: "10000stake",
},
},
{
name: "different signers",
message: &baseapptestutil.MsgSend{
From: toAddr.String(),
To: addr.String(),
Amount: "10000stake",
},
wantErr: true,
},
{
name: "empty from",
message: &baseapptestutil.MsgSend{
From: "",
To: toAddr.String(),
Amount: "10000stake",
},
wantErr: true,
},
{
name: "empty to",
message: &baseapptestutil.MsgSend{
From: addr.String(),
To: "",
Amount: "10000stake",
},
wantErr: true,
},
{
name: "negative amount",
message: &baseapptestutil.MsgSend{
From: addr.String(),
To: toAddr.String(),
Amount: "-10000stake",
},
wantErr: true,
},
{
name: "with nested messages",
message: &baseapptestutil.MsgNestedMessages{
Signer: addr.String(),
Messages: []*any.Any{
anyMessage(t, suite.cdc, &baseapptestutil.MsgSend{
From: addr.String(),
To: toAddr.String(),
Amount: "10000stake",
}),
},
},
wantErr: false,
},
{
name: "with invalid nested messages",
message: &baseapptestutil.MsgNestedMessages{
Signer: addr.String(),
Messages: []*any.Any{
anyMessage(t, suite.cdc, &baseapptestutil.MsgSend{
From: "",
To: toAddr.String(),
Amount: "10000stake",
}),
},
},
wantErr: true,
},
{
name: "with different signer ",
message: &baseapptestutil.MsgNestedMessages{
Signer: addr.String(),
Messages: []*any.Any{
anyMessage(t, suite.cdc, &baseapptestutil.MsgSend{
From: toAddr.String(),
To: addr.String(),
Amount: "10000stake",
}),
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
nestedMessages := make([]*any.Any, 1)
b, err := suite.cdc.Marshal(tt.message)
require.NoError(t, err)
nestedMessages[0] = &any.Any{
TypeUrl: sdk.MsgTypeURL(tt.message),
Value: b,
}

msg := &baseapptestutil.MsgNestedMessages{
Messages: nestedMessages,
Signer: addr.String(),
}

builder := suite.txConfig.NewTxBuilder()
err = builder.SetMsgs(msg)
require.NoError(t, err)
setTxSignature(t, builder, 0)
tx := builder.GetTx()

txBytes, err := suite.txConfig.TxEncoder()(tx)
require.Nil(t, err)

_, result, err := suite.baseApp.Simulate(txBytes)
if tt.wantErr {
require.Error(t, err)
require.Nil(t, result)
} else {
require.NoError(t, err)
require.NotNil(t, result)
}
})
}
}

func TestABCI_Query_SimulateTx(t *testing.T) {
gasConsumed := uint64(5)
anteOpt := func(bapp *baseapp.BaseApp) {
Expand Down
71 changes: 71 additions & 0 deletions baseapp/baseapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
"github.com/cometbft/cometbft/crypto/tmhash"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/cosmos-proto/anyutil"
"github.com/cosmos/gogoproto/proto"
"golang.org/x/exp/maps"
protov2 "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/reflect/protoreflect"

"cosmossdk.io/core/header"
Expand Down Expand Up @@ -811,6 +814,10 @@
return endblock, nil
}

type HasNestedMsgs interface {
GetMsgs() ([]sdk.Msg, error)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure whats the best place to define this 🤨

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is a good practice to define the type where it is used. You can also consider making it private or inline it into the function where it is used. In this case there is the same interface in types called HasMsgs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm HasMsgs is pretty similar but doesn't return an error. I think it was designed with tx in mind.

GetMsgs() []Msg

Makes me wonder if we should update HasMsgs or stick with this 'duplicate'. If we opt for both interfaces, baseapp is not the ideal place for HasNestedMsgs as it may be useful for ante handlers.
@tac0turtle @julienrbrt

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is the possible error that would be returned here? feel like it wouldnt return an error and just be length of 0

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Opted for that because current messages with nested messages within the SDK have defined that method:

// GetMessages returns the proposal messages
func (p Proposal) GetMsgs() ([]sdk.Msg, error) {
return sdktx.GetMsgs(p.Messages, "sdk.MsgProposal")
}

// GetMsgs unpacks p.Messages Any's into sdk.Msg's
func (p *Proposal) GetMsgs() ([]sdk.Msg, error) {
return tx.GetMsgs(p.Messages, "proposal")
}

I guess we should standardise this and document it.

}

// runTx processes a transaction within a given execution mode, encoded transaction
// bytes, and the decoded transaction itself. All state transitions occur through
// a cached Context depending on the mode provided. State only gets persisted
Expand Down Expand Up @@ -955,6 +962,16 @@
result, err = app.runMsgs(runMsgCtx, msgs, reflectMsgs, mode)
}

if mode == execModeSimulate {
nestedMsgsContext, _ := app.cacheTxContext(ctx, txBytes)
for _, msg := range msgs {
nestedErr := app.simulateNestedMessages(nestedMsgsContext, msg)
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
if nestedErr != nil {
return gInfo, nil, anteEvents, nestedErr
}
}
}

// Run optional postHandlers (should run regardless of the execution result).
//
// Note: If the postHandler fails, we also revert the runMsgs state.
Expand Down Expand Up @@ -1061,6 +1078,60 @@
}, nil
}

// simulateNestedMessages simulates a message nested messages.
func (app *BaseApp) simulateNestedMessages(ctx sdk.Context, msg sdk.Msg) error {
tac0turtle marked this conversation as resolved.
Show resolved Hide resolved
nestedMsgs, ok := msg.(HasNestedMsgs)
if !ok {
return nil
}

msgs, err := nestedMsgs.GetMsgs()
if err != nil {
return err
}

for _, msg := range msgs {
err = app.simulateNestedMessages(ctx, msg)
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}
}

if err := validateBasicTxMsgs(app.msgServiceRouter, msgs); err != nil {
return err
}

msgsV2, err := app.msgsV1ToMsgsV2(msgs)
if err != nil {
return err
}

_, err = app.runMsgs(ctx, msgs, msgsV2, execModeSimulate)

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / dependency-review

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / golangci-lint

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs) (typecheck)

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / golangci-lint

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs) (typecheck)

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / golangci-lint

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs) (typecheck)

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (03)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (03)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (00)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (00)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (00)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (00)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (01)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (01)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (02)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs

Check failure on line 1109 in baseapp/baseapp.go

View workflow job for this annotation

GitHub Actions / tests (02)

cannot use msgsV2 (variable of type []protoreflect.ProtoMessage) as []protoreflect.Message value in argument to app.runMsgs
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
return err
}

// msgsV1ToMsgsV2 transforms v1 messages into v2.
func (app *BaseApp) msgsV1ToMsgsV2(msgs []sdk.Msg) ([]protov2.Message, error) {
msgsV2 := make([]protov2.Message, len(msgs))
for i, msg := range msgs {
gogoAny, err := codectypes.NewAnyWithValue(msg)
if err != nil {
return nil, err
}
anyMsg := &anypb.Any{
TypeUrl: gogoAny.TypeUrl,
Value: gogoAny.Value,
}
msgV2, err := anyutil.Unpack(anyMsg, app.cdc.InterfaceRegistry().SigningContext().FileResolver(), app.cdc.InterfaceRegistry().SigningContext().TypeResolver())
if err != nil {
return nil, err
}
msgsV2[i] = msgV2
}
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved

return msgsV2, nil
}
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved

// makeABCIData generates the Data field to be sent to ABCI Check/DeliverTx.
func makeABCIData(msgResponses []*codectypes.Any) ([]byte, error) {
return proto.Marshal(&sdk.TxMsgData{MsgResponses: msgResponses})
Expand Down
24 changes: 24 additions & 0 deletions baseapp/testutil/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package testutil
import (
errorsmod "cosmossdk.io/errors"

codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand All @@ -16,10 +17,15 @@ func RegisterInterfaces(registry types.InterfaceRegistry) {
&MsgCounter{},
&MsgCounter2{},
&MsgKeyValue{},
&MsgNestedMessages{},
&MsgSend{},
)

msgservice.RegisterMsgServiceDesc(registry, &_Counter_serviceDesc)
msgservice.RegisterMsgServiceDesc(registry, &_Counter2_serviceDesc)
msgservice.RegisterMsgServiceDesc(registry, &_KeyValue_serviceDesc)
msgservice.RegisterMsgServiceDesc(registry, &_NestedMessages_serviceDesc)
msgservice.RegisterMsgServiceDesc(registry, &_Send_serviceDesc)

codec.RegisterInterfaces(registry)
}
Expand Down Expand Up @@ -63,3 +69,21 @@ func (msg *MsgKeyValue) ValidateBasic() error {
}
return nil
}

func (msg *MsgNestedMessages) GetMsgs() ([]sdk.Msg, error) {
cdc := codectestutil.CodecOptions{}.NewCodec()
RegisterInterfaces(cdc.InterfaceRegistry())
msgs := make([]sdk.Msg, len(msg.GetMessages()))
for i, m := range msg.GetMessages() {
mm, err := cdc.InterfaceRegistry().Resolve(m.TypeUrl)
if err != nil {
return nil, err
}
err = cdc.UnpackAny(m, &mm)
if err != nil {
return nil, err
}
msgs[i] = mm
}
return msgs, nil
}
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
Loading
Loading