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 13 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
236 changes: 236 additions & 0 deletions baseapp/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,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 All @@ -38,6 +39,7 @@ import (
"github.com/cosmos/cosmos-sdk/baseapp"
baseapptestutil "github.com/cosmos/cosmos-sdk/baseapp/testutil"
"github.com/cosmos/cosmos-sdk/baseapp/testutil/mock"
"github.com/cosmos/cosmos-sdk/codec"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
Expand Down Expand Up @@ -760,6 +762,240 @@ 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) {
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(uint64(15)))
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",
}),
},
},
},
{
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_SimulateNestedMessagesGas(t *testing.T) {
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(uint64(10)))
return
})
}

_, _, addr := testdata.KeyTestPubAddr()
_, _, toAddr := testdata.KeyTestPubAddr()

tests := []struct {
name string
suite *BaseAppSuite
message sdk.Msg
consumedGas uint64
}{
{
name: "add gas",
suite: NewBaseAppSuite(t, anteOpt),
message: &baseapptestutil.MsgSend{
From: addr.String(),
To: toAddr.String(),
Amount: "10000stake",
},
consumedGas: 10,
},
{
name: "don't add gas",
suite: NewBaseAppSuite(t, anteOpt, baseapp.SetExcludeNestedMsgsGas([]sdk.Msg{&baseapptestutil.MsgNestedMessages{}})),
message: &baseapptestutil.MsgSend{
From: addr.String(),
To: toAddr.String(),
Amount: "10000stake",
},
consumedGas: 5,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := tt.suite.baseApp.InitChain(&abci.InitChainRequest{
ConsensusParams: &cmtproto.ConsensusParams{},
})
require.NoError(t, err)

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

nestedMessages := make([]*any.Any, 1)
b, err := tt.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 := tt.suite.txConfig.NewTxBuilder()
err = builder.SetMsgs(msg)
require.NoError(t, err)
setTxSignature(t, builder, 0)
tx := builder.GetTx()

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

gas, result, err := tt.suite.baseApp.Simulate(txBytes)
require.NoError(t, err)
require.NotNil(t, result)
require.True(t, gas.GasUsed == tt.consumedGas)
})
}
}

