-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
router.go
200 lines (165 loc) · 6.49 KB
/
router.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package integration
import (
"context"
"fmt"
cmtabcitypes "github.com/cometbft/cometbft/abci/types"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/log"
"cosmossdk.io/store"
"cosmossdk.io/store/metrics"
storetypes "cosmossdk.io/store/types"
authtx "cosmossdk.io/x/auth/tx"
authtypes "cosmossdk.io/x/auth/types"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/runtime"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper"
consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types"
)
const appName = "integration-app"
// App is a test application that can be used to test the integration of modules.
type App struct {
*baseapp.BaseApp
ctx sdk.Context
logger log.Logger
moduleManager module.Manager
queryHelper *baseapp.QueryServiceTestHelper
}
// NewIntegrationApp creates an application for testing purposes. This application
// is able to route messages to their respective handlers.
func NewIntegrationApp(
sdkCtx sdk.Context,
logger log.Logger,
keys map[string]*storetypes.KVStoreKey,
appCodec codec.Codec,
addressCodec address.Codec,
validatorCodec address.Codec,
modules map[string]appmodule.AppModule,
) *App {
db := dbm.NewMemDB()
interfaceRegistry := codectypes.NewInterfaceRegistry()
moduleManager := module.NewManagerFromMap(modules)
moduleManager.RegisterInterfaces(interfaceRegistry)
txConfig := authtx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), addressCodec, validatorCodec, authtx.DefaultSignModes)
bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseapp.SetChainID(appName))
bApp.MountKVStores(keys)
bApp.SetInitChainer(func(ctx sdk.Context, _ *cmtabcitypes.RequestInitChain) (*cmtabcitypes.ResponseInitChain, error) {
for _, mod := range modules {
if m, ok := mod.(module.HasGenesis); ok {
m.InitGenesis(ctx, appCodec, m.DefaultGenesis(appCodec))
}
}
return &cmtabcitypes.ResponseInitChain{}, nil
})
bApp.SetBeginBlocker(func(_ sdk.Context) (sdk.BeginBlock, error) {
return moduleManager.BeginBlock(sdkCtx)
})
bApp.SetEndBlocker(func(_ sdk.Context) (sdk.EndBlock, error) {
return moduleManager.EndBlock(sdkCtx)
})
msgRouter := baseapp.NewMsgServiceRouter()
msgRouter.SetInterfaceRegistry(interfaceRegistry)
bApp.SetMsgServiceRouter(msgRouter)
if keys[consensusparamtypes.StoreKey] != nil {
// set baseApp param store
consensusParamsKeeper := consensusparamkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithRouterService(baseapp.NewGRPCQueryRouter(), msgRouter)), authtypes.NewModuleAddress("gov").String())
bApp.SetParamStore(consensusParamsKeeper.ParamsStore)
if err := bApp.LoadLatestVersion(); err != nil {
panic(fmt.Errorf("failed to load application version from store: %w", err))
}
if _, err := bApp.InitChain(&cmtabcitypes.RequestInitChain{ChainId: appName, ConsensusParams: simtestutil.DefaultConsensusParams}); err != nil {
panic(fmt.Errorf("failed to initialize application: %w", err))
}
} else {
if err := bApp.LoadLatestVersion(); err != nil {
panic(fmt.Errorf("failed to load application version from store: %w", err))
}
if _, err := bApp.InitChain(&cmtabcitypes.RequestInitChain{ChainId: appName}); err != nil {
panic(fmt.Errorf("failed to initialize application: %w", err))
}
}
_, err := bApp.Commit()
if err != nil {
panic(err)
}
ctx := sdkCtx.WithBlockHeader(cmtproto.Header{ChainID: appName}).WithIsCheckTx(true)
return &App{
BaseApp: bApp,
logger: logger,
ctx: ctx,
moduleManager: *moduleManager,
queryHelper: baseapp.NewQueryServerTestHelper(ctx, interfaceRegistry),
}
}
// RunMsg provides the ability to run a message and return the response.
// In order to run a message, the application must have a handler for it.
// These handlers are registered on the application message service router.
// The result of the message execution is returned as an Any type.
// That any type can be unmarshaled to the expected response type.
// If the message execution fails, an error is returned.
func (app *App) RunMsg(msg sdk.Msg, option ...Option) (*codectypes.Any, error) {
// set options
cfg := &Config{}
for _, opt := range option {
opt(cfg)
}
if cfg.AutomaticCommit {
defer func() {
_, err := app.Commit()
if err != nil {
panic(err)
}
}()
}
if cfg.AutomaticFinalizeBlock {
height := app.LastBlockHeight() + 1
if _, err := app.FinalizeBlock(&cmtabcitypes.RequestFinalizeBlock{Height: height, DecidedLastCommit: cmtabcitypes.CommitInfo{Votes: []cmtabcitypes.VoteInfo{{}}}}); err != nil {
return nil, fmt.Errorf("failed to run finalize block: %w", err)
}
}
app.logger.Info("Running msg", "msg", msg.String())
handler := app.MsgServiceRouter().Handler(msg)
if handler == nil {
return nil, fmt.Errorf("handler is nil, can't route message %s: %+v", sdk.MsgTypeURL(msg), msg)
}
msgResult, err := handler(app.ctx, msg)
if err != nil {
return nil, fmt.Errorf("failed to execute message %s: %w", sdk.MsgTypeURL(msg), err)
}
var response *codectypes.Any
if len(msgResult.MsgResponses) > 0 {
msgResponse := msgResult.MsgResponses[0]
if msgResponse == nil {
return nil, fmt.Errorf("got nil msg response %s in message result: %s", sdk.MsgTypeURL(msg), msgResult.String())
}
response = msgResponse
}
return response, nil
}
// Context returns the application context. It can be unwrapped to a sdk.Context,
// with the sdk.UnwrapSDKContext function.
func (app *App) Context() context.Context {
return app.ctx
}
// QueryHelper returns the application query helper.
// It can be used when registering query services.
func (app *App) QueryHelper() *baseapp.QueryServiceTestHelper {
return app.queryHelper
}
// CreateMultiStore is a helper for setting up multiple stores for provided modules.
func CreateMultiStore(keys map[string]*storetypes.KVStoreKey, logger log.Logger) storetypes.CommitMultiStore {
db := dbm.NewMemDB()
cms := store.NewCommitMultiStore(db, logger, metrics.NewNoOpMetrics())
for key := range keys {
cms.MountStoreWithDB(keys[key], storetypes.StoreTypeIAVL, db)
}
_ = cms.LoadLatestVersion()
return cms
}