clawchain/app/app.go
caelum0x 40c687d745 feat(app): add custom ante handler chain with 18 decorators
Production-grade tx validation pipeline: SetUpContext, CosmWasm gas/counter,
CircuitBreaker, SDK validation (basic, timeout, memo, gas, fees),
signature verification (pubkey, sig count, gas, verify), sequence
increment, and IBC redundant relay protection. 11 tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 23:47:35 +03:00

417 lines
14 KiB
Go

package app
import (
"io"
"path/filepath"
clienthelpers "cosmossdk.io/client/v2/helpers"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
circuitkeeper "cosmossdk.io/x/circuit/keeper"
upgradekeeper "cosmossdk.io/x/upgrade/keeper"
abci "github.com/cometbft/cometbft/abci/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth"
ante "github.com/cosmos/cosmos-sdk/x/auth/ante"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
consensuskeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper"
distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
icacontrollerkeeper "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/controller/keeper"
icahostkeeper "github.com/cosmos/ibc-go/v10/modules/apps/27-interchain-accounts/host/keeper"
ibctransferkeeper "github.com/cosmos/ibc-go/v10/modules/apps/transfer/keeper"
ibckeeper "github.com/cosmos/ibc-go/v10/modules/core/keeper"
"github.com/CosmWasm/wasmd/x/wasm"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
"clawchain/docs"
tokenfactorykeeper "clawchain/x/tokenfactory/keeper"
agentmodulekeeper "clawchain/x/agent/keeper"
clawchainmodulekeeper "clawchain/x/clawchain/keeper"
governancemodulekeeper "clawchain/x/governance/keeper"
marketplacemodulekeeper "clawchain/x/marketplace/keeper"
oraclemodulekeeper "clawchain/x/oracle/keeper"
messagingmodulekeeper "clawchain/x/messaging/keeper"
modelregistrymodulekeeper "clawchain/x/modelregistry/keeper"
privacymodulekeeper "clawchain/x/privacy/keeper"
reputationmodulekeeper "clawchain/x/reputation/keeper"
)
const (
// Name is the name of the application.
Name = "clawchain"
// AccountAddressPrefix is the prefix for accounts addresses.
AccountAddressPrefix = "claw"
// ChainCoinType is the coin type of the chain.
ChainCoinType = 118
)
// DefaultNodeHome default home directories for the application daemon
var DefaultNodeHome string
var (
_ runtime.AppI = (*App)(nil)
_ servertypes.Application = (*App)(nil)
)
// App 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 App struct {
*runtime.App
legacyAmino *codec.LegacyAmino
appCodec codec.Codec
txConfig client.TxConfig
interfaceRegistry codectypes.InterfaceRegistry
// keepers
// only keepers required by the app are exposed
// the list of all modules is available in the app_config
AuthKeeper authkeeper.AccountKeeper
BankKeeper bankkeeper.Keeper
StakingKeeper *stakingkeeper.Keeper
SlashingKeeper slashingkeeper.Keeper
MintKeeper mintkeeper.Keeper
DistrKeeper distrkeeper.Keeper
GovKeeper *govkeeper.Keeper
UpgradeKeeper *upgradekeeper.Keeper
AuthzKeeper authzkeeper.Keeper
ConsensusParamsKeeper consensuskeeper.Keeper
CircuitBreakerKeeper circuitkeeper.Keeper
ParamsKeeper paramskeeper.Keeper
// ibc keepers
IBCKeeper *ibckeeper.Keeper
ICAControllerKeeper icacontrollerkeeper.Keeper
ICAHostKeeper icahostkeeper.Keeper
TransferKeeper ibctransferkeeper.Keeper
// cosmwasm
WasmKeeper wasmkeeper.Keeper
TokenFactoryKeeper tokenfactorykeeper.Keeper
// simulation manager
sm *module.SimulationManager
ClawchainKeeper clawchainmodulekeeper.Keeper
PrivacyKeeper privacymodulekeeper.Keeper
AgentKeeper agentmodulekeeper.Keeper
MessagingKeeper messagingmodulekeeper.Keeper
MarketplaceKeeper marketplacemodulekeeper.Keeper
ReputationKeeper reputationmodulekeeper.Keeper
GovernanceKeeper governancemodulekeeper.Keeper
ModelRegistryKeeper modelregistrymodulekeeper.Keeper
OracleKeeper oraclemodulekeeper.Keeper
}
func init() {
var err error
clienthelpers.EnvPrefix = Name
DefaultNodeHome, err = clienthelpers.GetNodeHomeDirectory("." + Name)
if err != nil {
panic(err)
}
}
// AppConfig returns the default app config.
func AppConfig() depinject.Config {
return depinject.Configs(
appConfig,
depinject.Supply(
// supply custom module basics
map[string]module.AppModuleBasic{
genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator),
},
),
)
}
// New returns a reference to an initialized App.
func New(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
loadLatest bool,
appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) *App {
var (
app = &App{}
appBuilder *runtime.AppBuilder
// merge the AppConfig and other configuration in one config
appConfig = depinject.Configs(
AppConfig(),
depinject.Supply(
appOpts, // supply app options
logger, // supply logger
// Supply with IBC keeper getter for the IBC modules with App Wiring.
// The IBC Keeper cannot be passed because it has not been initiated yet.
// Passing the getter, the app IBC Keeper will always be accessible.
// This needs to be removed after IBC supports App Wiring.
app.GetIBCKeeper,
// here alternative options can be supplied to the DI container.
// those options can be used f.e to override the default behavior of some modules.
// for instance supplying a custom address codec for not using bech32 addresses.
// read the depinject documentation and depinject module wiring for more information
// on available options and how to use them.
),
)
)
var appModules map[string]appmodule.AppModule
if err := depinject.Inject(appConfig,
&appBuilder,
&appModules,
&app.appCodec,
&app.legacyAmino,
&app.txConfig,
&app.interfaceRegistry,
&app.AuthKeeper,
&app.BankKeeper,
&app.StakingKeeper,
&app.SlashingKeeper,
&app.MintKeeper,
&app.DistrKeeper,
&app.GovKeeper,
&app.UpgradeKeeper,
&app.AuthzKeeper,
&app.ConsensusParamsKeeper,
&app.CircuitBreakerKeeper,
&app.ParamsKeeper,
&app.ClawchainKeeper,
&app.PrivacyKeeper,
&app.AgentKeeper,
&app.MessagingKeeper,
&app.MarketplaceKeeper,
&app.ReputationKeeper,
&app.GovernanceKeeper,
&app.ModelRegistryKeeper,
&app.OracleKeeper,
); err != nil {
panic(err)
}
// Wire ReputationKeeper into AgentKeeper post-init to break the
// Agent↔Reputation circular depinject dependency.
app.AgentKeeper.SetReputationKeeper(app.ReputationKeeper)
// Wire module param executors into the governance keeper so that
// passed proposals actually apply parameter changes on-chain.
(&app.GovernanceKeeper).RegisterModuleParamExecutor("agent", app.AgentKeeper)
(&app.GovernanceKeeper).RegisterModuleParamExecutor("marketplace", app.MarketplaceKeeper)
(&app.GovernanceKeeper).RegisterModuleParamExecutor("privacy", app.PrivacyKeeper)
(&app.GovernanceKeeper).RegisterModuleParamExecutor("modelregistry", app.ModelRegistryKeeper)
(&app.GovernanceKeeper).RegisterModuleParamExecutor("messaging", app.MessagingKeeper)
(&app.GovernanceKeeper).RegisterModuleParamExecutor("reputation", app.ReputationKeeper)
(&app.GovernanceKeeper).RegisterModuleParamExecutor("oracle", app.OracleKeeper)
// Load Groth16 verifying keys for the privacy module.
// Keys are generated by `clawproof setup` and stored under <node-home>/keys/.
keysDir := filepath.Join(DefaultNodeHome, "keys")
if err := app.PrivacyKeeper.LoadVerifyingKeys(keysDir); err != nil {
logger.Warn("privacy module: verifying keys not loaded (non-privacy operations still work)", "error", err)
}
// add to default baseapp options
// enable optimistic execution
baseAppOptions = append(baseAppOptions, baseapp.SetOptimisticExecution())
// build app
app.App = appBuilder.Build(db, traceStore, baseAppOptions...)
// Initialize tokenfactory keeper first (wasm message handler needs it)
if err := app.initTokenFactoryKeeper(); err != nil {
panic(err)
}
// register legacy modules (IBC + CosmWasm keeper init + IBC routing)
if err := app.registerIBCModules(appOpts); err != nil {
panic(err)
}
// register CosmWasm module (app module + snapshot extension)
if err := app.registerWasmModule(); err != nil {
panic(err)
}
// register tokenfactory module (AppModule only, keeper already initialized)
if err := app.registerTokenFactoryModule(); err != nil {
panic(err)
}
// Read wasm node config for the ante handler simulation gas limit.
wasmConfig, err := wasm.ReadNodeConfig(appOpts)
if err != nil {
panic(err)
}
// Set up the custom ante handler chain with IBC, CosmWasm, and circuit breaker support.
anteHandlerOptions := HandlerOptions{
HandlerOptions: ante.HandlerOptions{
AccountKeeper: app.AuthKeeper,
BankKeeper: app.BankKeeper,
SignModeHandler: app.txConfig.SignModeHandler(),
},
IBCKeeper: app.IBCKeeper,
WasmConfig: &wasmConfig,
WasmKeeper: &app.WasmKeeper,
TXCounterStoreService: runtime.NewKVStoreService(app.GetKey(wasmtypes.StoreKey)),
CircuitKeeper: &app.CircuitBreakerKeeper,
StakingKeeper: app.StakingKeeper,
}
anteHandler, err := NewAnteHandler(anteHandlerOptions)
if err != nil {
panic(err)
}
app.SetAnteHandler(anteHandler)
postHandler, err := NewPostHandler(anteHandlerOptions)
if err != nil {
panic(err)
}
app.SetPostHandler(postHandler)
/**** Module Options ****/
// create the simulation manager and define the order of the modules for deterministic simulations
overrideModules := map[string]module.AppModuleSimulation{
authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AuthKeeper, authsims.RandomGenesisAccounts, nil),
}
app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules)
app.sm.RegisterStoreDecoders()
// A custom InitChainer sets if extra pre-init-genesis logic is required.
// This is necessary for manually registered modules that do not support app wiring.
// Manually set the module version map as shown below.
// The upgrade module will automatically handle de-duplication of the module version map.
app.SetInitChainer(func(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) {
if err := app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()); err != nil {
return nil, err
}
return app.App.InitChainer(ctx, req)
})
// Register upgrade handlers for live chain upgrades.
// This must be called after Build() but before Load().
app.RegisterUpgradeHandlers()
if err := app.Load(loadLatest); err != nil {
panic(err)
}
return app
}
// GetSubspace returns a param subspace for a given module name.
func (app *App) GetSubspace(moduleName string) paramstypes.Subspace {
subspace, _ := app.ParamsKeeper.GetSubspace(moduleName)
return subspace
}
// LegacyAmino returns App's amino codec.
func (app *App) LegacyAmino() *codec.LegacyAmino {
return app.legacyAmino
}
// AppCodec returns App's app codec.
func (app *App) AppCodec() codec.Codec {
return app.appCodec
}
// InterfaceRegistry returns App's InterfaceRegistry.
func (app *App) InterfaceRegistry() codectypes.InterfaceRegistry {
return app.interfaceRegistry
}
// TxConfig returns App's TxConfig
func (app *App) TxConfig() client.TxConfig {
return app.txConfig
}
// GetKey returns the KVStoreKey for the provided store key.
func (app *App) GetKey(storeKey string) *storetypes.KVStoreKey {
kvStoreKey, ok := app.UnsafeFindStoreKey(storeKey).(*storetypes.KVStoreKey)
if !ok {
return nil
}
return kvStoreKey
}
// SimulationManager implements the SimulationApp interface
func (app *App) SimulationManager() *module.SimulationManager {
return app.sm
}
// RegisterAPIRoutes registers all application module routes with the provided
// API server.
func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) {
app.App.RegisterAPIRoutes(apiSvr, apiConfig)
// register swagger API in app.go so that other applications can override easily
if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil {
panic(err)
}
// register app's OpenAPI routes.
docs.RegisterOpenAPIService(Name, apiSvr.Router)
}
// GetMaccPerms returns a copy of the module account permissions
//
// NOTE: This is solely to be used for testing purposes.
func GetMaccPerms() map[string][]string {
dup := make(map[string][]string)
for _, perms := range moduleAccPerms {
dup[perms.GetAccount()] = perms.GetPermissions()
}
return dup
}
// BlockedAddresses returns all the app's blocked account addresses.
func BlockedAddresses() map[string]bool {
result := make(map[string]bool)
if len(blockAccAddrs) > 0 {
for _, addr := range blockAccAddrs {
result[addr] = true
}
} else {
for addr := range GetMaccPerms() {
result[addr] = true
}
}
return result
}