func TestABCI_Query_SimulateTx(t *testing.T) {
gasConsumed := uint64(5)
anteOpt := func(bapp *baseapp.BaseApp) {
Expand Down
60 changes: 59 additions & 1 deletion baseapp/baseapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ type BaseApp struct {
// including the goroutine handling.This is experimental and must be enabled
// by developers.
optimisticExec *oe.OptimisticExecution

// excludeNestedMsgsGas holds a set of message types for which gas costs for its nested messages are not calculated.
excludeNestedMsgsGas map[string]struct{}
}

// NewBaseApp returns a reference to an initialized BaseApp. It accepts a
Expand Down Expand Up @@ -233,7 +236,9 @@ func NewBaseApp(
if app.interBlockCache != nil {
app.cms.SetInterBlockCache(app.interBlockCache)
}

if app.excludeNestedMsgsGas == nil {
app.excludeNestedMsgsGas = make(map[string]struct{})
}
app.runTxRecoveryMiddleware = newDefaultRecoveryMiddleware()

// Initialize with an empty interface registry to avoid nil pointer dereference.
Expand Down Expand Up @@ -811,6 +816,10 @@ func (app *BaseApp) endBlock(_ context.Context) (sdk.EndBlock, error) {
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 +964,19 @@ func (app *BaseApp) runTx(mode execMode, txBytes []byte) (gInfo sdk.GasInfo, res
result, err = app.runMsgs(runMsgCtx, msgs, reflectMsgs, mode)
}

if mode == execModeSimulate {
gas := ctx.GasMeter().GasConsumed()
for _, msg := range msgs {
nestedErr := app.simulateNestedMessages(ctx, msg)
if nestedErr != nil {
return gInfo, nil, anteEvents, nestedErr
}
if _, ok := app.excludeNestedMsgsGas[sdk.MsgTypeURL(msg)]; ok {
ctx.GasMeter().RefundGas(ctx.GasMeter().GasConsumed()-gas, "simulation of nested messages")
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

// 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 +1083,42 @@ func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, reflectMsgs []proto
}, 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
}

protoMessages := make([]protoreflect.Message, len(msgs))
for i, msg := range msgs {
_, protoMsg, err := app.cdc.GetMsgSigners(msg)
if err != nil {
return err
}
protoMessages[i] = protoMsg
}
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved

_, err = app.runMsgs(ctx, msgs, protoMessages, execModeSimulate)
return err
}
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding a recursion depth limit or converting to an iterative approach.

The simulateNestedMessages function uses recursion to handle nested messages. The depth of recursion could potentially lead to stack overflow errors with deeply nested structures. Consider adding a recursion depth limit or converting this to an iterative approach using a stack data structure to enhance robustness.

func (app *BaseApp) simulateNestedMessages(ctx sdk.Context, msg sdk.Msg) error {
+  const maxRecursionDepth = 100
+  return app.simulateNestedMessagesHelper(ctx, msg, 0, maxRecursionDepth)
}

+func (app *BaseApp) simulateNestedMessagesHelper(ctx sdk.Context, msg sdk.Msg, depth, maxDepth int) error {
+  if depth > maxDepth {
+    return errors.New("max recursion depth exceeded")
+  }
  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)
+    err = app.simulateNestedMessagesHelper(ctx, msg, depth+1, maxDepth)
    if err != nil {
      return err
    }
  }

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

  protoMessages := make([]protoreflect.Message, len(msgs))
  for i, msg := range msgs {
    _, protoMsg, err := app.cdc.GetMsgSigners(msg)
    if err != nil {
      return err
    }
    protoMessages[i] = protoMsg
  }

  _, err = app.runMsgs(ctx, msgs, protoMessages, execModeSimulate)
  return err
}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// simulateNestedMessages simulates a message nested messages.
func (app *BaseApp) simulateNestedMessages(ctx sdk.Context, msg sdk.Msg) error {
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)
if err != nil {
return err
}
}
if err := validateBasicTxMsgs(app.msgServiceRouter, msgs); err != nil {
return err
}
protoMessages := make([]protoreflect.Message, len(msgs))
for i, msg := range msgs {
_, protoMsg, err := app.cdc.GetMsgSigners(msg)
if err != nil {
return err
}
protoMessages[i] = protoMsg
}
_, err = app.runMsgs(ctx, msgs, protoMessages, execModeSimulate)
return err
}
// simulateNestedMessages simulates a message nested messages.
func (app *BaseApp) simulateNestedMessages(ctx sdk.Context, msg sdk.Msg) error {
const maxRecursionDepth = 100
return app.simulateNestedMessagesHelper(ctx, msg, 0, maxRecursionDepth)
}
func (app *BaseApp) simulateNestedMessagesHelper(ctx sdk.Context, msg sdk.Msg, depth, maxDepth int) error {
if depth > maxDepth {
return errors.New("max recursion depth exceeded")
}
nestedMsgs, ok := msg.(HasNestedMsgs)
if (!ok) {
return nil
}
msgs, err := nestedMsgs.GetMsgs()
if (err != nil) {
return err
}
for _, msg := range msgs {
err = app.simulateNestedMessagesHelper(ctx, msg, depth+1, maxDepth)
if (err != nil) {
return err
}
}
if err := validateBasicTxMsgs(app.msgServiceRouter, msgs); err != nil {
return err
}
protoMessages := make([]protoreflect.Message, len(msgs))
for i, msg := range msgs {
_, protoMsg, err := app.cdc.GetMsgSigners(msg)
if (err != nil) {
return err
}
protoMessages[i] = protoMsg
}
_, err = app.runMsgs(ctx, msgs, protoMessages, execModeSimulate)
return err
}


// 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
13 changes: 13 additions & 0 deletions baseapp/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,19 @@ func SetOptimisticExecution(opts ...func(*oe.OptimisticExecution)) func(*BaseApp
}
}

// SetExcludeNestedMsgsGas sets the message types for which gas costs for its nested messages are not calculated when simulating.
func SetExcludeNestedMsgsGas(msgs []sdk.Msg) func(*BaseApp) {
return func(app *BaseApp) {
app.excludeNestedMsgsGas = make(map[string]struct{})
for _, msg := range msgs {
if _, ok := msg.(HasNestedMsgs); !ok {
Copy link
Contributor

Choose a reason for hiding this comment

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

👍 good to check

continue
}
app.excludeNestedMsgsGas[sdk.MsgTypeURL(msg)] = struct{}{}
}
}
}
JulianToledano marked this conversation as resolved.
Show resolved Hide resolved

func (app *BaseApp) SetName(name string) {
if app.sealed {
panic("SetName() on sealed BaseApp")
Expand Down
Loading
Loading