-
Notifications
You must be signed in to change notification settings - Fork 556
/
app.go
520 lines (426 loc) · 17.8 KB
/
app.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package app
import (
// Imports from the Go Standard Library
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
// HTTP Router
"github.com/gorilla/mux"
// Used to serve OpenAPI information
"github.com/rakyll/statik/fs"
// A CLI helper
"github.com/spf13/cast"
// Imports from Tendermint, Osmosis' consensus protocol
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
// Utilities from the Cosmos-SDK other than Cosmos modules
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
store "github.com/cosmos/cosmos-sdk/store/types"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
// Cosmos-SDK Modules
// https://github.com/cosmos/cosmos-sdk/tree/master/x
// NB: Osmosis uses a fork of the cosmos-sdk which can be found at: https://github.com/osmosis-labs/cosmos-sdk
// Auth: Authentication of accounts and transactions for Cosmos SDK applications.
"github.com/cosmos/cosmos-sdk/x/auth/ante"
authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
// Capability: allows developers to atomically define what a module can and cannot do
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
// Crisis: Halting the blockchain under certain circumstances (e.g. if an invariant is broken).
"github.com/cosmos/cosmos-sdk/x/crisis"
// Evidence handling for double signing, misbehaviour, etc.
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
// Params: Parameters that are always available
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
// Upgrade: Software upgrades handling and coordination.
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
// IBC Transfer: Defines the "transfer" IBC port
transfer "github.com/cosmos/ibc-go/v2/modules/apps/transfer"
// Osmosis application prarmeters
appparams "github.com/osmosis-labs/osmosis/v8/app/params"
// Upgrades from earlier versions of Osmosis
v4 "github.com/osmosis-labs/osmosis/v8/app/upgrades/v4"
v5 "github.com/osmosis-labs/osmosis/v8/app/upgrades/v5"
v7 "github.com/osmosis-labs/osmosis/v8/app/upgrades/v7"
_ "github.com/osmosis-labs/osmosis/v8/client/docs/statik"
// Superfluid: Allows users to stake gamm (bonded liquidity)
superfluidtypes "github.com/osmosis-labs/osmosis/v8/x/superfluid/types"
// Wasm: Allows Osmosis to interact with web assembly smart contracts
"github.com/CosmWasm/wasmd/x/wasm"
)
const appName = "OsmosisApp"
var (
// If EnableSpecificWasmProposals is "", and this is "true", then enable all x/wasm proposals.
// If EnableSpecificWasmProposals is "", and this is not "true", then disable all x/wasm proposals.
WasmProposalsEnabled = "true"
// If set to non-empty string it must be comma-separated list of values that are all a subset
// of "EnableAllProposals" (takes precedence over WasmProposalsEnabled)
// https://github.com/CosmWasm/wasmd/blob/02a54d33ff2c064f3539ae12d75d027d9c665f05/x/wasm/internal/types/proposal.go#L28-L34
EnableSpecificWasmProposals = ""
// use this for clarity in argument list
EmptyWasmOpts []wasm.Option
)
// GetWasmEnabledProposals parses the WasmProposalsEnabled / EnableSpecificWasmProposals values to
// produce a list of enabled proposals to pass into wasmd app.
func GetWasmEnabledProposals() []wasm.ProposalType {
if EnableSpecificWasmProposals == "" {
if WasmProposalsEnabled == "true" {
return wasm.EnableAllProposals
}
return wasm.DisableAllProposals
}
chunks := strings.Split(EnableSpecificWasmProposals, ",")
proposals, err := wasm.ConvertToProposals(chunks)
if err != nil {
panic(err)
}
return proposals
}
var (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome string
// ModuleBasics defines the module BasicManager is in charge of setting up basic,
// non-dependant module elements, such as codec registration
// and genesis verification.
ModuleBasics = module.NewBasicManager(appModuleBasics...)
// module account permissions
maccPerms = moduleAaccountPermissions
// module accounts that are allowed to receive tokens
allowedReceivingModAcc = map[string]bool{
distrtypes.ModuleName: true,
}
)
var _ App = (*OsmosisApp)(nil)
// Osmosis extends an ABCI application, but with most of its parameters exported.
// They are exported for convenience in creating helper functions, as object
// capabilities aren't needed for testing.
type OsmosisApp struct {
*baseapp.BaseApp
appKeepers
cdc *codec.LegacyAmino
appCodec codec.Codec
interfaceRegistry types.InterfaceRegistry
invCheckPeriod uint
// keys to access the substores
keys map[string]*sdk.KVStoreKey
tkeys map[string]*sdk.TransientStoreKey
memKeys map[string]*sdk.MemoryStoreKey
transferModule transfer.AppModule
// the module manager
mm *module.Manager
// simulation manager
sm *module.SimulationManager
// module migration manager
configurator module.Configurator
}
func init() {
userHomeDir, err := os.UserHomeDir()
if err != nil {
panic(err)
}
DefaultNodeHome = filepath.Join(userHomeDir, ".osmosisd")
}
// NewOsmosis returns a reference to an initialized Osmosis.
func NewOsmosisApp(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
loadLatest bool,
skipUpgradeHeights map[int64]bool,
homePath string,
invCheckPeriod uint,
encodingConfig appparams.EncodingConfig,
appOpts servertypes.AppOptions,
wasmEnabledProposals []wasm.ProposalType,
wasmOpts []wasm.Option,
baseAppOptions ...func(*baseapp.BaseApp),
) *OsmosisApp {
appCodec := encodingConfig.Marshaler
cdc := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
// Define what keys will be used in the cosmos-sdk key/value store.
// Cosmos-SDK modules each have a "key" that allows the application to reference what they've stored on the chain.
// Keys are in keys.go to kep app.go as brief as possible.
keys := sdk.NewKVStoreKeys(KVStoreKeys()...)
// Define transient store keys
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
// MemKeys are for information that is stored only in RAM.
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
app := &OsmosisApp{
BaseApp: bApp,
cdc: cdc,
appCodec: appCodec,
interfaceRegistry: interfaceRegistry,
invCheckPeriod: invCheckPeriod,
keys: keys,
tkeys: tkeys,
memKeys: memKeys,
}
wasmDir := filepath.Join(homePath, "wasm")
wasmConfig, err := wasm.ReadWasmConfig(appOpts)
if err != nil {
panic(fmt.Sprintf("error while reading wasm config: %s", err))
}
app.InitSpecialKeepers(skipUpgradeHeights, homePath, invCheckPeriod)
app.setupUpgradeStoreLoaders()
app.InitNormalKeepers(wasmDir, wasmConfig, wasmEnabledProposals, wasmOpts)
app.SetupHooks()
/**** Module Options ****/
// NOTE: we may consider parsing `appOpts` inside module constructors. For the moment
// we prefer to be more strict in what arguments the modules expect.
var skipGenesisInvariants = cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants))
// NOTE: All module / keeper changes should happen prior to this module.NewManager line being called.
// However in the event any changes do need to happen after this call, ensure that that keeper
// is only passed in its keeper form (not de-ref'd anywhere)
//
// Generally NewAppModule will require the keeper that module defines to be passed in as an exact struct,
// but should take in every other keeper as long as it matches a certain interface. (So no need to be de-ref'd)
//
// Any time a module requires a keeper de-ref'd thats not its native one,
// its code-smell and should probably change. We should get the staking keeper dependencies fixed.
app.mm = module.NewManager(appModules(app, encodingConfig, skipGenesisInvariants)...)
// During begin block slashing happens after distr.BeginBlocker so that
// there is nothing left over in the validator fee pool, so as to keep the
// CanWithdrawInvariant invariant.
// NOTE: staking module is required if HistoricalEntries param > 0
// NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC)
// Tell the app's module manager how to set the order of BeginBlockers, which are run at the beginning of every block.
app.mm.SetOrderBeginBlockers(orderBeginBlockers()...)
// Tell the app's module manager how to set the order of EndBlockers, which are run at the end of every block.
app.mm.SetOrderEndBlockers(orderEndBlockers...)
// NOTE: The genutils moodule must occur after staking so that pools are
// properly initialized with tokens from genesis accounts.
// NOTE: Capability module must occur first so that it can initialize any capabilities
// so that other modules that want to create or claim capabilities afterwards in InitChain
// can do so safely.
app.mm.SetOrderInitGenesis(modulesOrderInitGenesis...)
app.mm.RegisterInvariants(app.CrisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.configurator = module.NewConfigurator(app.AppCodec(), app.MsgServiceRouter(), app.GRPCQueryRouter())
app.mm.RegisterServices(app.configurator)
app.setupUpgradeHandlers()
// create the simulation manager and define the order of the modules for deterministic simulations
//
// NOTE: this is not required apps that don't use the simulator for fuzz testing
// transactions
app.sm = module.NewSimulationManager(simulationModules(app, encodingConfig, skipGenesisInvariants)...)
app.sm.RegisterStoreDecoders()
// add test gRPC service for testing gRPC queries in isolation
testdata.RegisterQueryServer(app.GRPCQueryRouter(), testdata.QueryImpl{})
// initialize stores
app.MountKVStores(keys)
app.MountTransientStores(tkeys)
app.MountMemoryStores(memKeys)
// initialize BaseApp
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
app.SetAnteHandler(
NewAnteHandler(
appOpts,
wasmConfig,
keys[wasm.StoreKey],
app.AccountKeeper,
app.BankKeeper,
app.TxFeesKeeper,
app.GAMMKeeper,
ante.DefaultSigVerificationGasConsumer,
encodingConfig.TxConfig.SignModeHandler(),
app.IBCKeeper.ChannelKeeper,
),
)
app.SetEndBlocker(app.EndBlocker)
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
tmos.Exit(err.Error())
}
ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{})
// Initialize pinned codes in wasmvm as they are not persisted there
if err := app.WasmKeeper.InitializePinnedCodes(ctx); err != nil {
tmos.Exit(fmt.Sprintf("failed initialize pinned codes %s", err))
}
}
return app
}
// MakeCodecs constructs the *std.Codec and *codec.LegacyAmino instances used by
// simapp. It is useful for tests and clients who do not want to construct the
// full simapp
func MakeCodecs() (codec.Codec, *codec.LegacyAmino) {
config := MakeEncodingConfig()
return config.Marshaler, config.Amino
}
// Name returns the name of the App
func (app *OsmosisApp) Name() string { return app.BaseApp.Name() }
// BeginBlocker application updates every begin block
func (app *OsmosisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
BeginBlockForks(ctx, app)
return app.mm.BeginBlock(ctx, req)
}
// EndBlocker application updates every end block
func (app *OsmosisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
return app.mm.EndBlock(ctx, req)
}
// InitChainer application update at chain initialization
func (app *OsmosisApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var genesisState GenesisState
if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}
// LoadHeight loads a particular height
func (app *OsmosisApp) LoadHeight(height int64) error {
return app.LoadVersion(height)
}
// LegacyAmino returns SimApp's amino codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *OsmosisApp) LegacyAmino() *codec.LegacyAmino {
return app.cdc
}
// AppCodec returns Osmosis' app codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *OsmosisApp) AppCodec() codec.Codec {
return app.appCodec
}
// InterfaceRegistry returns Osmosis' InterfaceRegistry
func (app *OsmosisApp) InterfaceRegistry() types.InterfaceRegistry {
return app.interfaceRegistry
}
// GetKey returns the KVStoreKey for the provided store key.
//
// NOTE: This is solely to be used for testing purposes.
func (app *OsmosisApp) GetKey(storeKey string) *sdk.KVStoreKey {
return app.keys[storeKey]
}
// GetTKey returns the TransientStoreKey for the provided store key.
//
// NOTE: This is solely to be used for testing purposes.
func (app *OsmosisApp) GetTKey(storeKey string) *sdk.TransientStoreKey {
return app.tkeys[storeKey]
}
// GetMemKey returns the MemStoreKey for the provided mem key.
//
// NOTE: This is solely used for testing purposes.
func (app *OsmosisApp) GetMemKey(storeKey string) *sdk.MemoryStoreKey {
return app.memKeys[storeKey]
}
// GetSubspace returns a param subspace for a given module name.
//
// NOTE: This is solely to be used for testing purposes.
func (app *OsmosisApp) GetSubspace(moduleName string) paramstypes.Subspace {
subspace, _ := app.ParamsKeeper.GetSubspace(moduleName)
return subspace
}
// SimulationManager implements the SimulationApp interface
func (app *OsmosisApp) SimulationManager() *module.SimulationManager {
return app.sm
}
// RegisterAPIRoutes registers all application module routes with the provided
// API server.
func (app *OsmosisApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) {
clientCtx := apiSvr.ClientCtx
rpc.RegisterRoutes(clientCtx, apiSvr.Router)
// Register legacy tx routes.
authrest.RegisterTxRoutes(clientCtx, apiSvr.Router)
// Register new tx routes from grpc-gateway.
authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register new tendermint queries routes from grpc-gateway.
tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register legacy and grpc-gateway routes for all modules.
ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router)
ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// register swagger API from root so that other applications can override easily
if apiConfig.Swagger {
RegisterSwaggerAPI(clientCtx, apiSvr.Router)
}
}
// RegisterTxService implements the Application.RegisterTxService method.
func (app *OsmosisApp) RegisterTxService(clientCtx client.Context) {
authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry)
}
// RegisterTendermintService implements the Application.RegisterTendermintService method.
func (app *OsmosisApp) RegisterTendermintService(clientCtx client.Context) {
tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry)
}
func (app *OsmosisApp) setupUpgradeStoreLoaders() {
upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk()
if err != nil {
panic(fmt.Sprintf("failed to read upgrade info from disk %s", err))
}
if upgradeInfo.Name == v7.UpgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) {
// @Frey do we do this for Cosmwasm?
storeUpgrades := store.StoreUpgrades{
Added: []string{wasm.ModuleName, superfluidtypes.ModuleName},
}
// configure store loader that checks if version == upgradeHeight and applies store upgrades
app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades))
}
}
func (app *OsmosisApp) setupUpgradeHandlers() {
// this configures a no-op upgrade handler for the v4 upgrade,
// which improves the lockup module's store management.
app.UpgradeKeeper.SetUpgradeHandler(
v4.UpgradeName, v4.CreateUpgradeHandler(
app.mm, app.configurator,
*app.BankKeeper, app.DistrKeeper, app.GAMMKeeper))
app.UpgradeKeeper.SetUpgradeHandler(
v5.UpgradeName,
v5.CreateUpgradeHandler(
app.mm, app.configurator,
&app.IBCKeeper.ConnectionKeeper, app.TxFeesKeeper,
app.GAMMKeeper, app.StakingKeeper))
app.UpgradeKeeper.SetUpgradeHandler(
v7.UpgradeName,
v7.CreateUpgradeHandler(
app.mm, app.configurator,
app.WasmKeeper,
app.SuperfluidKeeper,
app.EpochsKeeper,
app.LockupKeeper,
app.MintKeeper,
app.AccountKeeper))
}
// RegisterSwaggerAPI registers swagger route with API Server
func RegisterSwaggerAPI(ctx client.Context, rtr *mux.Router) {
statikFS, err := fs.New()
if err != nil {
panic(err)
}
staticServer := http.FileServer(statikFS)
rtr.PathPrefix("/static/").Handler(http.StripPrefix("/static/", staticServer))
rtr.PathPrefix("/swagger/").Handler(staticServer)
}
// GetMaccPerms returns a copy of the module account permissions
func GetMaccPerms() map[string][]string {
dupMaccPerms := make(map[string][]string)
for k, v := range maccPerms {
dupMaccPerms[k] = v
}
return dupMaccPerms
}