diff --git a/CHANGELOG.md b/CHANGELOG.md index c1eec8e21c..b06194802f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#3818](https://github.com/sei-protocol/sei-chain/pull/3818) feat(evmrpc): extend HTTP admission control (`max_request_body_bytes`, `max_concurrent_request_bytes`, `ws_admission_timeout`) to the WebSocket plane (:8546). WS oversize frames close with WebSocket close code 1009; budget-wait timeouts return JSON-RPC error `-32005` before the connection closes. `evmrpc_requests_rejected_total` gains a `protocol` label (`http` / `ws`). ### Upgrade guide +* **Capability removal.** Removes the capability module and its IBC, transfer, and CosmWasm integrations. The capability store remains mounted for historical state access in freeze mode. * [#3958](https://github.com/sei-protocol/sei-chain/pull/3958) **Feegrant removal.** Removes feegrant execution, module APIs, and the unreleased feegrant EVM precompile. The feegrant store remains mounted for historical state access. Transactions with a fee granter different from the payer are rejected. * **WebSocket frame size default drops from 10 MiB to 5 MiB.** Before this release, :8546 used a hardcoded 10 MiB frame cap. Both HTTP and WebSocket now share `[evm].max_request_body_bytes`, whose default is 5 MiB (`5242880`). WS clients that send frames in the 5-10 MiB range (large `eth_sendRawTransaction` batches, wide filter payloads, etc.) will be disconnected after upgrade unless the limit is raised. **Operators who relied on the old 10 MiB WS cap should set `max_request_body_bytes = 10485760` in `app.toml` before upgrading.** This also raises the HTTP body limit to 10 MiB. The exported `DefaultWebsocketMaxMessageSize` constant was removed; use the config knob instead. * [#3927](https://github.com/sei-protocol/sei-chain/pull/3927) **Legacy Sei JSON-RPC and CLI removal.** Removes `sei_associate`, `sei_getBlockByHash`, `sei_getBlockByHashExcludeTraceFail`, `sei_getBlockTransactionCountByHash`, `sei_getBlockTransactionCountByNumber`, `sei_getEvmTx`, `sei_getFilterChanges`, `sei_getFilterLogs`, `sei_getLogs`, `sei_getTransactionByBlockHashAndIndex`, `sei_getTransactionByBlockNumberAndIndex`, `sei_getTransactionByHash`, `sei_getTransactionCount`, `sei_getTransactionErrorByHash`, `sei_getTransactionReceiptExcludeTraceFail`, `sei_getVMError`, `sei_newBlockFilter`, `sei_newFilter`, `sei_sign`, and `sei_uninstallFilter`. Use standard `eth_*` methods for EVM-originated data and `seid tx evm native-associate -y` for address association. There is no block- or filter-level replacement for discovering Cosmos-originated synthetic logs; clients that know the synthetic transaction hash can enable `sei_getTransactionReceipt`. diff --git a/app/app.go b/app/app.go index e903148def..91a30d62ba 100644 --- a/app/app.go +++ b/app/app.go @@ -63,9 +63,6 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank" bankkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/keeper" banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" distr "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution" distrclient "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/client" distrkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/keeper" @@ -214,7 +211,6 @@ var ( authzmodule.AppModuleBasic{}, genutil.AppModuleBasic{}, bank.AppModuleBasic{}, - capability.AppModuleBasic{}, staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, @@ -264,7 +260,7 @@ var ( authtypes.StoreKey, authzkeeper.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, feegrantModuleName, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, oracletypes.StoreKey, + evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilityModuleName, oracletypes.StoreKey, evmtypes.StoreKey, wasm.StoreKey, epochmoduletypes.StoreKey, tokenfactorytypes.StoreKey, @@ -299,8 +295,9 @@ var ( ) const ( - MinGasEVMTx = 21000 - feegrantModuleName = "feegrant" + MinGasEVMTx = 21000 + capabilityModuleName = "capability" + feegrantModuleName = "feegrant" // NewHeadsNotifierCapacity bounds the in-process eth_newHeads // notifier buffer. Capacity 1 pairs with the notifier's @@ -385,30 +382,24 @@ type App struct { memKeys map[string]*sdk.MemoryStoreKey // keepers - AccountKeeper authkeeper.AccountKeeper - AuthzKeeper authzkeeper.Keeper - BankKeeper bankkeeper.Keeper - GigaBankKeeper *gigabankkeeper.BaseKeeper - CapabilityKeeper *capabilitykeeper.Keeper - StakingKeeper stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - MintKeeper mintkeeper.Keeper - DistrKeeper distrkeeper.Keeper - GovKeeper govkeeper.Keeper - UpgradeKeeper upgradekeeper.Keeper - ParamsKeeper paramskeeper.Keeper - IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly - EvidenceKeeper evidencekeeper.Keeper - TransferKeeper ibctransferkeeper.Keeper - WasmKeeper wasm.Keeper - OracleKeeper oraclekeeper.Keeper - EvmKeeper evmkeeper.Keeper - GigaEvmKeeper gigaevmkeeper.Keeper - - // make scoped keepers public for test purposes - ScopedIBCKeeper capabilitykeeper.ScopedKeeper - ScopedTransferKeeper capabilitykeeper.ScopedKeeper - ScopedWasmKeeper capabilitykeeper.ScopedKeeper + AccountKeeper authkeeper.AccountKeeper + AuthzKeeper authzkeeper.Keeper + BankKeeper bankkeeper.Keeper + GigaBankKeeper *gigabankkeeper.BaseKeeper + StakingKeeper stakingkeeper.Keeper + SlashingKeeper slashingkeeper.Keeper + MintKeeper mintkeeper.Keeper + DistrKeeper distrkeeper.Keeper + GovKeeper govkeeper.Keeper + UpgradeKeeper upgradekeeper.Keeper + ParamsKeeper paramskeeper.Keeper + IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly + EvidenceKeeper evidencekeeper.Keeper + TransferKeeper ibctransferkeeper.Keeper + WasmKeeper wasm.Keeper + OracleKeeper oraclekeeper.Keeper + EvmKeeper evmkeeper.Keeper + GigaEvmKeeper gigaevmkeeper.Keeper EpochKeeper epochmodulekeeper.Keeper @@ -521,7 +512,7 @@ func New( keys := sdk.NewKVStoreKeys(kvStoreKeyNames...) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientStoreKey) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey, banktypes.DeferredCacheStoreKey, oracletypes.MemStoreKey) + memKeys := sdk.NewMemoryStoreKeys(banktypes.DeferredCacheStoreKey, oracletypes.MemStoreKey) app := &App{ BaseApp: bApp, @@ -558,15 +549,6 @@ func New( // set the BaseApp's parameter store bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramskeeper.ConsensusParamsKeyTable())) - // add capability keeper and ScopeToModule for ibc module - app.CapabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey]) - - // grant capabilities for the ibc and ibc-transfer modules - scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibchost.ModuleName) - scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) - scopedWasmKeeper := app.CapabilityKeeper.ScopeToModule(wasm.ModuleName) - // this line is used by starport scaffolding # stargate/app/scopedKeeper - // add keepers app.AccountKeeper = authkeeper.NewAccountKeeper( appCodec, keys[authtypes.StoreKey], app.GetSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms, @@ -606,7 +588,7 @@ func New( // Create IBC Keeper app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, app.UpgradeKeeper, scopedIBCKeeper, + appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, app.UpgradeKeeper, ) // Create Transfer Keepers @@ -616,10 +598,8 @@ func New( app.GetSubspace(ibctransfertypes.ModuleName), app.IBCKeeper.ChannelKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, - scopedTransferKeeper, evmkeeper.NewEvmAddressHandler(&app.EvmKeeper), ) transferModule := transfer.NewAppModule(app.TransferKeeper) @@ -671,7 +651,6 @@ func New( &app.AccountKeeper, app.MsgServiceRouter(), app.IBCKeeper.ChannelKeeper, - scopedWasmKeeper, app.BankKeeper, appCodec, app.TransferKeeper, @@ -690,8 +669,6 @@ func New( app.StakingKeeper, app.DistrKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - scopedWasmKeeper, app.UpgradeKeeper, app.TransferKeeper, app.MsgServiceRouter(), @@ -873,7 +850,6 @@ func New( auth.NewAppModule(appCodec, app.AccountKeeper, nil), vesting.NewAppModule(app.AccountKeeper, app.BankKeeper, app.UpgradeKeeper), bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - capability.NewAppModule(appCodec, *app.CapabilityKeeper), gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), @@ -894,15 +870,14 @@ func New( ) app.BeginBlockKeepers = legacyabci.BeginBlockKeepers{ - EpochKeeper: &app.EpochKeeper, - UpgradeKeeper: &app.UpgradeKeeper, - CapabilityKeeper: app.CapabilityKeeper, - DistrKeeper: &app.DistrKeeper, - SlashingKeeper: &app.SlashingKeeper, - EvidenceKeeper: &app.EvidenceKeeper, - StakingKeeper: &app.StakingKeeper, - IBCKeeper: app.IBCKeeper, - EvmKeeper: &app.EvmKeeper, + EpochKeeper: &app.EpochKeeper, + UpgradeKeeper: &app.UpgradeKeeper, + DistrKeeper: &app.DistrKeeper, + SlashingKeeper: &app.SlashingKeeper, + EvidenceKeeper: &app.EvidenceKeeper, + StakingKeeper: &app.StakingKeeper, + IBCKeeper: app.IBCKeeper, + EvmKeeper: &app.EvmKeeper, } app.EndBlockKeepers = legacyabci.EndBlockKeepers{ GovKeeper: &app.GovKeeper, @@ -932,13 +907,9 @@ func New( // NOTE: The genutils module 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( upgradetypes.ModuleName, paramstypes.ModuleName, - capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, @@ -968,7 +939,6 @@ func New( app.sm = module.NewSimulationManager( auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - capability.NewAppModule(appCodec, *app.CapabilityKeeper), gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), @@ -1069,10 +1039,6 @@ func New( panic(err) } - app.ScopedIBCKeeper = scopedIBCKeeper - app.ScopedTransferKeeper = scopedTransferKeeper - app.ScopedWasmKeeper = scopedWasmKeeper - // Create hard fork manager and register all hard fork upgrade handlers. Note, // when creating the manager, BaseApp must already be instantiated. // diff --git a/app/legacyabci/begin_block.go b/app/legacyabci/begin_block.go index 5114dd931f..46841efb26 100644 --- a/app/legacyabci/begin_block.go +++ b/app/legacyabci/begin_block.go @@ -5,8 +5,6 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/telemetry" sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" abci "github.com/sei-protocol/sei-chain/sei-tendermint/abci/types" "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution" @@ -29,15 +27,14 @@ import ( ) type BeginBlockKeepers struct { - EpochKeeper *epochmodulekeeper.Keeper - UpgradeKeeper *upgradekeeper.Keeper - CapabilityKeeper *capabilitykeeper.Keeper - DistrKeeper *distrkeeper.Keeper - SlashingKeeper *slashingkeeper.Keeper - EvidenceKeeper *evidencekeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - IBCKeeper *ibckeeper.Keeper - EvmKeeper *evmkeeper.Keeper + EpochKeeper *epochmodulekeeper.Keeper + UpgradeKeeper *upgradekeeper.Keeper + DistrKeeper *distrkeeper.Keeper + SlashingKeeper *slashingkeeper.Keeper + EvidenceKeeper *evidencekeeper.Keeper + StakingKeeper *stakingkeeper.Keeper + IBCKeeper *ibckeeper.Keeper + EvmKeeper *evmkeeper.Keeper } func BeginBlock( @@ -56,7 +53,6 @@ func BeginBlock( keepers.EpochKeeper.BeginBlock(ctx) upgrade.BeginBlocker(*keepers.UpgradeKeeper, ctx) - capability.BeginBlocker(ctx, *keepers.CapabilityKeeper) distribution.BeginBlocker(ctx, votes, *keepers.DistrKeeper) slashing.BeginBlocker(ctx, votes, *keepers.SlashingKeeper) evidence.BeginBlocker(ctx, byzantineValidators, *keepers.EvidenceKeeper) diff --git a/app/store_keys_test.go b/app/store_keys_test.go index 7bfdb8fcaf..b081b6e3ab 100644 --- a/app/store_keys_test.go +++ b/app/store_keys_test.go @@ -29,3 +29,13 @@ func TestFeegrantStoreRemainsMounted(t *testing.T) { store.Set([]byte("allowance"), []byte("retained")) require.Equal(t, []byte("retained"), store.Get([]byte("allowance"))) } + +func TestCapabilityStoreRemainsMounted(t *testing.T) { + require.Contains(t, kvStoreKeyNames, keys.CapabilityStoreKey) + + testApp := Setup(t, false, false, false) + ctx := testApp.NewContext(false, tmproto.Header{}) + store := ctx.KVStore(testApp.GetKey(keys.CapabilityStoreKey)) + store.Set([]byte("owner"), []byte("retained")) + require.Equal(t, []byte("retained"), store.Get([]byte("owner"))) +} diff --git a/app/upgrade_test.go b/app/upgrade_test.go index 9b13b3160b..f63a847559 100644 --- a/app/upgrade_test.go +++ b/app/upgrade_test.go @@ -30,7 +30,7 @@ func TestDistributionCommunityTaxParamMigration(t *testing.T) { testWrapper.Require().Equal(params.CommunityTax, sdk.NewDec(0)) } -func TestV67RemovesFeegrantModuleVersion(t *testing.T) { +func TestV67RemovesRetiredModuleVersions(t *testing.T) { t.Setenv("UPGRADE_VERSION_LIST", "v6.7") tm := time.Now().UTC() valPub := secp256k1.GenPrivKey().PubKey() @@ -38,6 +38,7 @@ func TestV67RemovesFeegrantModuleVersion(t *testing.T) { testWrapper.App.RegisterUpgradeHandlers() versionMap := testWrapper.App.UpgradeKeeper.GetModuleVersionMap(testWrapper.Ctx) + versionMap["capability"] = 1 versionMap["feegrant"] = 1 testWrapper.App.UpgradeKeeper.SetModuleVersionMap(testWrapper.Ctx, versionMap) @@ -47,6 +48,7 @@ func TestV67RemovesFeegrantModuleVersion(t *testing.T) { }) versionMap = testWrapper.App.UpgradeKeeper.GetModuleVersionMap(testWrapper.Ctx) + require.NotContains(t, versionMap, "capability") require.NotContains(t, versionMap, "feegrant") } diff --git a/app/upgrades.go b/app/upgrades.go index 4912f1ab75..a219a61caf 100644 --- a/app/upgrades.go +++ b/app/upgrades.go @@ -97,6 +97,7 @@ func (app *App) RegisterUpgradeHandlers() { if err != nil { return nil, err } + app.UpgradeKeeper.DeleteModuleVersion(ctx, capabilityModuleName) app.UpgradeKeeper.DeleteModuleVersion(ctx, feegrantModuleName) return newVM, nil } diff --git a/evmrpc/tests/mock_state.go b/evmrpc/tests/mock_state.go index bf683c88b1..83d373ceae 100644 --- a/evmrpc/tests/mock_state.go +++ b/evmrpc/tests/mock_state.go @@ -115,7 +115,7 @@ func mockStateFromJson(ctx sdk.Context, a *app.App, stateRaw json.RawMessage) { } } for moduleName, data := range typed { - if moduleName == "evm_transient" { + if moduleName == "evm_transient" || moduleName == "mem_capability" { continue } var storeKey sdk.StoreKey diff --git a/occ_tests/utils/utils.go b/occ_tests/utils/utils.go index cf07fe42c1..5ef47f0eb0 100644 --- a/occ_tests/utils/utils.go +++ b/occ_tests/utils/utils.go @@ -40,9 +40,8 @@ import ( // ignoreStoreKeys are store keys that are not compared var ignoredStoreKeys = map[string]struct{}{ - "mem_capability": {}, - "epoch": {}, - "deferredcache": {}, + "epoch": {}, + "deferredcache": {}, } type TestMessage struct { diff --git a/sei-cosmos/proto/cosmos/capability/v1beta1/capability.proto b/sei-cosmos/proto/cosmos/capability/v1beta1/capability.proto deleted file mode 100644 index 918bdbac12..0000000000 --- a/sei-cosmos/proto/cosmos/capability/v1beta1/capability.proto +++ /dev/null @@ -1,30 +0,0 @@ -syntax = "proto3"; -package cosmos.capability.v1beta1; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types"; - -// Capability defines an implementation of an object capability. The index -// provided to a Capability must be globally unique. -message Capability { - option (gogoproto.goproto_stringer) = false; - - uint64 index = 1 [(gogoproto.moretags) = "yaml:\"index\""]; -} - -// Owner defines a single capability owner. An owner is defined by the name of -// capability and the module name. -message Owner { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string module = 1 [(gogoproto.moretags) = "yaml:\"module\""]; - string name = 2 [(gogoproto.moretags) = "yaml:\"name\""]; -} - -// CapabilityOwners defines a set of owners of a single Capability. The set of -// owners must be unique. -message CapabilityOwners { - repeated Owner owners = 1 [(gogoproto.nullable) = false]; -} diff --git a/sei-cosmos/proto/cosmos/capability/v1beta1/genesis.proto b/sei-cosmos/proto/cosmos/capability/v1beta1/genesis.proto deleted file mode 100644 index 6b94e7b643..0000000000 --- a/sei-cosmos/proto/cosmos/capability/v1beta1/genesis.proto +++ /dev/null @@ -1,29 +0,0 @@ -syntax = "proto3"; -package cosmos.capability.v1beta1; - -import "cosmos/capability/v1beta1/capability.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types"; - -// GenesisOwners defines the capability owners with their corresponding index. -message GenesisOwners { - // index is the index of the capability owner. - uint64 index = 1; - - // index_owners are the owners at the given index. - CapabilityOwners index_owners = 2 [ - (gogoproto.nullable) = false, - (gogoproto.moretags) = "yaml:\"index_owners\"" - ]; -} - -// GenesisState defines the capability module's genesis state. -message GenesisState { - // index is the capability global index. - uint64 index = 1; - - // owners represents a map from index to owners of the capability index - // index key is string to allow amino marshalling. - repeated GenesisOwners owners = 2 [(gogoproto.nullable) = false]; -} diff --git a/sei-cosmos/x/README.md b/sei-cosmos/x/README.md index 4362b310b8..e77e6a756f 100644 --- a/sei-cosmos/x/README.md +++ b/sei-cosmos/x/README.md @@ -10,7 +10,6 @@ Here are some production-grade modules that can be used in Cosmos SDK applicatio - [Auth](auth/spec/README.md) - Authentication of accounts and transactions for Cosmos SDK application. - [Authz](authz/spec/README.md) - Authorization for accounts to perform actions on behalf of other accounts. - [Bank](bank/spec/README.md) - Token transfer functionalities. -- [Capability](capability/spec/README.md) - Object capability implementation. - [Distribution](distribution/spec/README.md) - Fee distribution, and staking token provision distribution. - [Evidence](evidence/spec/README.md) - Evidence handling for double signing, misbehaviour, etc. - [Governance](gov/spec/README.md) - On-chain proposals and voting. diff --git a/sei-cosmos/x/capability/abci.go b/sei-cosmos/x/capability/abci.go deleted file mode 100644 index 32e02323d9..0000000000 --- a/sei-cosmos/x/capability/abci.go +++ /dev/null @@ -1,26 +0,0 @@ -package capability - -import ( - "time" - - "github.com/sei-protocol/sei-chain/sei-cosmos/telemetry" - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -// BeginBlocker will call InitMemStore to initialize the memory stores in the case -// that this is the first time the node is executing a block since restarting (wiping memory). -// In this case, the BeginBlocker method will reinitialize the memory stores locally, so that subsequent -// capability transactions will pass. -// Otherwise BeginBlocker performs a no-op. -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - beginBlockerStart := time.Now() - defer func() { - capabilityMetrics.beginBlockerDuration.Record(ctx.Context(), time.Since(beginBlockerStart).Seconds()) - // TODO(PLT-414): remove once capability_begin_blocker_duration verified - telemetry.ModuleMeasureSince(types.ModuleName, beginBlockerStart, telemetry.MetricKeyBeginBlocker) - }() - - k.InitMemStore(ctx) -} diff --git a/sei-cosmos/x/capability/capability_test.go b/sei-cosmos/x/capability/capability_test.go deleted file mode 100644 index b81b2b98f2..0000000000 --- a/sei-cosmos/x/capability/capability_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package capability_test - -import ( - "testing" - - tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types" - "github.com/stretchr/testify/suite" - - seiapp "github.com/sei-protocol/sei-chain/app" - "github.com/sei-protocol/sei-chain/sei-cosmos/codec" - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/types/module" - banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -type CapabilityTestSuite struct { - suite.Suite - - cdc codec.Codec - ctx sdk.Context - app *seiapp.App - keeper *keeper.Keeper - module module.AppModule -} - -func (suite *CapabilityTestSuite) SetupTest() { - checkTx := false - app := seiapp.Setup(suite.T(), checkTx, false, false) - cdc := app.AppCodec() - - // create new keeper so we can define custom scoping before init and seal - keeper := keeper.NewKeeper(cdc, app.GetKey(types.StoreKey), app.GetMemKey(types.MemStoreKey)) - - suite.app = app - suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 1}) - suite.keeper = keeper - suite.cdc = cdc - suite.module = capability.NewAppModule(cdc, *keeper) -} - -// The following test case mocks a specific bug discovered in https://github.com/cosmos/cosmos-sdk/issues/9800 -// and ensures that the current code successfully fixes the issue. -func (suite *CapabilityTestSuite) TestInitializeMemStore() { - // mock statesync by creating new keeper that shares persistent state but loses in-memory map - newKeeper := keeper.NewKeeper(suite.cdc, suite.app.GetKey(types.StoreKey), suite.app.GetMemKey("mem_capability")) - newSk1 := newKeeper.ScopeToModule(banktypes.ModuleName) - - cap1, err := newSk1.NewCapability(suite.ctx, "transfer") - suite.Require().NoError(err) - suite.Require().NotNil(cap1) - - // Mock App startup - ctx := suite.app.BaseApp.NewUncachedContext(false, tmproto.Header{}) - newKeeper.Seal() - suite.Require().False(newKeeper.IsInitialized(ctx), "memstore initialized flag set before BeginBlock") - - // Mock app beginblock and ensure that no gas has been consumed and memstore is initialized - ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) - capability.BeginBlocker(ctx, *newKeeper) - suite.Require().True(newKeeper.IsInitialized(ctx), "memstore initialized flag not set") - - // Mock the first transaction getting capability and subsequently failing - // by using a cached context and discarding all cached writes. - cacheCtx, _ := ctx.CacheContext() - _, ok := newSk1.GetCapability(cacheCtx, "transfer") - suite.Require().True(ok) - - // Ensure that the second transaction can still receive capability even if first tx fails. - ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) - - cap1, ok = newSk1.GetCapability(ctx, "transfer") - suite.Require().True(ok) - - // Ensure the capabilities don't get reinitialized on next BeginBlock - // by testing to see if capability returns same pointer - // also check that initialized flag is still set - capability.BeginBlocker(ctx, *newKeeper) - recap, ok := newSk1.GetCapability(ctx, "transfer") - suite.Require().True(ok) - suite.Require().Equal(cap1, recap, "capabilities got reinitialized after second BeginBlock") - suite.Require().True(newKeeper.IsInitialized(ctx), "memstore initialized flag not set") -} - -func TestCapabilityTestSuite(t *testing.T) { - suite.Run(t, new(CapabilityTestSuite)) -} diff --git a/sei-cosmos/x/capability/genesis.go b/sei-cosmos/x/capability/genesis.go deleted file mode 100644 index f4f96aca75..0000000000 --- a/sei-cosmos/x/capability/genesis.go +++ /dev/null @@ -1,46 +0,0 @@ -package capability - -import ( - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -// InitGenesis initializes the capability module's state from a provided genesis -// state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { - if err := k.InitializeIndex(ctx, genState.Index); err != nil { - panic(err) - } - - // set owners for each index - for _, genOwner := range genState.Owners { - k.SetOwners(ctx, genOwner.Index, genOwner.IndexOwners) - } - // initialize in-memory capabilities - k.InitMemStore(ctx) -} - -// ExportGenesis returns the capability module's exported genesis. -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { - index := k.GetLatestIndex(ctx) - owners := []types.GenesisOwners{} - - for i := uint64(1); i < index; i++ { - capabilityOwners, ok := k.GetOwners(ctx, i) - if !ok || len(capabilityOwners.Owners) == 0 { - continue - } - - genOwner := types.GenesisOwners{ - Index: i, - IndexOwners: capabilityOwners, - } - owners = append(owners, genOwner) - } - - return &types.GenesisState{ - Index: index, - Owners: owners, - } -} diff --git a/sei-cosmos/x/capability/genesis_test.go b/sei-cosmos/x/capability/genesis_test.go deleted file mode 100644 index f63b01dbcd..0000000000 --- a/sei-cosmos/x/capability/genesis_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package capability_test - -import ( - tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" - - seiapp "github.com/sei-protocol/sei-chain/app" - banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" - stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" -) - -func (suite *CapabilityTestSuite) TestGenesis() { - sk1 := suite.keeper.ScopeToModule(banktypes.ModuleName) - sk2 := suite.keeper.ScopeToModule(stakingtypes.ModuleName) - - cap1, err := sk1.NewCapability(suite.ctx, "transfer") - suite.Require().NoError(err) - suite.Require().NotNil(cap1) - - err = sk2.ClaimCapability(suite.ctx, cap1, "transfer") - suite.Require().NoError(err) - - cap2, err := sk2.NewCapability(suite.ctx, "ica") - suite.Require().NoError(err) - suite.Require().NotNil(cap2) - - genState := capability.ExportGenesis(suite.ctx, *suite.keeper) - - // create new app that does not share persistent or in-memory state - // and initialize app from exported genesis state above. - db := dbm.NewMemDB() - newApp := seiapp.SetupWithDB(suite.T(), db, false, false, false) - - newKeeper := keeper.NewKeeper(suite.cdc, newApp.GetKey(types.StoreKey), newApp.GetMemKey(types.MemStoreKey)) - newSk1 := newKeeper.ScopeToModule(banktypes.ModuleName) - newSk2 := newKeeper.ScopeToModule(stakingtypes.ModuleName) - deliverCtx, _ := newApp.BaseApp.NewUncachedContext(false, tmproto.Header{}).CacheContext() - - capability.InitGenesis(deliverCtx, *newKeeper, *genState) - - // check that all previous capabilities exist in new app after InitGenesis - sk1Cap1, ok := newSk1.GetCapability(deliverCtx, "transfer") - suite.Require().True(ok, "could not get first capability after genesis on first ScopedKeeper") - suite.Require().Equal(*cap1, *sk1Cap1, "capability values not equal on first ScopedKeeper") - - sk2Cap1, ok := newSk2.GetCapability(deliverCtx, "transfer") - suite.Require().True(ok, "could not get first capability after genesis on first ScopedKeeper") - suite.Require().Equal(*cap1, *sk2Cap1, "capability values not equal on first ScopedKeeper") - - sk2Cap2, ok := newSk2.GetCapability(deliverCtx, "ica") - suite.Require().True(ok, "could not get second capability after genesis on second ScopedKeeper") - suite.Require().Equal(*cap2, *sk2Cap2, "capability values not equal on second ScopedKeeper") -} diff --git a/sei-cosmos/x/capability/keeper/keeper.go b/sei-cosmos/x/capability/keeper/keeper.go deleted file mode 100644 index 498aa8c217..0000000000 --- a/sei-cosmos/x/capability/keeper/keeper.go +++ /dev/null @@ -1,475 +0,0 @@ -package keeper - -import ( - "fmt" - "strings" - "sync" - - "github.com/sei-protocol/sei-chain/sei-cosmos/codec" - "github.com/sei-protocol/sei-chain/sei-cosmos/store/prefix" - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" - "github.com/sei-protocol/seilog" -) - -var logger = seilog.NewLogger("cosmos", "x", "capability", "keeper") - -type ( - // Keeper defines the capability module's keeper. It is responsible for provisioning, - // tracking, and authenticating capabilities at runtime. During application - // initialization, the keeper can be hooked up to modules through unique function - // references so that it can identify the calling module when later invoked. - // - // When the initial state is loaded from disk, the keeper allows the ability to - // create new capability keys for all previously allocated capability identifiers - // (allocated during execution of past transactions and assigned to particular modes), - // and keep them in a memory-only store while the chain is running. - // - // The keeper allows the ability to create scoped sub-keepers which are tied to - // a single specific module. - Keeper struct { - cdc codec.BinaryCodec - storeKey sdk.StoreKey - memKey sdk.StoreKey - capMap *sync.Map - scopedModules map[string]struct{} - sealed bool - } - - // ScopedKeeper defines a scoped sub-keeper which is tied to a single specific - // module provisioned by the capability keeper. Scoped keepers must be created - // at application initialization and passed to modules, which can then use them - // to claim capabilities they receive and retrieve capabilities which they own - // by name, in addition to creating new capabilities & authenticating capabilities - // passed by other modules. - ScopedKeeper struct { - cdc codec.BinaryCodec - storeKey sdk.StoreKey - memKey sdk.StoreKey - capMap *sync.Map - module string - } -) - -// NewKeeper constructs a new CapabilityKeeper instance and initializes maps -// for capability map and scopedModules map. -func NewKeeper(cdc codec.BinaryCodec, storeKey, memKey sdk.StoreKey) *Keeper { - return &Keeper{ - cdc: cdc, - storeKey: storeKey, - memKey: memKey, - capMap: &sync.Map{}, - scopedModules: make(map[string]struct{}), - sealed: false, - } -} - -// internCapability returns the canonical *Capability for the given index, -// allocating one on first sight. The returned pointer is stable for the -// lifetime of the keeper, so the pointer-derived forward-lookup key in the -// in-memory store stays consistent for a given index. Addresses the -// long-standing TODO referenced in GetCapability (cosmos-sdk#7805). -func internCapability(m *sync.Map, index uint64) *types.Capability { - actual, _ := m.LoadOrStore(index, types.NewCapability(index)) - return actual.(*types.Capability) -} - -// ScopeToModule attempts to create and return a ScopedKeeper for a given module -// by name. It will panic if the keeper is already sealed or if the module name -// already has a ScopedKeeper. -func (k *Keeper) ScopeToModule(moduleName string) ScopedKeeper { - if k.sealed { - panic("cannot scope to module via a sealed capability keeper") - } - if strings.TrimSpace(moduleName) == "" { - panic("cannot scope to an empty module name") - } - - if _, ok := k.scopedModules[moduleName]; ok { - panic(fmt.Sprintf("cannot create multiple scoped keepers for the same module name: %s", moduleName)) - } - - k.scopedModules[moduleName] = struct{}{} - - return ScopedKeeper{ - cdc: k.cdc, - storeKey: k.storeKey, - memKey: k.memKey, - capMap: k.capMap, - module: moduleName, - } -} - -// Seal seals the keeper to prevent further modules from creating a scoped keeper. -// Seal may be called during app initialization for applications that do not wish to create scoped keepers dynamically. -func (k *Keeper) Seal() { - if k.sealed { - panic("cannot initialize and seal an already sealed capability keeper") - } - - k.sealed = true -} - -// InitMemStore will assure that the module store is a memory store (it will panic if it's not) -// and willl initialize it. The function is safe to be called multiple times. -// InitMemStore must be called every time the app starts before the keeper is used (so -// `BeginBlock` or `InitChain` - whichever is first). We need access to the store so we -// can't initialize it in a constructor. -func (k *Keeper) InitMemStore(ctx sdk.Context) { - memStore := ctx.KVStore(k.memKey) - if storeType := memStore.GetStoreType(); storeType != sdk.StoreTypeMemory { - panic(fmt.Sprintf("invalid memory store type; got %s, expected: %s", storeType, sdk.StoreTypeMemory)) - } - - // check if memory store has not been initialized yet by checking if initialized flag is nil. - if !k.IsInitialized(ctx) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixIndexCapability) - iterator := sdk.KVStorePrefixIterator(prefixStore, nil) - - // initialize the in-memory store for all persisted capabilities - defer func() { _ = iterator.Close() }() - - for ; iterator.Valid(); iterator.Next() { - index := types.IndexFromKey(iterator.Key()) - - var capOwners types.CapabilityOwners - - k.cdc.MustUnmarshal(iterator.Value(), &capOwners) - k.InitializeCapability(ctx, index, capOwners) - } - - // set the initialized flag so we don't rerun initialization logic - memStore.Set(types.KeyMemInitialized, []byte{1}) - } -} - -// IsInitialized returns true if the keeper is properly initialized, and false otherwise. -func (k *Keeper) IsInitialized(ctx sdk.Context) bool { - memStore := ctx.KVStore(k.memKey) - return memStore.Get(types.KeyMemInitialized) != nil -} - -// InitializeIndex sets the index to one (or greater) in InitChain according -// to the GenesisState. It must only be called once. -// It will panic if the provided index is 0, or if the index is already set. -func (k Keeper) InitializeIndex(ctx sdk.Context, index uint64) error { - if index == 0 { - panic("SetIndex requires index > 0") - } - latest := k.GetLatestIndex(ctx) - if latest > 0 { - panic("SetIndex requires index to not be set") - } - - // set the global index to the passed index - store := ctx.KVStore(k.storeKey) - store.Set(types.KeyIndex, types.IndexToKey(index)) - return nil -} - -// GetLatestIndex returns the latest index of the CapabilityKeeper -func (k Keeper) GetLatestIndex(ctx sdk.Context) uint64 { - store := ctx.KVStore(k.storeKey) - return types.IndexFromKey(store.Get(types.KeyIndex)) -} - -// SetOwners set the capability owners to the store -func (k Keeper) SetOwners(ctx sdk.Context, index uint64, owners types.CapabilityOwners) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixIndexCapability) - indexKey := types.IndexToKey(index) - - // set owners in persistent store - prefixStore.Set(indexKey, k.cdc.MustMarshal(&owners)) -} - -// GetOwners returns the capability owners with a given index. -func (k Keeper) GetOwners(ctx sdk.Context, index uint64) (types.CapabilityOwners, bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixIndexCapability) - indexKey := types.IndexToKey(index) - - // get owners for index from persistent store - ownerBytes := prefixStore.Get(indexKey) - if ownerBytes == nil { - return types.CapabilityOwners{}, false - } - var owners types.CapabilityOwners - k.cdc.MustUnmarshal(ownerBytes, &owners) - return owners, true -} - -// InitializeCapability takes in an index and an owners array. It creates the capability in memory -// and sets the fwd and reverse keys for each owner in the memstore. -// It is used during initialization from genesis. -func (k Keeper) InitializeCapability(ctx sdk.Context, index uint64, owners types.CapabilityOwners) { - memStore := ctx.KVStore(k.memKey) - c := internCapability(k.capMap, index) - - for _, owner := range owners.Owners { - // Set the forward mapping between the module and capability tuple and the - // capability name in the memKVStore - memStore.Set(types.FwdCapabilityKey(owner.Module, c), []byte(owner.Name)) - - // Set the reverse mapping between the module and capability name and the - // index in the in-memory store. Since marshalling and unmarshalling into a store - // will change memory address of capability, we simply store index as value here - // and retrieve the in-memory pointer to the capability from our map - memStore.Set(types.RevCapabilityKey(owner.Module, owner.Name), sdk.Uint64ToBigEndian(index)) - } - -} - -// NewCapability attempts to create a new capability with a given name. If the -// capability already exists in the in-memory store, an error will be returned. -// Otherwise, a new capability is created with the current global unique index. -// The newly created capability has the scoped module name and capability name -// tuple set as the initial owner. Finally, the global index is incremented along -// with forward and reverse indexes set in the in-memory store. -// -// Note, namespacing is completely local, which is safe since records are prefixed -// with the module name and no two ScopedKeeper can have the same module name. -func (sk ScopedKeeper) NewCapability(ctx sdk.Context, name string) (*types.Capability, error) { - if strings.TrimSpace(name) == "" { - return nil, sdkerrors.Wrap(types.ErrInvalidCapabilityName, "capability name cannot be empty") - } - store := ctx.KVStore(sk.storeKey) - - if _, ok := sk.GetCapability(ctx, name); ok { - return nil, sdkerrors.Wrapf(types.ErrCapabilityTaken, "module: %s, name: %s", sk.module, name) - } - - // create new capability with the current global index - index := types.IndexFromKey(store.Get(types.KeyIndex)) - capability := internCapability(sk.capMap, index) - - // update capability owner set - if err := sk.addOwner(ctx, capability, name); err != nil { - return nil, err - } - - // increment global index - store.Set(types.KeyIndex, types.IndexToKey(index+1)) - - memStore := ctx.KVStore(sk.memKey) - - // Set the forward mapping between the module and capability tuple and the - // capability name in the memKVStore - memStore.Set(types.FwdCapabilityKey(sk.module, capability), []byte(name)) - - // Set the reverse mapping between the module and capability name and the - // index in the in-memory store. Since marshalling and unmarshalling into a store - // will change memory address of capability, we simply store index as value here - // and retrieve the in-memory pointer to the capability from our map - memStore.Set(types.RevCapabilityKey(sk.module, name), sdk.Uint64ToBigEndian(index)) - - logger.Info("created new capability", "module", sk.module, "name", name) - - return capability, nil -} - -// AuthenticateCapability attempts to authenticate a given capability and name -// from a caller. It allows for a caller to check that a capability does in fact -// correspond to a particular name. The scoped keeper will lookup the capability -// from the internal in-memory store and check against the provided name. It returns -// true upon success and false upon failure. -// -// Note, the capability's forward mapping is indexed by a string which should -// contain its unique memory reference. -func (sk ScopedKeeper) AuthenticateCapability(ctx sdk.Context, c *types.Capability, name string) bool { - if strings.TrimSpace(name) == "" || c == nil { - return false - } - return sk.GetCapabilityName(ctx, c) == name -} - -// ClaimCapability attempts to claim a given Capability. The provided name and -// the scoped module's name tuple are treated as the owner. It will attempt -// to add the owner to the persistent set of capability owners for the capability -// index. If the owner already exists, it will return an error. Otherwise, it will -// also set a forward and reverse index for the capability and capability name. -func (sk ScopedKeeper) ClaimCapability(ctx sdk.Context, c *types.Capability, name string) error { - if c == nil { - return sdkerrors.Wrap(types.ErrNilCapability, "cannot claim nil capability") - } - if strings.TrimSpace(name) == "" { - return sdkerrors.Wrap(types.ErrInvalidCapabilityName, "capability name cannot be empty") - } - c = internCapability(sk.capMap, c.GetIndex()) - - // update capability owner set - if err := sk.addOwner(ctx, c, name); err != nil { - return err - } - - memStore := ctx.KVStore(sk.memKey) - - // Set the forward mapping between the module and capability tuple and the - // capability name in the memKVStore - memStore.Set(types.FwdCapabilityKey(sk.module, c), []byte(name)) - - // Set the reverse mapping between the module and capability name and the - // index in the in-memory store. Since marshalling and unmarshalling into a store - // will change memory address of capability, we simply store index as value here - // and retrieve the in-memory pointer to the capability from our map - memStore.Set(types.RevCapabilityKey(sk.module, name), sdk.Uint64ToBigEndian(c.GetIndex())) - - logger.Info("claimed capability", "module", sk.module, "name", name, "capability", c.GetIndex()) - - return nil -} - -// ReleaseCapability allows a scoped module to release a capability which it had -// previously claimed or created. After releasing the capability, if no more -// owners exist, the capability will be globally removed. -func (sk ScopedKeeper) ReleaseCapability(ctx sdk.Context, c *types.Capability) error { - if c == nil { - return sdkerrors.Wrap(types.ErrNilCapability, "cannot release nil capability") - } - name := sk.GetCapabilityName(ctx, c) - if len(name) == 0 { - return sdkerrors.Wrap(types.ErrCapabilityNotOwned, sk.module) - } - - memStore := ctx.KVStore(sk.memKey) - - // Delete the forward mapping between the module and capability tuple and the - // capability name in the memKVStore - memStore.Delete(types.FwdCapabilityKey(sk.module, c)) - - // Delete the reverse mapping between the module and capability name and the - // index in the in-memory store. - memStore.Delete(types.RevCapabilityKey(sk.module, name)) - - // remove owner - capOwners := sk.getOwners(ctx, c) - capOwners.Remove(types.NewOwner(sk.module, name)) - - prefixStore := prefix.NewStore(ctx.KVStore(sk.storeKey), types.KeyPrefixIndexCapability) - indexKey := types.IndexToKey(c.GetIndex()) - - if len(capOwners.Owners) == 0 { - // remove capability owner set - prefixStore.Delete(indexKey) - // The persistent owners store and the memstore reverse-lookup deleted - // above are authoritative for capability existence; leaving the index - // interned in capMap is harmless. See cosmos-sdk#7805. - } else { - // update capability owner set - prefixStore.Set(indexKey, sk.cdc.MustMarshal(capOwners)) - } - - return nil -} - -// GetCapability allows a module to fetch a capability which it previously claimed -// by name. The module is not allowed to retrieve capabilities which it does not -// own. -func (sk ScopedKeeper) GetCapability(ctx sdk.Context, name string) (*types.Capability, bool) { - if strings.TrimSpace(name) == "" { - return nil, false - } - memStore := ctx.KVStore(sk.memKey) - - key := types.RevCapabilityKey(sk.module, name) - indexBytes := memStore.Get(key) - if len(indexBytes) == 0 { - return nil, false - } - index := sdk.BigEndianToUint64(indexBytes) - - return internCapability(sk.capMap, index), true -} - -// GetCapabilityName allows a module to retrieve the name under which it stored a given -// capability given the capability -func (sk ScopedKeeper) GetCapabilityName(ctx sdk.Context, c *types.Capability) string { - if c == nil { - return "" - } - memStore := ctx.KVStore(sk.memKey) - - return string(memStore.Get(types.FwdCapabilityKey(sk.module, c))) -} - -// GetOwners all the Owners that own the capability associated with the name this ScopedKeeper uses -// to refer to the capability -func (sk ScopedKeeper) GetOwners(ctx sdk.Context, name string) (*types.CapabilityOwners, bool) { - if strings.TrimSpace(name) == "" { - return nil, false - } - c, ok := sk.GetCapability(ctx, name) - if !ok { - return nil, false - } - - prefixStore := prefix.NewStore(ctx.KVStore(sk.storeKey), types.KeyPrefixIndexCapability) - indexKey := types.IndexToKey(c.GetIndex()) - - var capOwners types.CapabilityOwners - - bz := prefixStore.Get(indexKey) - if len(bz) == 0 { - return nil, false - } - - sk.cdc.MustUnmarshal(bz, &capOwners) - - return &capOwners, true -} - -// LookupModules returns all the module owners for a given capability -// as a string array and the capability itself. -// The method returns an error if either the capability or the owners cannot be -// retreived from the memstore. -func (sk ScopedKeeper) LookupModules(ctx sdk.Context, name string) ([]string, *types.Capability, error) { - if strings.TrimSpace(name) == "" { - return nil, nil, sdkerrors.Wrap(types.ErrInvalidCapabilityName, "cannot lookup modules with empty capability name") - } - c, ok := sk.GetCapability(ctx, name) - if !ok { - return nil, nil, sdkerrors.Wrap(types.ErrCapabilityNotFound, name) - } - - capOwners, ok := sk.GetOwners(ctx, name) - if !ok { - return nil, nil, sdkerrors.Wrap(types.ErrCapabilityOwnersNotFound, name) - } - - mods := make([]string, len(capOwners.Owners)) - for i, co := range capOwners.Owners { - mods[i] = co.Module - } - - return mods, c, nil -} - -func (sk ScopedKeeper) addOwner(ctx sdk.Context, c *types.Capability, name string) error { - prefixStore := prefix.NewStore(ctx.KVStore(sk.storeKey), types.KeyPrefixIndexCapability) - indexKey := types.IndexToKey(c.GetIndex()) - - capOwners := sk.getOwners(ctx, c) - - if err := capOwners.Set(types.NewOwner(sk.module, name)); err != nil { - return err - } - - // update capability owner set - prefixStore.Set(indexKey, sk.cdc.MustMarshal(capOwners)) - - return nil -} - -func (sk ScopedKeeper) getOwners(ctx sdk.Context, c *types.Capability) *types.CapabilityOwners { - prefixStore := prefix.NewStore(ctx.KVStore(sk.storeKey), types.KeyPrefixIndexCapability) - indexKey := types.IndexToKey(c.GetIndex()) - - bz := prefixStore.Get(indexKey) - - if len(bz) == 0 { - return types.NewCapabilityOwners() - } - - var capOwners types.CapabilityOwners - sk.cdc.MustUnmarshal(bz, &capOwners) - return &capOwners -} diff --git a/sei-cosmos/x/capability/keeper/keeper_test.go b/sei-cosmos/x/capability/keeper/keeper_test.go deleted file mode 100644 index 115f125483..0000000000 --- a/sei-cosmos/x/capability/keeper/keeper_test.go +++ /dev/null @@ -1,561 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - seiapp "github.com/sei-protocol/sei-chain/app" - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" - stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" - tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types" -) - -// setupKeeper creates a fresh app, context, and capability keeper for a single test. -// It mirrors the original SetupTest hook but is invoked explicitly per test, which makes -// each test self-contained and free of shared state. -func setupKeeper(t *testing.T) (sdk.Context, *keeper.Keeper) { - t.Helper() - - const checkTx = false - app := seiapp.Setup(t, checkTx, false, false) - - // Construct a fresh keeper so the test can define custom scoping before Seal is called. - k := keeper.NewKeeper(app.AppCodec(), app.GetKey(types.StoreKey), app.GetMemKey(types.MemStoreKey)) - ctx := app.BaseApp.NewContext(checkTx, tmproto.Header{Height: 1}) - - return ctx, k -} - -func TestSeal(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - - sk := k.ScopeToModule(banktypes.ModuleName) - require.Panics(t, func() { k.ScopeToModule(" ") }, "whitespace module name must panic") - - // Capture the latest index before creating new capabilities so we can validate that - // indices are assigned contiguously starting from prevIndex. - prevIndex := k.GetLatestIndex(ctx) - - caps := make([]*types.Capability, 5) - for i := range caps { - cap, err := sk.NewCapability(ctx, fmt.Sprintf("transfer-%d", i)) - require.NoError(t, err) - require.NotNil(t, cap) - require.Equal(t, uint64(i)+prevIndex, cap.GetIndex()) - caps[i] = cap - } - - require.NotPanics(t, func() { k.Seal() }) - - // All previously created capabilities remain accessible after Seal. - for i, cap := range caps { - got, ok := sk.GetCapability(ctx, fmt.Sprintf("transfer-%d", i)) - require.True(t, ok) - require.Equal(t, cap, got) - require.Equal(t, uint64(i)+prevIndex, got.GetIndex()) - } - - require.Panics(t, func() { k.Seal() }, "second Seal must panic") - require.Panics(t, func() { _ = k.ScopeToModule(stakingtypes.ModuleName) }, "ScopeToModule after Seal must panic") -} - -func TestNewCapability(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - - // Capability does not exist yet. - got, ok := sk.GetCapability(ctx, "transfer") - require.False(t, ok) - require.Nil(t, got) - - // Create it. - cap, err := sk.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap) - - // Fetching by name returns the exact same pointer. - got, ok = sk.GetCapability(ctx, "transfer") - require.True(t, ok) - require.Same(t, cap, got, "GetCapability must return the same pointer") - - // Unknown names return nothing. - got, ok = sk.GetCapability(ctx, "invalid") - require.False(t, ok) - require.Nil(t, got) - - // Duplicate creation fails and must not mutate the stored capability. - cap2, err := sk.NewCapability(ctx, "transfer") - require.Error(t, err) - require.Nil(t, cap2) - - got, ok = sk.GetCapability(ctx, "transfer") - require.True(t, ok) - require.Same(t, cap, got, "duplicate-creation attempt must not replace stored capability") - - // Whitespace-only names are rejected. - cap, err = sk.NewCapability(ctx, " ") - require.Error(t, err) - require.Nil(t, cap) -} - -func TestAuthenticateCapability(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk1 := k.ScopeToModule(banktypes.ModuleName) - sk2 := k.ScopeToModule(stakingtypes.ModuleName) - - cap1, err := sk1.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap1) - - // A capability minted by index alone (not via the keeper) must not authenticate - // in any scope. This is the core security invariant of object-capability tokens. - forgedCap := types.NewCapability(cap1.Index) - require.False(t, sk1.AuthenticateCapability(ctx, forgedCap, "transfer")) - require.False(t, sk2.AuthenticateCapability(ctx, forgedCap, "transfer")) - - cap2, err := sk2.NewCapability(ctx, "bond") - require.NoError(t, err) - require.NotNil(t, cap2) - - got, ok := sk1.GetCapability(ctx, "transfer") - require.True(t, ok) - - require.True(t, sk1.AuthenticateCapability(ctx, cap1, "transfer")) - require.True(t, sk1.AuthenticateCapability(ctx, got, "transfer")) - require.False(t, sk1.AuthenticateCapability(ctx, cap1, "invalid"), "wrong name must fail auth") - require.False(t, sk1.AuthenticateCapability(ctx, cap2, "transfer"), "wrong scope must fail auth") - - require.True(t, sk2.AuthenticateCapability(ctx, cap2, "bond")) - require.False(t, sk2.AuthenticateCapability(ctx, cap2, "invalid")) - require.False(t, sk2.AuthenticateCapability(ctx, cap1, "bond")) - - // A released capability must no longer authenticate. - require.NoError(t, sk2.ReleaseCapability(ctx, cap2)) - require.False(t, sk2.AuthenticateCapability(ctx, cap2, "bond")) - - // Unknown index, whitespace name, and nil capability all fail to authenticate. - badCap := types.NewCapability(100) - require.False(t, sk1.AuthenticateCapability(ctx, badCap, "transfer")) - require.False(t, sk2.AuthenticateCapability(ctx, badCap, "bond")) - require.False(t, sk1.AuthenticateCapability(ctx, cap1, " ")) - require.False(t, sk1.AuthenticateCapability(ctx, nil, "transfer")) -} - -func TestClaimCapability(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk1 := k.ScopeToModule(banktypes.ModuleName) - sk2 := k.ScopeToModule(stakingtypes.ModuleName) - sk3 := k.ScopeToModule("foo") - - cap, err := sk1.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap) - - // The creating module already owns the capability; re-claiming must error. - require.Error(t, sk1.ClaimCapability(ctx, cap, "transfer")) - // A different module may claim it under the same name. - require.NoError(t, sk2.ClaimCapability(ctx, cap, "transfer")) - - // Both owners must see the capability under that name. - for _, sk := range []keeper.ScopedKeeper{sk1, sk2} { - got, ok := sk.GetCapability(ctx, "transfer") - require.True(t, ok) - require.Equal(t, cap, got) - } - - require.Error(t, sk3.ClaimCapability(ctx, cap, " "), "whitespace name must be rejected") - require.Error(t, sk3.ClaimCapability(ctx, nil, "transfer"), "nil capability must be rejected") -} - -func TestGetOwners(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk1 := k.ScopeToModule(banktypes.ModuleName) - sk2 := k.ScopeToModule(stakingtypes.ModuleName) - sk3 := k.ScopeToModule("foo") - - cap, err := sk1.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap) - - require.NoError(t, sk2.ClaimCapability(ctx, cap, "transfer")) - require.NoError(t, sk3.ClaimCapability(ctx, cap, "transfer")) - - // Helper: every scoped keeper in sks must see the same owner set in expectedOrder. - // Owners are returned in lexicographic order by module name. - assertOwners := func(t *testing.T, sks []keeper.ScopedKeeper, expectedOrder []string) { - t.Helper() - for _, sk := range sks { - owners, ok := sk.GetOwners(ctx, "transfer") - require.True(t, ok, "could not retrieve owners") - require.NotNil(t, owners, "owners is nil") - - mods, gotCap, err := sk.LookupModules(ctx, "transfer") - require.NoError(t, err, "could not retrieve modules") - require.NotNil(t, gotCap, "capability is nil") - require.NotNil(t, mods, "modules is nil") - require.Equal(t, cap, gotCap, "caps not equal") - - require.Len(t, owners.Owners, len(expectedOrder), "unexpected number of owners") - for i, o := range owners.Owners { - require.Equal(t, expectedOrder[i], o.Module, "unexpected module at position %d", i) - require.Equal(t, expectedOrder[i], mods[i], "unexpected module in lookup at position %d", i) - } - } - } - - assertOwners(t, - []keeper.ScopedKeeper{sk1, sk2, sk3}, - []string{banktypes.ModuleName, "foo", stakingtypes.ModuleName}, - ) - - // Once "foo" releases the capability, it disappears from every owner list. - require.NoError(t, sk3.ReleaseCapability(ctx, cap), "could not release capability") - - assertOwners(t, - []keeper.ScopedKeeper{sk1, sk2}, - []string{banktypes.ModuleName, stakingtypes.ModuleName}, - ) - - _, ok := sk1.GetOwners(ctx, " ") - require.False(t, ok, "got owners from whitespace capability name") -} - -func TestReleaseCapability(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk1 := k.ScopeToModule(banktypes.ModuleName) - sk2 := k.ScopeToModule(stakingtypes.ModuleName) - - cap1, err := sk1.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap1) - require.NoError(t, sk2.ClaimCapability(ctx, cap1, "transfer")) - - cap2, err := sk2.NewCapability(ctx, "bond") - require.NoError(t, err) - require.NotNil(t, cap2) - - // sk1 cannot release a capability it does not own. - require.Error(t, sk1.ReleaseCapability(ctx, cap2)) - - // After sk2 releases cap1, sk2 no longer sees it — but sk1 still does. - require.NoError(t, sk2.ReleaseCapability(ctx, cap1)) - got, ok := sk2.GetCapability(ctx, "transfer") - require.False(t, ok) - require.Nil(t, got) - - // sk1 releases its own ownership — the capability is fully gone. - require.NoError(t, sk1.ReleaseCapability(ctx, cap1)) - got, ok = sk1.GetCapability(ctx, "transfer") - require.False(t, ok) - require.Nil(t, got) - - require.Error(t, sk1.ReleaseCapability(ctx, nil)) -} - -func TestCachedCapabilityUsesStableIndexPointer(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - ms := ctx.MultiStore() - - // Two independent cached branches both mint a capability at the same in-memory index. - msCache1 := ms.CacheMultiStore() - cap1, err := sk.NewCapability(ctx.WithMultiStore(msCache1), "transfer") - require.NoError(t, err) - require.NotNil(t, cap1) - - msCache2 := ms.CacheMultiStore() - cap2, err := sk.NewCapability(ctx.WithMultiStore(msCache2), "stake") - require.NoError(t, err) - require.NotNil(t, cap2) - require.Equal(t, cap1, cap2, "both branches see the same index pointer") - - // Commit branch 1 and confirm the capability survives via the root context. - msCache1.Write() - - got, ok := sk.GetCapability(ctx, "transfer") - require.True(t, ok) - require.Equal(t, cap1, got) - require.True(t, sk.AuthenticateCapability(ctx, got, "transfer")) -} - -func TestCachedReleaseKeepsCapabilityIndexAvailable(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - - cap, err := sk.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap) - - // Release the capability on a cached branch — do NOT commit it. - msCache := ctx.MultiStore().CacheMultiStore() - require.NoError(t, sk.ReleaseCapability(ctx.WithMultiStore(msCache), cap)) - - // Root context must still see the capability since the release was never written. - require.NotPanics(t, func() { - got, ok := sk.GetCapability(ctx, "transfer") - require.True(t, ok) - require.Equal(t, cap, got) - }) - require.True(t, sk.AuthenticateCapability(ctx, cap, "transfer")) -} - -func TestRevertCapability(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - - msCache := ctx.MultiStore().CacheMultiStore() - cacheCtx := ctx.WithMultiStore(msCache) - - const capName = "revert" - - // Create the capability on the cached context only. - cap, err := sk.NewCapability(cacheCtx, capName) - require.NoError(t, err, "could not create capability") - - // Cached context sees it. - gotCache, ok := sk.GetCapability(cacheCtx, capName) - require.True(t, ok, "could not retrieve capability from cached context") - require.Equal(t, cap, gotCache, "did not get correct capability from cached context") - - // Root context does NOT see it yet — the write is still pending. - got, ok := sk.GetCapability(ctx, capName) - require.False(t, ok, "retrieved capability from root context before write") - require.Nil(t, got, "capability not nil in root store") - - // Commit and re-check visibility from the root context. - msCache.Write() - - got, ok = sk.GetCapability(ctx, capName) - require.True(t, ok, "could not retrieve capability from root context after write") - require.Equal(t, cap, got, "did not get correct capability from root context after write") -} - -// TestScopeToModule_DuplicateModulePanics covers the third panic branch in -// ScopeToModule (duplicate registration), which the original suite missed. -func TestScopeToModule_DuplicateModulePanics(t *testing.T) { - t.Parallel() - _, k := setupKeeper(t) - _ = k.ScopeToModule(banktypes.ModuleName) - - require.Panics(t, func() { k.ScopeToModule(banktypes.ModuleName) }, - "creating two scoped keepers for the same module name must panic") -} - -// TestSeal_AllowsExistingScopesToMintCapabilities verifies that Seal only blocks -// new ScopeToModule calls — existing ScopedKeepers must remain fully operational. -// Without this, a regression that wires Seal into ScopedKeeper would slip through. -func TestSeal_AllowsExistingScopesToMintCapabilities(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - - k.Seal() - - cap, err := sk.NewCapability(ctx, "post-seal") - require.NoError(t, err, "existing scoped keeper must still mint after Seal") - require.NotNil(t, cap) - - require.True(t, sk.AuthenticateCapability(ctx, cap, "post-seal")) -} - -// TestNewCapability_NameIsolatedAcrossModules exercises the keeper's core -// namespacing invariant: the same capability name in two different modules -// produces two distinct capabilities, each visible only to its owning scope. -func TestNewCapability_NameIsolatedAcrossModules(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk1 := k.ScopeToModule(banktypes.ModuleName) - sk2 := k.ScopeToModule(stakingtypes.ModuleName) - - cap1, err := sk1.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap1) - - cap2, err := sk2.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.NotNil(t, cap2) - - // Distinct capabilities → distinct indices. - require.NotEqual(t, cap1.GetIndex(), cap2.GetIndex(), - "per-module name isolation must produce distinct global indices") - - // Each scope authenticates only its own capability under that name. - require.True(t, sk1.AuthenticateCapability(ctx, cap1, "transfer")) - require.False(t, sk1.AuthenticateCapability(ctx, cap2, "transfer")) - require.True(t, sk2.AuthenticateCapability(ctx, cap2, "transfer")) - require.False(t, sk2.AuthenticateCapability(ctx, cap1, "transfer")) -} - -// TestGetCapability_ScopeIsolation verifies a module cannot retrieve another -// module's capability by name even when the name exists in the system. -func TestGetCapability_ScopeIsolation(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk1 := k.ScopeToModule(banktypes.ModuleName) - sk2 := k.ScopeToModule(stakingtypes.ModuleName) - - _, err := sk1.NewCapability(ctx, "transfer") - require.NoError(t, err) - - // sk2 never claimed "transfer" — it must not be retrievable from that scope. - got, ok := sk2.GetCapability(ctx, "transfer") - require.False(t, ok, "GetCapability must respect scope ownership") - require.Nil(t, got) -} - -// TestInitializeIndex covers both panic branches of InitializeIndex (index == 0 -// and index already set). The success branch is implicitly exercised by app -// genesis bootstrapping in setupKeeper. -func TestInitializeIndex(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - - // index == 0 always panics. - require.Panics(t, func() { _ = k.InitializeIndex(ctx, 0) }, - "InitializeIndex(0) must panic") - - // Bump the global index past zero by minting a capability. - sk := k.ScopeToModule(banktypes.ModuleName) - _, err := sk.NewCapability(ctx, "transfer") - require.NoError(t, err) - require.Greater(t, k.GetLatestIndex(ctx), uint64(0)) - - // With the index now > 0, InitializeIndex must panic regardless of the value. - require.Panics(t, func() { _ = k.InitializeIndex(ctx, 1) }, - "InitializeIndex must panic when the global index is already set") -} - -// TestIsInitialized verifies the memstore-initialization flag is set after app -// setup (genesis runs InitMemStore as part of bringup) and that calling -// InitMemStore again is a safe no-op. -func TestIsInitialized(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - - require.True(t, k.IsInitialized(ctx), - "memstore should be initialized after app setup") - - // Idempotency: repeated calls must not panic and must leave the flag set. - require.NotPanics(t, func() { k.InitMemStore(ctx) }) - require.True(t, k.IsInitialized(ctx)) -} - -// TestGetCapabilityName covers the method directly across its three branches: -// nil input, owning scope, and a non-owning scope. -func TestGetCapabilityName(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - skOther := k.ScopeToModule(stakingtypes.ModuleName) - - // nil capability → empty name (no panic). - require.Empty(t, sk.GetCapabilityName(ctx, nil)) - - cap, err := sk.NewCapability(ctx, "transfer") - require.NoError(t, err) - - // Owning scope returns the registered name. - require.Equal(t, "transfer", sk.GetCapabilityName(ctx, cap)) - - // A different scope that doesn't own this capability must return empty — - // otherwise the OCAP isolation property would leak names across scopes. - require.Empty(t, skOther.GetCapabilityName(ctx, cap), - "non-owning scope must not learn the capability name") -} - -// TestLookupModules_ErrorPaths covers the two error branches in LookupModules -// that the existing TestGetOwners only happy-paths through. -func TestLookupModules_ErrorPaths(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - - // Whitespace name is rejected before any store lookup. - mods, cap, err := sk.LookupModules(ctx, " ") - require.Error(t, err) - require.Nil(t, mods) - require.Nil(t, cap) - - // Non-existent capability returns an error and nil results. - mods, cap, err = sk.LookupModules(ctx, "does-not-exist") - require.Error(t, err) - require.Nil(t, mods) - require.Nil(t, cap) -} - -// TestKeeperGetSetOwners exercises the Keeper-level (not ScopedKeeper-level) -// owner read/write API, which the original suite never touched. This is the -// surface used by genesis import/export. -func TestKeeperGetSetOwners(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - - // Reading a never-set index returns the zero owners and false. - owners, ok := k.GetOwners(ctx, 12345) - require.False(t, ok) - require.Empty(t, owners.Owners) - - // Write a synthetic owners record at a free index and round-trip it. - initial := types.CapabilityOwners{ - Owners: []types.Owner{ - {Module: banktypes.ModuleName, Name: "transfer"}, - {Module: stakingtypes.ModuleName, Name: "transfer"}, - }, - } - k.SetOwners(ctx, 42, initial) - - got, ok := k.GetOwners(ctx, 42) - require.True(t, ok) - require.Equal(t, initial.Owners, got.Owners) - - // As a cross-check, NewCapability should also populate the persistent - // owners store at the capability's own index. - sk := k.ScopeToModule(banktypes.ModuleName) - cap, err := sk.NewCapability(ctx, "from-new") - require.NoError(t, err) - - persisted, ok := k.GetOwners(ctx, cap.GetIndex()) - require.True(t, ok, "NewCapability must populate persistent owners store") - require.Len(t, persisted.Owners, 1) - require.Equal(t, banktypes.ModuleName, persisted.Owners[0].Module) - require.Equal(t, "from-new", persisted.Owners[0].Name) -} - -func TestReleaseCapability_FinalReleaseClearsPersistentEntry(t *testing.T) { - t.Parallel() - ctx, k := setupKeeper(t) - sk := k.ScopeToModule(banktypes.ModuleName) - - cap, err := sk.NewCapability(ctx, "transfer") - require.NoError(t, err) - - // Persistent entry exists immediately after creation. - _, ok := k.GetOwners(ctx, cap.GetIndex()) - require.True(t, ok, "persistent owners entry must exist after creation") - - // Release the only owner. - require.NoError(t, sk.ReleaseCapability(ctx, cap)) - - // Persistent entry must be gone (not just empty). - _, ok = k.GetOwners(ctx, cap.GetIndex()) - require.False(t, ok, "persistent owners entry must be removed after final release") - - // And the in-memory mapping is also clear. - got, found := sk.GetCapability(ctx, "transfer") - require.False(t, found) - require.Nil(t, got) -} diff --git a/sei-cosmos/x/capability/metrics.go b/sei-cosmos/x/capability/metrics.go deleted file mode 100644 index 4ef9a79679..0000000000 --- a/sei-cosmos/x/capability/metrics.go +++ /dev/null @@ -1,33 +0,0 @@ -package capability - -import ( - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/metric" -) - -var ( - meter = otel.Meter("seicosmos_x_capability") - - // finerGrainedBuckets units are in seconds - finerGrainedBuckets = metric.WithExplicitBucketBoundaries( - 0.000025, 0.000050, 0.0001, 0.0005, 0.001, 0.0025, 0.005, 0.010, 0.020, 0.050, 0.075, 0.1, 0.25, 0.5, 1, 10, - ) - - capabilityMetrics = struct { - beginBlockerDuration metric.Float64Histogram - }{ - beginBlockerDuration: must(meter.Float64Histogram( - "capability_begin_blocker_duration", - metric.WithDescription("Duration of capability begin-blocker execution in seconds"), - finerGrainedBuckets, - metric.WithUnit("s"), - )), - } -) - -func must[V any](v V, err error) V { - if err != nil { - panic(err) - } - return v -} diff --git a/sei-cosmos/x/capability/module.go b/sei-cosmos/x/capability/module.go deleted file mode 100644 index 557b73234f..0000000000 --- a/sei-cosmos/x/capability/module.go +++ /dev/null @@ -1,184 +0,0 @@ -package capability - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - abci "github.com/sei-protocol/sei-chain/sei-tendermint/abci/types" - - "github.com/sei-protocol/sei-chain/sei-cosmos/client" - "github.com/sei-protocol/sei-chain/sei-cosmos/codec" - cdctypes "github.com/sei-protocol/sei-chain/sei-cosmos/codec/types" - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/types/module" - simtypes "github.com/sei-protocol/sei-chain/sei-cosmos/types/simulation" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/simulation" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -// AppModuleBasic implements the AppModuleBasic interface for the capability module. -type AppModuleBasic struct { - cdc codec.Codec -} - -func NewAppModuleBasic(cdc codec.Codec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} -} - -// Name returns the capability module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec does nothing. Capability does not support amino. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} - -// RegisterInterfaces registers the module's interface types -func (a AppModuleBasic) RegisterInterfaces(_ cdctypes.InterfaceRegistry) {} - -// DefaultGenesis returns the capability module's default genesis state. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesis()) -} - -// ValidateGenesis performs genesis state validation for the capability module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var genState types.GenesisState - if err := cdc.UnmarshalAsJSON(bz, &genState); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - return genState.Validate() -} - -func (am AppModuleBasic) ValidateGenesisStream(cdc codec.JSONCodec, config client.TxEncodingConfig, genesisCh <-chan json.RawMessage) error { - for genesis := range genesisCh { - err := am.ValidateGenesis(cdc, config, genesis) - if err != nil { - return err - } - } - return nil -} - -// RegisterRESTRoutes registers the capability module's REST service handlers. -func (a AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the capability module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *runtime.ServeMux) { -} - -// GetTxCmd returns the capability module's root tx command. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { return nil } - -// GetQueryCmd returns the capability module's root query command. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { return nil } - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for the capability module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), - keeper: keeper, - } -} - -// Name returns the capability module's name. -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// Route returns the capability module's message routing key. -func (AppModule) Route() sdk.Route { return sdk.Route{} } - -// QuerierRoute returns the capability module's query routing key. -func (AppModule) QuerierRoute() string { return "" } - -// LegacyQuerierHandler returns the capability module's Querier. -func (am AppModule) LegacyQuerierHandler(*codec.LegacyAmino) sdk.Querier { return nil } - -// RegisterServices registers a GRPC query service to respond to the -// module-specific GRPC queries. -func (am AppModule) RegisterServices(module.Configurator) {} - -// RegisterInvariants registers the capability module's invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// InitGenesis performs the capability module's genesis initialization It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the capability module's exported genesis state as raw JSON bytes. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - genState := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(genState) -} - -func (am AppModule) ExportGenesisStream(ctx sdk.Context, cdc codec.JSONCodec) <-chan json.RawMessage { - ch := make(chan json.RawMessage) - go func() { - ch <- am.ExportGenesis(ctx, cdc) - close(ch) - }() - return ch -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } - -// GenerateGenesisState creates a randomized GenState of the capability module. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// ProposalContents performs a no-op -func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { - return nil -} - -// RandomizedParams creates randomized capability param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { - return nil -} - -// RegisterStoreDecoder registers a decoder for capability module's types -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[types.StoreKey] = simulation.NewDecodeStore(am.cdc) -} - -// WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return nil -} diff --git a/sei-cosmos/x/capability/simulation/decoder.go b/sei-cosmos/x/capability/simulation/decoder.go deleted file mode 100644 index 000951d788..0000000000 --- a/sei-cosmos/x/capability/simulation/decoder.go +++ /dev/null @@ -1,33 +0,0 @@ -package simulation - -import ( - "bytes" - "fmt" - - "github.com/sei-protocol/sei-chain/sei-cosmos/codec" - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/types/kv" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -// NewDecodeStore returns a decoder function closure that unmarshals the KVPair's -// Value to the corresponding capability type. -func NewDecodeStore(cdc codec.Codec) func(kvA, kvB kv.Pair) string { - return func(kvA, kvB kv.Pair) string { - switch { - case bytes.Equal(kvA.Key, types.KeyIndex): - idxA := sdk.BigEndianToUint64(kvA.Value) - idxB := sdk.BigEndianToUint64(kvB.Value) - return fmt.Sprintf("Index A: %d\nIndex B: %d\n", idxA, idxB) - - case bytes.HasPrefix(kvA.Key, types.KeyPrefixIndexCapability): - var capOwnersA, capOwnersB types.CapabilityOwners - cdc.MustUnmarshal(kvA.Value, &capOwnersA) - cdc.MustUnmarshal(kvB.Value, &capOwnersB) - return fmt.Sprintf("CapabilityOwners A: %v\nCapabilityOwners B: %v\n", capOwnersA, capOwnersB) - - default: - panic(fmt.Sprintf("invalid %s key prefix %X (%s)", types.ModuleName, kvA.Key, string(kvA.Key))) - } - } -} diff --git a/sei-cosmos/x/capability/simulation/genesis.go b/sei-cosmos/x/capability/simulation/genesis.go deleted file mode 100644 index f8065bae08..0000000000 --- a/sei-cosmos/x/capability/simulation/genesis.go +++ /dev/null @@ -1,39 +0,0 @@ -package simulation - -// DONTCOVER - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/sei-protocol/sei-chain/sei-cosmos/types/module" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -// Simulation parameter constants -const index = "index" - -// GenIndex returns a random global index between 1-1000 -func GenIndex(r *rand.Rand) uint64 { - return uint64(r.Int63n(1000)) + 1 //nolint:gosec // Int63n returns non-negative values -} - -// RandomizedGenState generates a random GenesisState for capability -func RandomizedGenState(simState *module.SimulationState) { - var idx uint64 - - simState.AppParams.GetOrGenerate( - simState.Cdc, index, &idx, simState.Rand, - func(r *rand.Rand) { idx = GenIndex(r) }, - ) - - capabilityGenesis := types.GenesisState{Index: idx} - - bz, err := json.MarshalIndent(&capabilityGenesis, "", " ") - if err != nil { - panic(err) - } - fmt.Printf("Selected randomly generated %s parameters:\n%s\n", types.ModuleName, bz) - simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&capabilityGenesis) -} diff --git a/sei-cosmos/x/capability/spec/01_concepts.md b/sei-cosmos/x/capability/spec/01_concepts.md deleted file mode 100644 index 7751df4c08..0000000000 --- a/sei-cosmos/x/capability/spec/01_concepts.md +++ /dev/null @@ -1,34 +0,0 @@ - - -# Concepts - -## Capabilities - -Capabilities are multi-owner. A scoped keeper can create a capability via `NewCapability` -which creates a new unique, unforgeable object-capability reference. The newly -created capability is automatically persisted; the calling module need not call -`ClaimCapability`. Calling `NewCapability` will create the capability with the -calling module and name as a tuple to be treated the capabilities first owner. - -Capabilities can be claimed by other modules which add them as owners. `ClaimCapability` -allows a module to claim a capability key which it has received from another -module so that future `GetCapability` calls will succeed. `ClaimCapability` MUST -be called if a module which receives a capability wishes to access it by name in -the future. Again, capabilities are multi-owner, so if multiple modules have a -single Capability reference, they will all own it. If a module receives a capability -from another module but does not call `ClaimCapability`, it may use it in the executing -transaction but will not be able to access it afterwards. - -`AuthenticateCapability` can be called by any module to check that a capability -does in fact correspond to a particular name (the name can be un-trusted user input) -with which the calling module previously associated it. - -`GetCapability` allows a module to fetch a capability which it has previously -claimed by name. The module is not allowed to retrieve capabilities which it does -not own. - -## Stores - -- MemStore diff --git a/sei-cosmos/x/capability/spec/02_state.md b/sei-cosmos/x/capability/spec/02_state.md deleted file mode 100644 index b93de4bf4a..0000000000 --- a/sei-cosmos/x/capability/spec/02_state.md +++ /dev/null @@ -1,11 +0,0 @@ - - -# State - -## Index - -## CapabilityOwners - -## Capability diff --git a/sei-cosmos/x/capability/spec/README.md b/sei-cosmos/x/capability/spec/README.md deleted file mode 100644 index ec612ba976..0000000000 --- a/sei-cosmos/x/capability/spec/README.md +++ /dev/null @@ -1,76 +0,0 @@ - - -# `capability` - -## Overview - -`x/capability` is an implementation of a Cosmos SDK module, per [ADR 003](./../../../docs/architecture/adr-003-dynamic-capability-store.md), -that allows for provisioning, tracking, and authenticating multi-owner capabilities -at runtime. - -The keeper maintains two states: persistent and ephemeral in-memory. The persistent -store maintains a globally unique auto-incrementing index and a mapping from -capability index to a set of capability owners that are defined as a module and -capability name tuple. The in-memory ephemeral state keeps track of the actual -capabilities, represented as addresses in local memory, with both forward and reverse indexes. -The forward index maps module name and capability tuples to the capability name. The -reverse index maps between the module and capability name and the capability itself. - -The keeper allows the creation of "scoped" sub-keepers which are tied to a particular -module by name. Scoped keepers must be created at application initialization and -passed to modules, which can then use them to claim capabilities they receive and -retrieve capabilities which they own by name, in addition to creating new capabilities -& authenticating capabilities passed by other modules. A scoped keeper cannot escape its scope, -so a module cannot interfere with or inspect capabilities owned by other modules. - -The keeper provides no other core functionality that can be found in other modules -like queriers, REST and CLI handlers, and genesis state. - -## Initialization - -During application initialization, the keeper must be instantiated with a persistent -store key and an in-memory store key. - -```go -type App struct { - // ... - - capabilityKeeper *capability.Keeper -} - -func NewApp(...) *App { - // ... - - app.capabilityKeeper = capability.NewKeeper(codec, persistentStoreKey, memStoreKey) -} -``` - -After the keeper is created, it can be used to create scoped sub-keepers which -are passed to other modules that can create, authenticate, and claim capabilities. -After all the necessary scoped keepers are created and the state is loaded, the -main capability keeper must be initialized and sealed to populate the in-memory -state and to prevent further scoped keepers from being created. - -```go -func NewApp(...) *App { - // ... - - // Initialize and seal the capability keeper so all persistent capabilities - // are loaded in-memory and prevent any further modules from creating scoped - // sub-keepers. - ctx := app.BaseApp.NewContext(true, tmproto.Header{}) - app.capabilityKeeper.InitializeAndSeal(ctx) - - return app -} -``` - -## Contents - -1. **[Concepts](01_concepts.md)** -1. **[State](02_state.md)** diff --git a/sei-cosmos/x/capability/types/capability.pb.go b/sei-cosmos/x/capability/types/capability.pb.go deleted file mode 100644 index a4b10775e0..0000000000 --- a/sei-cosmos/x/capability/types/capability.pb.go +++ /dev/null @@ -1,703 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/capability/v1beta1/capability.proto - -package types - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Capability defines an implementation of an object capability. The index -// provided to a Capability must be globally unique. -type Capability struct { - Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty" yaml:"index"` -} - -func (m *Capability) Reset() { *m = Capability{} } -func (*Capability) ProtoMessage() {} -func (*Capability) Descriptor() ([]byte, []int) { - return fileDescriptor_6308261edd8470a9, []int{0} -} -func (m *Capability) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Capability) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Capability.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Capability) XXX_Merge(src proto.Message) { - xxx_messageInfo_Capability.Merge(m, src) -} -func (m *Capability) XXX_Size() int { - return m.Size() -} -func (m *Capability) XXX_DiscardUnknown() { - xxx_messageInfo_Capability.DiscardUnknown(m) -} - -var xxx_messageInfo_Capability proto.InternalMessageInfo - -func (m *Capability) GetIndex() uint64 { - if m != nil { - return m.Index - } - return 0 -} - -// Owner defines a single capability owner. An owner is defined by the name of -// capability and the module name. -type Owner struct { - Module string `protobuf:"bytes,1,opt,name=module,proto3" json:"module,omitempty" yaml:"module"` - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty" yaml:"name"` -} - -func (m *Owner) Reset() { *m = Owner{} } -func (*Owner) ProtoMessage() {} -func (*Owner) Descriptor() ([]byte, []int) { - return fileDescriptor_6308261edd8470a9, []int{1} -} -func (m *Owner) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Owner) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Owner.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Owner) XXX_Merge(src proto.Message) { - xxx_messageInfo_Owner.Merge(m, src) -} -func (m *Owner) XXX_Size() int { - return m.Size() -} -func (m *Owner) XXX_DiscardUnknown() { - xxx_messageInfo_Owner.DiscardUnknown(m) -} - -var xxx_messageInfo_Owner proto.InternalMessageInfo - -// CapabilityOwners defines a set of owners of a single Capability. The set of -// owners must be unique. -type CapabilityOwners struct { - Owners []Owner `protobuf:"bytes,1,rep,name=owners,proto3" json:"owners"` -} - -func (m *CapabilityOwners) Reset() { *m = CapabilityOwners{} } -func (m *CapabilityOwners) String() string { return proto.CompactTextString(m) } -func (*CapabilityOwners) ProtoMessage() {} -func (*CapabilityOwners) Descriptor() ([]byte, []int) { - return fileDescriptor_6308261edd8470a9, []int{2} -} -func (m *CapabilityOwners) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CapabilityOwners) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CapabilityOwners.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CapabilityOwners) XXX_Merge(src proto.Message) { - xxx_messageInfo_CapabilityOwners.Merge(m, src) -} -func (m *CapabilityOwners) XXX_Size() int { - return m.Size() -} -func (m *CapabilityOwners) XXX_DiscardUnknown() { - xxx_messageInfo_CapabilityOwners.DiscardUnknown(m) -} - -var xxx_messageInfo_CapabilityOwners proto.InternalMessageInfo - -func (m *CapabilityOwners) GetOwners() []Owner { - if m != nil { - return m.Owners - } - return nil -} - -func init() { - proto.RegisterType((*Capability)(nil), "cosmos.capability.v1beta1.Capability") - proto.RegisterType((*Owner)(nil), "cosmos.capability.v1beta1.Owner") - proto.RegisterType((*CapabilityOwners)(nil), "cosmos.capability.v1beta1.CapabilityOwners") -} - -func init() { - proto.RegisterFile("cosmos/capability/v1beta1/capability.proto", fileDescriptor_6308261edd8470a9) -} - -var fileDescriptor_6308261edd8470a9 = []byte{ - // 310 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4a, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x4f, 0x4e, 0x2c, 0x48, 0x4c, 0xca, 0xcc, 0xc9, 0x2c, 0xa9, 0xd4, 0x2f, 0x33, - 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0x44, 0x12, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x84, - 0xa8, 0xd5, 0x43, 0x92, 0x80, 0xaa, 0x95, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xab, 0xd2, 0x07, - 0xb1, 0x20, 0x1a, 0x94, 0xac, 0xb8, 0xb8, 0x9c, 0xe1, 0x6a, 0x85, 0xd4, 0xb8, 0x58, 0x33, 0xf3, - 0x52, 0x52, 0x2b, 0x24, 0x18, 0x15, 0x18, 0x35, 0x58, 0x9c, 0x04, 0x3e, 0xdd, 0x93, 0xe7, 0xa9, - 0x4c, 0xcc, 0xcd, 0xb1, 0x52, 0x02, 0x0b, 0x2b, 0x05, 0x41, 0xa4, 0xad, 0x58, 0x66, 0x2c, 0x90, - 0x67, 0x50, 0x4a, 0xe4, 0x62, 0xf5, 0x2f, 0xcf, 0x4b, 0x2d, 0x12, 0xd2, 0xe4, 0x62, 0xcb, 0xcd, - 0x4f, 0x29, 0xcd, 0x49, 0x05, 0xeb, 0xe3, 0x74, 0x12, 0xfc, 0x74, 0x4f, 0x9e, 0x17, 0xa2, 0x0f, - 0x22, 0xae, 0x14, 0x04, 0x55, 0x20, 0xa4, 0xcc, 0xc5, 0x92, 0x97, 0x98, 0x9b, 0x2a, 0xc1, 0x04, - 0x56, 0xc8, 0xff, 0xe9, 0x9e, 0x3c, 0x37, 0x44, 0x21, 0x48, 0x54, 0x29, 0x08, 0x2c, 0x69, 0xc5, - 0xd1, 0xb1, 0x40, 0x9e, 0x01, 0x6c, 0x45, 0x10, 0x97, 0x00, 0xc2, 0x79, 0x60, 0xcb, 0x8a, 0x85, - 0xec, 0xb8, 0xd8, 0xf2, 0xc1, 0x2c, 0x09, 0x46, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x05, 0x3d, 0x9c, - 0x9e, 0xd6, 0x03, 0x6b, 0x71, 0x62, 0x39, 0x71, 0x4f, 0x9e, 0x21, 0x08, 0xaa, 0xcb, 0x29, 0xf2, - 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, - 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xec, 0xd3, 0x33, 0x4b, 0x32, 0x4a, - 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x8b, 0x53, 0x33, 0x75, 0xc1, 0x41, 0x94, 0x9c, 0x9f, 0x03, - 0xe6, 0x24, 0x67, 0x24, 0x66, 0xe6, 0x41, 0x58, 0x90, 0xf8, 0xa8, 0x40, 0x8e, 0x91, 0x92, 0xca, - 0x82, 0xd4, 0xe2, 0x24, 0x36, 0xb0, 0x0e, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x95, - 0xc9, 0x81, 0xb3, 0x01, 0x00, 0x00, -} - -func (m *Capability) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Capability) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Capability) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Index != 0 { - i = encodeVarintCapability(dAtA, i, uint64(m.Index)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Owner) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Owner) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Owner) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Name) > 0 { - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintCapability(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0x12 - } - if len(m.Module) > 0 { - i -= len(m.Module) - copy(dAtA[i:], m.Module) - i = encodeVarintCapability(dAtA, i, uint64(len(m.Module))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CapabilityOwners) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CapabilityOwners) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CapabilityOwners) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Owners) > 0 { - for iNdEx := len(m.Owners) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Owners[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCapability(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintCapability(dAtA []byte, offset int, v uint64) int { - offset -= sovCapability(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Capability) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Index != 0 { - n += 1 + sovCapability(uint64(m.Index)) - } - return n -} - -func (m *Owner) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Module) - if l > 0 { - n += 1 + l + sovCapability(uint64(l)) - } - l = len(m.Name) - if l > 0 { - n += 1 + l + sovCapability(uint64(l)) - } - return n -} - -func (m *CapabilityOwners) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Owners) > 0 { - for _, e := range m.Owners { - l = e.Size() - n += 1 + l + sovCapability(uint64(l)) - } - } - return n -} - -func sovCapability(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozCapability(x uint64) (n int) { - return sovCapability(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Capability) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCapability - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Capability: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Capability: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - m.Index = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCapability - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Index |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipCapability(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCapability - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Owner) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCapability - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Owner: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Owner: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Module", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCapability - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthCapability - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCapability - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Module = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCapability - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthCapability - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCapability - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCapability(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCapability - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CapabilityOwners) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCapability - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CapabilityOwners: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CapabilityOwners: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owners", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCapability - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCapability - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCapability - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owners = append(m.Owners, Owner{}) - if err := m.Owners[len(m.Owners)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCapability(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCapability - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipCapability(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowCapability - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowCapability - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowCapability - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthCapability - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupCapability - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthCapability - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthCapability = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowCapability = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupCapability = fmt.Errorf("proto: unexpected end of group") -) diff --git a/sei-cosmos/x/capability/types/errors.go b/sei-cosmos/x/capability/types/errors.go deleted file mode 100644 index 09baed0e9f..0000000000 --- a/sei-cosmos/x/capability/types/errors.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -// DONTCOVER - -import ( - sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" -) - -// x/capability module sentinel errors -var ( - ErrInvalidCapabilityName = sdkerrors.Register(ModuleName, 2, "capability name not valid") - ErrNilCapability = sdkerrors.Register(ModuleName, 3, "provided capability is nil") - ErrCapabilityTaken = sdkerrors.Register(ModuleName, 4, "capability name already taken") - ErrOwnerClaimed = sdkerrors.Register(ModuleName, 5, "given owner already claimed capability") - ErrCapabilityNotOwned = sdkerrors.Register(ModuleName, 6, "capability not owned by module") - ErrCapabilityNotFound = sdkerrors.Register(ModuleName, 7, "capability not found") - ErrCapabilityOwnersNotFound = sdkerrors.Register(ModuleName, 8, "owners not found for capability") -) diff --git a/sei-cosmos/x/capability/types/genesis.go b/sei-cosmos/x/capability/types/genesis.go deleted file mode 100644 index afab1d0c7d..0000000000 --- a/sei-cosmos/x/capability/types/genesis.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import ( - "fmt" - "strings" -) - -// DefaultIndex is the default capability global index -const DefaultIndex uint64 = 1 - -// DefaultGenesis returns the default Capability genesis state -func DefaultGenesis() *GenesisState { - return &GenesisState{ - Index: DefaultIndex, - Owners: []GenesisOwners{}, - } -} - -// Validate performs basic genesis state validation returning an error upon any -// failure. -func (gs GenesisState) Validate() error { - // NOTE: index must be greater than 0 - if gs.Index == 0 { - return fmt.Errorf("capability index must be non-zero") - } - - for _, genOwner := range gs.Owners { - if len(genOwner.IndexOwners.Owners) == 0 { - return fmt.Errorf("empty owners in genesis") - } - - // all exported existing indices must be between [1, gs.Index) - if genOwner.Index == 0 || genOwner.Index >= gs.Index { - return fmt.Errorf("owners exist for index %d outside of valid range: %d-%d", genOwner.Index, 1, gs.Index-1) - } - - for _, owner := range genOwner.IndexOwners.Owners { - if strings.TrimSpace(owner.Module) == "" { - return fmt.Errorf("owner's module cannot be blank: %s", owner) - } - - if strings.TrimSpace(owner.Name) == "" { - return fmt.Errorf("owner's name cannot be blank: %s", owner) - } - } - } - - return nil -} diff --git a/sei-cosmos/x/capability/types/genesis.pb.go b/sei-cosmos/x/capability/types/genesis.pb.go deleted file mode 100644 index 18a946c78f..0000000000 --- a/sei-cosmos/x/capability/types/genesis.pb.go +++ /dev/null @@ -1,586 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/capability/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisOwners defines the capability owners with their corresponding index. -type GenesisOwners struct { - // index is the index of the capability owner. - Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"` - // index_owners are the owners at the given index. - IndexOwners CapabilityOwners `protobuf:"bytes,2,opt,name=index_owners,json=indexOwners,proto3" json:"index_owners" yaml:"index_owners"` -} - -func (m *GenesisOwners) Reset() { *m = GenesisOwners{} } -func (m *GenesisOwners) String() string { return proto.CompactTextString(m) } -func (*GenesisOwners) ProtoMessage() {} -func (*GenesisOwners) Descriptor() ([]byte, []int) { - return fileDescriptor_94922dd16a11c23e, []int{0} -} -func (m *GenesisOwners) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisOwners) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisOwners.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisOwners) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisOwners.Merge(m, src) -} -func (m *GenesisOwners) XXX_Size() int { - return m.Size() -} -func (m *GenesisOwners) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisOwners.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisOwners proto.InternalMessageInfo - -func (m *GenesisOwners) GetIndex() uint64 { - if m != nil { - return m.Index - } - return 0 -} - -func (m *GenesisOwners) GetIndexOwners() CapabilityOwners { - if m != nil { - return m.IndexOwners - } - return CapabilityOwners{} -} - -// GenesisState defines the capability module's genesis state. -type GenesisState struct { - // index is the capability global index. - Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"` - // owners represents a map from index to owners of the capability index - // index key is string to allow amino marshalling. - Owners []GenesisOwners `protobuf:"bytes,2,rep,name=owners,proto3" json:"owners"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_94922dd16a11c23e, []int{1} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetIndex() uint64 { - if m != nil { - return m.Index - } - return 0 -} - -func (m *GenesisState) GetOwners() []GenesisOwners { - if m != nil { - return m.Owners - } - return nil -} - -func init() { - proto.RegisterType((*GenesisOwners)(nil), "cosmos.capability.v1beta1.GenesisOwners") - proto.RegisterType((*GenesisState)(nil), "cosmos.capability.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("cosmos/capability/v1beta1/genesis.proto", fileDescriptor_94922dd16a11c23e) -} - -var fileDescriptor_94922dd16a11c23e = []byte{ - // 291 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4f, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x4f, 0x4e, 0x2c, 0x48, 0x4c, 0xca, 0xcc, 0xc9, 0x2c, 0xa9, 0xd4, 0x2f, 0x33, - 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, - 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x84, 0x28, 0xd4, 0x43, 0x28, 0xd4, 0x83, 0x2a, 0x94, 0xd2, 0xc2, - 0x6d, 0x06, 0x92, 0x6a, 0xb0, 0x31, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0xa6, 0x3e, 0x88, - 0x05, 0x11, 0x55, 0x9a, 0xc4, 0xc8, 0xc5, 0xeb, 0x0e, 0xb1, 0xce, 0xbf, 0x3c, 0x2f, 0xb5, 0xa8, - 0x58, 0x48, 0x84, 0x8b, 0x35, 0x33, 0x2f, 0x25, 0xb5, 0x42, 0x82, 0x51, 0x81, 0x51, 0x83, 0x25, - 0x08, 0xc2, 0x11, 0xca, 0xe6, 0xe2, 0x01, 0x33, 0xe2, 0xf3, 0xc1, 0xaa, 0x24, 0x98, 0x14, 0x18, - 0x35, 0xb8, 0x8d, 0xb4, 0xf5, 0x70, 0xba, 0x4d, 0xcf, 0x19, 0x2e, 0x04, 0x31, 0xd8, 0x49, 0xfa, - 0xc4, 0x3d, 0x79, 0x86, 0x4f, 0xf7, 0xe4, 0x85, 0x2b, 0x13, 0x73, 0x73, 0xac, 0x94, 0x90, 0x8d, - 0x53, 0x0a, 0xe2, 0x06, 0x73, 0x21, 0x2a, 0x95, 0x72, 0xb8, 0x78, 0xa0, 0x6e, 0x0a, 0x2e, 0x49, - 0x2c, 0x49, 0xc5, 0xe1, 0x24, 0x37, 0x2e, 0x36, 0xb8, 0x63, 0x98, 0x35, 0xb8, 0x8d, 0x34, 0xf0, - 0x38, 0x06, 0xc5, 0x8b, 0x4e, 0x2c, 0x20, 0x97, 0x04, 0x41, 0x75, 0x3b, 0x45, 0x9e, 0x78, 0x24, - 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, - 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x7d, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, - 0x72, 0x7e, 0xae, 0x7e, 0x71, 0x6a, 0xa6, 0x2e, 0x38, 0xc8, 0x92, 0xf3, 0x73, 0xc0, 0x9c, 0xe4, - 0x8c, 0xc4, 0xcc, 0x3c, 0x08, 0x0b, 0x12, 0x09, 0x15, 0xc8, 0xd1, 0x50, 0x52, 0x59, 0x90, 0x5a, - 0x9c, 0xc4, 0x06, 0xd6, 0x61, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x7b, 0x96, 0xd0, 0x2a, 0xec, - 0x01, 0x00, 0x00, -} - -func (m *GenesisOwners) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisOwners) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisOwners) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.IndexOwners.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.Index != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Index)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Owners) > 0 { - for iNdEx := len(m.Owners) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Owners[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Index != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Index)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisOwners) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Index != 0 { - n += 1 + sovGenesis(uint64(m.Index)) - } - l = m.IndexOwners.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Index != 0 { - n += 1 + sovGenesis(uint64(m.Index)) - } - if len(m.Owners) > 0 { - for _, e := range m.Owners { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisOwners) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisOwners: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisOwners: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - m.Index = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Index |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IndexOwners", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IndexOwners.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - m.Index = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Index |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owners", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owners = append(m.Owners, GenesisOwners{}) - if err := m.Owners[len(m.Owners)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/sei-cosmos/x/capability/types/genesis_test.go b/sei-cosmos/x/capability/types/genesis_test.go deleted file mode 100644 index d8a02e0192..0000000000 --- a/sei-cosmos/x/capability/types/genesis_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestValidateGenesis(t *testing.T) { - testCases := []struct { - name string - malleate func(*GenesisState) - expPass bool - }{ - { - name: "default", - malleate: func(_ *GenesisState) {}, - expPass: true, - }, - { - name: "valid genesis state", - malleate: func(genState *GenesisState) { - genState.Index = 10 - genOwner := GenesisOwners{ - Index: 1, - IndexOwners: CapabilityOwners{[]Owner{{Module: "ibc", Name: "port/transfer"}}}, - } - - genState.Owners = append(genState.Owners, genOwner) - }, - expPass: true, - }, - { - name: "initial index is 0", - malleate: func(genState *GenesisState) { - genState.Index = 0 - genOwner := GenesisOwners{ - Index: 0, - IndexOwners: CapabilityOwners{[]Owner{{Module: "ibc", Name: "port/transfer"}}}, - } - - genState.Owners = append(genState.Owners, genOwner) - - }, - expPass: false, - }, - - { - name: "blank owner module", - malleate: func(genState *GenesisState) { - genState.Index = 1 - genOwner := GenesisOwners{ - Index: 1, - IndexOwners: CapabilityOwners{[]Owner{{Module: "", Name: "port/transfer"}}}, - } - - genState.Owners = append(genState.Owners, genOwner) - - }, - expPass: false, - }, - { - name: "blank owner name", - malleate: func(genState *GenesisState) { - genState.Index = 1 - genOwner := GenesisOwners{ - Index: 1, - IndexOwners: CapabilityOwners{[]Owner{{Module: "ibc", Name: ""}}}, - } - - genState.Owners = append(genState.Owners, genOwner) - - }, - expPass: false, - }, - { - name: "index above range", - malleate: func(genState *GenesisState) { - genState.Index = 10 - genOwner := GenesisOwners{ - Index: 12, - IndexOwners: CapabilityOwners{[]Owner{{Module: "ibc", Name: "port/transfer"}}}, - } - - genState.Owners = append(genState.Owners, genOwner) - - }, - expPass: false, - }, - { - name: "index below range", - malleate: func(genState *GenesisState) { - genState.Index = 10 - genOwner := GenesisOwners{ - Index: 0, - IndexOwners: CapabilityOwners{[]Owner{{Module: "ibc", Name: "port/transfer"}}}, - } - - genState.Owners = append(genState.Owners, genOwner) - - }, - expPass: false, - }, - { - name: "owners are empty", - malleate: func(genState *GenesisState) { - genState.Index = 10 - genOwner := GenesisOwners{ - Index: 0, - IndexOwners: CapabilityOwners{[]Owner{}}, - } - - genState.Owners = append(genState.Owners, genOwner) - - }, - expPass: false, - }, - } - - for _, tc := range testCases { - tc := tc - genState := DefaultGenesis() - tc.malleate(genState) - err := genState.Validate() - if tc.expPass { - require.NoError(t, err, tc.name) - } else { - require.Error(t, err, tc.name) - } - } -} diff --git a/sei-cosmos/x/capability/types/keys.go b/sei-cosmos/x/capability/types/keys.go deleted file mode 100644 index 698a783082..0000000000 --- a/sei-cosmos/x/capability/types/keys.go +++ /dev/null @@ -1,61 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" -) - -const ( - // ModuleName defines the module name - ModuleName = "capability" - - // StoreKey defines the primary module store key - StoreKey = ModuleName - - // MemStoreKey defines the in-memory store key - MemStoreKey = "mem_capability" -) - -var ( - // KeyIndex defines the key that stores the current globally unique capability - // index. - KeyIndex = []byte("index") - - // KeyPrefixIndexCapability defines a key prefix that stores index to capability - // name mappings. - KeyPrefixIndexCapability = []byte("capability_index") - - // KeyMemInitialized defines the key that stores the initialized flag in the memory store - KeyMemInitialized = []byte("mem_initialized") -) - -// RevCapabilityKey returns a reverse lookup key for a given module and capability -// name. -func RevCapabilityKey(module, name string) []byte { - return []byte(fmt.Sprintf("%s/rev/%s", module, name)) -} - -// FwdCapabilityKey returns a forward lookup key for a given module and capability -// reference. -func FwdCapabilityKey(module string, cap *Capability) []byte { - // encode the key to a fixed length to avoid breaking consensus state machine - // it's a hacky backport of https://github.com/cosmos/cosmos-sdk/pull/11737 - // the length 10 is picked so it's backward compatible on common architectures. - key := fmt.Sprintf("%#010p", cap) - if len(key) > 10 { - key = key[len(key)-10:] - } - return []byte(fmt.Sprintf("%s/fwd/0x%s", module, key)) -} - -// IndexToKey returns bytes to be used as a key for a given capability index. -func IndexToKey(index uint64) []byte { - return sdk.Uint64ToBigEndian(index) -} - -// IndexFromKey returns an index from a call to IndexToKey for a given capability -// index. -func IndexFromKey(key []byte) uint64 { - return sdk.BigEndianToUint64(key) -} diff --git a/sei-cosmos/x/capability/types/keys_test.go b/sei-cosmos/x/capability/types/keys_test.go deleted file mode 100644 index bdb670fbd6..0000000000 --- a/sei-cosmos/x/capability/types/keys_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package types_test - -import ( - "fmt" - "runtime" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -func TestRevCapabilityKey(t *testing.T) { - expected := []byte("bank/rev/send") - require.Equal(t, expected, types.RevCapabilityKey("bank", "send")) -} - -func TestFwdCapabilityKey(t *testing.T) { - cap := types.NewCapability(23) - key := fmt.Sprintf("%#010p", cap) - if len(key) > 10 { - key = key[len(key)-10:] - } - require.Equal(t, 10, len(key)) - expected := []byte(fmt.Sprintf("bank/fwd/0x%s", key)) - require.Equal(t, expected, types.FwdCapabilityKey("bank", cap)) -} - -func TestIndexToKey(t *testing.T) { - require.Equal(t, []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc, 0x5a}, types.IndexToKey(3162)) -} - -func TestIndexFromKey(t *testing.T) { - require.Equal(t, uint64(3162), types.IndexFromKey([]byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc, 0x5a})) -} - -// to test the backward compatibiltiy of the new function -func legacyFwdCapabilityKey(module string, cap *types.Capability) []byte { - return []byte(fmt.Sprintf("%s/fwd/%p", module, cap)) -} - -func TestFwdCapabilityKeyCompatibility(t *testing.T) { - cap := types.NewCapability(24) - new := types.FwdCapabilityKey("bank", cap) - old := legacyFwdCapabilityKey("bank", cap) - if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { - require.Equal(t, len(old), len(new)+1) - } else { - require.Equal(t, new, old) - } -} diff --git a/sei-cosmos/x/capability/types/types.go b/sei-cosmos/x/capability/types/types.go deleted file mode 100644 index b713077921..0000000000 --- a/sei-cosmos/x/capability/types/types.go +++ /dev/null @@ -1,87 +0,0 @@ -package types - -import ( - "fmt" - "sort" - - yaml "gopkg.in/yaml.v2" - - sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" -) - -// NewCapability returns a reference to a new Capability to be used as an -// actual capability. -func NewCapability(index uint64) *Capability { - return &Capability{Index: index} -} - -// String returns the string representation of a Capability. The string contains -// the Capability's memory reference as the string is to be used in a composite -// key and to authenticate capabilities. -func (ck *Capability) String() string { - return fmt.Sprintf("Capability{%p, %d}", ck, ck.Index) -} - -func NewOwner(module, name string) Owner { - return Owner{Module: module, Name: name} -} - -// Key returns a composite key for an Owner. -func (o Owner) Key() string { - return fmt.Sprintf("%s/%s", o.Module, o.Name) -} - -func (o Owner) String() string { - bz, _ := yaml.Marshal(o) - return string(bz) -} - -func NewCapabilityOwners() *CapabilityOwners { - return &CapabilityOwners{Owners: make([]Owner, 0)} -} - -// Set attempts to add a given owner to the CapabilityOwners. If the owner -// already exists, an error will be returned. Set runs in O(log n) average time -// and O(n) in the worst case. -func (co *CapabilityOwners) Set(owner Owner) error { - i, ok := co.Get(owner) - if ok { - // owner already exists at co.Owners[i] - return sdkerrors.Wrapf(ErrOwnerClaimed, "%s", owner.String()) - } - - // owner does not exist in the set of owners, so we insert at position i - co.Owners = append(co.Owners, Owner{}) // expand by 1 in amortized O(1) / O(n) worst case - copy(co.Owners[i+1:], co.Owners[i:]) - co.Owners[i] = owner - - return nil -} - -// Remove removes a provided owner from the CapabilityOwners if it exists. If the -// owner does not exist, Remove is considered a no-op. -func (co *CapabilityOwners) Remove(owner Owner) { - if len(co.Owners) == 0 { - return - } - - i, ok := co.Get(owner) - if ok { - // owner exists at co.Owners[i] - co.Owners = append(co.Owners[:i], co.Owners[i+1:]...) - } -} - -// Get returns (i, true) of the provided owner in the CapabilityOwners if the -// owner exists, where i indicates the owner's index in the set. Otherwise -// (i, false) where i indicates where in the set the owner should be added. -func (co *CapabilityOwners) Get(owner Owner) (int, bool) { - // find smallest index s.t. co.Owners[i] >= owner in O(log n) time - i := sort.Search(len(co.Owners), func(i int) bool { return co.Owners[i].Key() >= owner.Key() }) - if i < len(co.Owners) && co.Owners[i].Key() == owner.Key() { - // owner exists at co.Owners[i] - return i, true - } - - return i, false -} diff --git a/sei-cosmos/x/capability/types/types_test.go b/sei-cosmos/x/capability/types/types_test.go deleted file mode 100644 index ea8f4e90e2..0000000000 --- a/sei-cosmos/x/capability/types/types_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package types_test - -import ( - "fmt" - "sort" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" -) - -func TestCapabilityKey(t *testing.T) { - idx := uint64(3162) - cap := types.NewCapability(idx) - require.Equal(t, idx, cap.GetIndex()) - require.Equal(t, fmt.Sprintf("Capability{%p, %d}", cap, idx), cap.String()) -} - -func TestOwner(t *testing.T) { - o := types.NewOwner("bank", "send") - require.Equal(t, "bank/send", o.Key()) - require.Equal(t, "module: bank\nname: send\n", o.String()) -} - -func TestCapabilityOwners_Set(t *testing.T) { - co := types.NewCapabilityOwners() - - owners := make([]types.Owner, 1024) - for i := range owners { - var owner types.Owner - - if i%2 == 0 { - owner = types.NewOwner("bank", fmt.Sprintf("send-%d", i)) - } else { - owner = types.NewOwner("slashing", fmt.Sprintf("slash-%d", i)) - } - - owners[i] = owner - require.NoError(t, co.Set(owner)) - } - - sort.Slice(owners, func(i, j int) bool { return owners[i].Key() < owners[j].Key() }) - require.Equal(t, owners, co.Owners) - - for _, owner := range owners { - require.Error(t, co.Set(owner)) - } -} - -func TestCapabilityOwners_Remove(t *testing.T) { - co := types.NewCapabilityOwners() - - co.Remove(types.NewOwner("bank", "send-0")) - require.Len(t, co.Owners, 0) - - for i := 0; i < 5; i++ { - require.NoError(t, co.Set(types.NewOwner("bank", fmt.Sprintf("send-%d", i)))) - } - - require.Len(t, co.Owners, 5) - - for i := 0; i < 5; i++ { - co.Remove(types.NewOwner("bank", fmt.Sprintf("send-%d", i))) - require.Len(t, co.Owners, 5-(i+1)) - } - - require.Len(t, co.Owners, 0) -} diff --git a/sei-db/common/keys/store_keys.go b/sei-db/common/keys/store_keys.go index 7a284264e7..8cac111594 100644 --- a/sei-db/common/keys/store_keys.go +++ b/sei-db/common/keys/store_keys.go @@ -24,7 +24,7 @@ const ( FeegrantStoreKey = "feegrant" // retained for historical state access EvidenceStoreKey = "evidence" // sei-cosmos/x/evidence/types.StoreKey IBCTransferStoreKey = "transfer" // sei-ibc-go/modules/apps/transfer/types.StoreKey - CapabilityStoreKey = "capability" // sei-cosmos/x/capability/types.StoreKey + CapabilityStoreKey = "capability" // retained for historical state access OracleStoreKey = "oracle" // x/oracle/types.StoreKey EVMStoreKey = "evm" // x/evm/types.StoreKey WasmStoreKey = "wasm" // sei-wasmd/x/wasm/types.StoreKey diff --git a/sei-ibc-go/modules/apps/transfer/ibc_module.go b/sei-ibc-go/modules/apps/transfer/ibc_module.go index dfabe28ccd..1fa3095c8c 100644 --- a/sei-ibc-go/modules/apps/transfer/ibc_module.go +++ b/sei-ibc-go/modules/apps/transfer/ibc_module.go @@ -7,13 +7,11 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/apps/transfer/keeper" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/apps/transfer/types" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" porttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/05-port/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" ibcexported "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" ) @@ -68,7 +66,6 @@ func (im IBCModule) OnChanOpenInit( connectionHops []string, portID string, channelID string, - chanCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, version string, ) error { @@ -80,11 +77,6 @@ func (im IBCModule) OnChanOpenInit( return sdkerrors.Wrapf(types.ErrInvalidVersion, "got %s, expected %s", version, types.Version) } - // Claim channel capability passed back by IBC module - if err := im.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return err - } - return nil } @@ -95,7 +87,6 @@ func (im IBCModule) OnChanOpenTry( connectionHops []string, portID, channelID string, - chanCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, counterpartyVersion string, ) (string, error) { @@ -107,17 +98,6 @@ func (im IBCModule) OnChanOpenTry( return "", sdkerrors.Wrapf(types.ErrInvalidVersion, "invalid counterparty version: got: %s, expected %s", counterpartyVersion, types.Version) } - // Module may have already claimed capability in OnChanOpenInit in the case of crossing hellos - // (ie chainA and chainB both call ChanOpenInit before one of them calls ChanOpenTry) - // If module can already authenticate the capability then module already owns it so we don't need to claim - // Otherwise, module does not have channel capability and we must claim it from IBC - if !im.keeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - // Only claim channel capability passed back by IBC module if we do not already own it - if err := im.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return "", err - } - } - return types.Version, nil } diff --git a/sei-ibc-go/modules/apps/transfer/keeper/genesis.go b/sei-ibc-go/modules/apps/transfer/keeper/genesis.go index 8e5cc76da3..6674004632 100644 --- a/sei-ibc-go/modules/apps/transfer/keeper/genesis.go +++ b/sei-ibc-go/modules/apps/transfer/keeper/genesis.go @@ -8,7 +8,7 @@ import ( "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/apps/transfer/types" ) -// InitGenesis initializes the ibc-transfer state and binds to PortID. +// InitGenesis initializes the ibc-transfer state. func (k Keeper) InitGenesis(ctx sdk.Context, state types.GenesisState) { k.SetPort(ctx, state.PortId) @@ -16,17 +16,6 @@ func (k Keeper) InitGenesis(ctx sdk.Context, state types.GenesisState) { k.SetDenomTrace(ctx, trace) } - // Only try to bind to port if it is not already bound, since we may already own - // port capability from capability InitGenesis - if !k.IsBound(ctx, state.PortId) { - // transfer module binds to the transfer port on InitChain - // and claims the returned capability - err := k.BindPort(ctx, state.PortId) - if err != nil { - panic(fmt.Sprintf("could not claim port capability: %v", err)) - } - } - k.SetParams(ctx, state.Params) // check if the module account exists diff --git a/sei-ibc-go/modules/apps/transfer/keeper/keeper.go b/sei-ibc-go/modules/apps/transfer/keeper/keeper.go index 5180692668..d44d80b846 100644 --- a/sei-ibc-go/modules/apps/transfer/keeper/keeper.go +++ b/sei-ibc-go/modules/apps/transfer/keeper/keeper.go @@ -5,11 +5,8 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/store/prefix" sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" authtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/types" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" paramtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/types" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/apps/transfer/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" tmbytes "github.com/sei-protocol/sei-chain/sei-tendermint/libs/bytes" ) @@ -21,10 +18,8 @@ type Keeper struct { ics4Wrapper types.ICS4Wrapper channelKeeper types.ChannelKeeper - portKeeper types.PortKeeper authKeeper types.AccountKeeper bankKeeper types.BankKeeper - scopedKeeper capabilitykeeper.ScopedKeeper addressHandler types.AddressHandler } @@ -32,8 +27,8 @@ type Keeper struct { // NewKeeper creates a new IBC transfer Keeper instance func NewKeeper( cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, - ics4Wrapper types.ICS4Wrapper, channelKeeper types.ChannelKeeper, portKeeper types.PortKeeper, - authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, scopedKeeper capabilitykeeper.ScopedKeeper, + ics4Wrapper types.ICS4Wrapper, channelKeeper types.ChannelKeeper, + authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, ) Keeper { // ensure ibc transfer module account is set if addr := authKeeper.GetModuleAddress(types.ModuleName); addr == nil { @@ -51,10 +46,8 @@ func NewKeeper( paramSpace: paramSpace, ics4Wrapper: ics4Wrapper, channelKeeper: channelKeeper, - portKeeper: portKeeper, authKeeper: authKeeper, bankKeeper: bankKeeper, - scopedKeeper: scopedKeeper, addressHandler: types.SeiAddressHandler{}, } } @@ -62,11 +55,11 @@ func NewKeeper( // NewKeeperWithAddressHandler creates a new IBC transfer Keeper instance with an address handler func NewKeeperWithAddressHandler( cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, - ics4Wrapper types.ICS4Wrapper, channelKeeper types.ChannelKeeper, portKeeper types.PortKeeper, - authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, scopedKeeper capabilitykeeper.ScopedKeeper, + ics4Wrapper types.ICS4Wrapper, channelKeeper types.ChannelKeeper, + authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, addressHandler types.AddressHandler, ) Keeper { - keeper := NewKeeper(cdc, key, paramSpace, ics4Wrapper, channelKeeper, portKeeper, authKeeper, bankKeeper, scopedKeeper) + keeper := NewKeeper(cdc, key, paramSpace, ics4Wrapper, channelKeeper, authKeeper, bankKeeper) if keeper.addressHandler = addressHandler; keeper.addressHandler == nil { panic("the IBC transfer module address handler has not been set") } @@ -78,19 +71,6 @@ func (k Keeper) GetTransferAccount(ctx sdk.Context) authtypes.ModuleAccountI { return k.authKeeper.GetModuleAccount(ctx, types.ModuleName) } -// IsBound checks if the transfer module is already bound to the desired port -func (k Keeper) IsBound(ctx sdk.Context, portID string) bool { - _, ok := k.scopedKeeper.GetCapability(ctx, host.PortPath(portID)) - return ok -} - -// BindPort defines a wrapper function for the ort Keeper's function in -// order to expose it to module's InitGenesis function -func (k Keeper) BindPort(ctx sdk.Context, portID string) error { - cap := k.portKeeper.BindPort(ctx, portID) - return k.ClaimCapability(ctx, cap, host.PortPath(portID)) -} - // GetPort returns the portID for the transfer module. Used in ExportGenesis func (k Keeper) GetPort(ctx sdk.Context) string { store := ctx.KVStore(k.storeKey) @@ -154,14 +134,3 @@ func (k Keeper) IterateDenomTraces(ctx sdk.Context, cb func(denomTrace types.Den } } } - -// AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function -func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool { - return k.scopedKeeper.AuthenticateCapability(ctx, cap, name) -} - -// ClaimCapability allows the transfer module that can claim a capability that IBC module -// passes to it -func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - return k.scopedKeeper.ClaimCapability(ctx, cap, name) -} diff --git a/sei-ibc-go/modules/apps/transfer/keeper/relay.go b/sei-ibc-go/modules/apps/transfer/keeper/relay.go index 63b17b608f..a39519a95b 100644 --- a/sei-ibc-go/modules/apps/transfer/keeper/relay.go +++ b/sei-ibc-go/modules/apps/transfer/keeper/relay.go @@ -14,7 +14,7 @@ import ( "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/apps/transfer/types" clienttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/02-client/types" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" + porttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/05-port/types" coretypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/types" ) @@ -88,6 +88,11 @@ func (k Keeper) sendTransfer( timeoutTimestamp uint64, memo string, ) (uint64, error) { + expectedPort := k.GetPort(ctx) + if sourcePort != expectedPort { + return 0, sdkerrors.Wrapf(porttypes.ErrInvalidPort, "invalid port: %s, expected %s", sourcePort, expectedPort) + } + if !k.GetSendEnabled(ctx) { return 0, types.ErrSendDisabled } @@ -119,10 +124,6 @@ func (k Keeper) sendTransfer( // begin createOutgoingPacket logic // See spec for this logic: https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#packet-relay - channelCap, ok := k.scopedKeeper.GetCapability(ctx, host.ChannelCapabilityPath(sourcePort, sourceChannel)) - if !ok { - return 0, sdkerrors.Wrap(channeltypes.ErrChannelCapabilityNotFound, "module does not own channel capability") - } // NOTE: denomination and hex hash correctness checked during msg.ValidateBasic fullDenomPath := token.Denom @@ -198,7 +199,7 @@ func (k Keeper) sendTransfer( timeoutTimestamp, ) - if err := k.ics4Wrapper.SendPacket(ctx, channelCap, packet); err != nil { + if err := k.ics4Wrapper.SendPacket(ctx, packet); err != nil { return 0, err } diff --git a/sei-ibc-go/modules/apps/transfer/keeper/relay_test.go b/sei-ibc-go/modules/apps/transfer/keeper/relay_test.go new file mode 100644 index 0000000000..bdbe71488b --- /dev/null +++ b/sei-ibc-go/modules/apps/transfer/keeper/relay_test.go @@ -0,0 +1,40 @@ +package keeper + +import ( + "testing" + + "github.com/stretchr/testify/require" + tmdb "github.com/tendermint/tm-db" + + "github.com/sei-protocol/sei-chain/sei-cosmos/store" + sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" + tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types" + + clienttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/02-client/types" + porttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/05-port/types" +) + +func TestSendTransferRejectsForeignPort(t *testing.T) { + storeKey := sdk.NewKVStoreKey("transfer") + db := tmdb.NewMemDB() + stateStore := store.NewCommitMultiStore(db) + stateStore.MountStoreWithDB(storeKey, sdk.StoreTypeIAVL, db) + require.NoError(t, stateStore.LoadLatestVersion()) + + ctx := sdk.NewContext(stateStore, tmproto.Header{}, false) + k := Keeper{storeKey: storeKey} + k.SetPort(ctx, "transfer") + + _, err := k.sendTransfer( + ctx, + "wasm.contract", + "channel-0", + sdk.Coin{}, + nil, + "receiver", + clienttypes.Height{}, + 0, + "", + ) + require.ErrorIs(t, err, porttypes.ErrInvalidPort) +} diff --git a/sei-ibc-go/modules/apps/transfer/types/expected_keepers.go b/sei-ibc-go/modules/apps/transfer/types/expected_keepers.go index c7d3c466c2..bcaa813e68 100644 --- a/sei-ibc-go/modules/apps/transfer/types/expected_keepers.go +++ b/sei-ibc-go/modules/apps/transfer/types/expected_keepers.go @@ -3,7 +3,6 @@ package types import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" connectiontypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/03-connection/types" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" @@ -29,7 +28,7 @@ type BankKeeper interface { // ICS4Wrapper defines the expected ICS4Wrapper for middleware type ICS4Wrapper interface { - SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error + SendPacket(ctx sdk.Context, packet ibcexported.PacketI) error } // ChannelKeeper defines the expected IBC channel keeper @@ -47,8 +46,3 @@ type ClientKeeper interface { type ConnectionKeeper interface { GetConnection(ctx sdk.Context, connectionID string) (connection connectiontypes.ConnectionEnd, found bool) } - -// PortKeeper defines the expected IBC port keeper -type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability -} diff --git a/sei-ibc-go/modules/core/04-channel/keeper/handshake.go b/sei-ibc-go/modules/core/04-channel/keeper/handshake.go index 99433b41d4..131054509d 100644 --- a/sei-ibc-go/modules/core/04-channel/keeper/handshake.go +++ b/sei-ibc-go/modules/core/04-channel/keeper/handshake.go @@ -6,13 +6,10 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/telemetry" sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" "github.com/sei-protocol/seilog" connectiontypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/03-connection/types" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" - porttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/05-port/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" ) @@ -32,24 +29,23 @@ func (k Keeper) ChanOpenInit( order types.Order, connectionHops []string, portID string, - portCap *capabilitytypes.Capability, counterparty types.Counterparty, version string, -) (string, *capabilitytypes.Capability, error) { +) (string, error) { // outbound gating: disallow outbound channel inits when outbound disabled if !k.IsOutboundEnabled(ctx) { - return "", nil, sdkerrors.Wrap(ErrOutboundDisabledHandshake, "channel outbound disabled") + return "", sdkerrors.Wrap(ErrOutboundDisabledHandshake, "channel outbound disabled") } // connection hop length checked on msg.ValidateBasic() connectionEnd, found := k.connectionKeeper.GetConnection(ctx, connectionHops[0]) if !found { - return "", nil, sdkerrors.Wrap(connectiontypes.ErrConnectionNotFound, connectionHops[0]) + return "", sdkerrors.Wrap(connectiontypes.ErrConnectionNotFound, connectionHops[0]) } getVersions := connectionEnd.GetVersions() if len(getVersions) != 1 { - return "", nil, sdkerrors.Wrapf( + return "", sdkerrors.Wrapf( connectiontypes.ErrInvalidVersion, "single version must be negotiated on connection before opening channel, got: %v", getVersions, @@ -57,25 +53,16 @@ func (k Keeper) ChanOpenInit( } if !connectiontypes.VerifySupportedFeature(getVersions[0], order.String()) { - return "", nil, sdkerrors.Wrapf( + return "", sdkerrors.Wrapf( connectiontypes.ErrInvalidVersion, "connection version %s does not support channel ordering: %s", getVersions[0], order.String(), ) } - if !k.portKeeper.Authenticate(ctx, portCap, portID) { - return "", nil, sdkerrors.Wrapf(porttypes.ErrInvalidPort, "caller does not own port capability for port ID %s", portID) - } - channelID := k.GenerateChannelIdentifier(ctx) - capKey, err := k.scopedKeeper.NewCapability(ctx, host.ChannelCapabilityPath(portID, channelID)) - if err != nil { - return "", nil, sdkerrors.Wrapf(err, "could not create channel capability for port ID %s and channel ID %s", portID, channelID) - } - - return channelID, capKey, nil + return channelID, nil } // WriteOpenInitChannel writes a channel which has successfully passed the OpenInit handshake step. @@ -116,15 +103,14 @@ func (k Keeper) ChanOpenTry( connectionHops []string, portID, previousChannelID string, - portCap *capabilitytypes.Capability, counterparty types.Counterparty, counterpartyVersion string, proofInit []byte, proofHeight exported.Height, -) (string, *capabilitytypes.Capability, error) { +) (string, error) { // inbound gating: disallow inbound channel tries when inbound disabled if !k.IsInboundEnabled(ctx) { - return "", nil, sdkerrors.Wrap(ErrInboundDisabledHandshake, "channel inbound disabled") + return "", sdkerrors.Wrap(ErrInboundDisabledHandshake, "channel inbound disabled") } var ( @@ -136,7 +122,7 @@ func (k Keeper) ChanOpenTry( // connection hops only supports a single connection if len(connectionHops) != 1 { - return "", nil, sdkerrors.Wrapf(types.ErrTooManyConnectionHops, "expected 1, got %d", len(connectionHops)) + return "", sdkerrors.Wrapf(types.ErrTooManyConnectionHops, "expected 1, got %d", len(connectionHops)) } // empty channel identifier indicates continuing a previous channel handshake @@ -145,7 +131,7 @@ func (k Keeper) ChanOpenTry( // ensure that the previous channel exists previousChannel, previousChannelFound = k.GetChannel(ctx, portID, previousChannelID) if !previousChannelFound { - return "", nil, sdkerrors.Wrapf(types.ErrInvalidChannel, "previous channel does not exist for supplied previous channelID %s", previousChannelID) + return "", sdkerrors.Wrapf(types.ErrInvalidChannel, "previous channel does not exist for supplied previous channelID %s", previousChannelID) } // previous channel must use the same fields if previousChannel.Ordering != order || @@ -153,11 +139,11 @@ func (k Keeper) ChanOpenTry( previousChannel.Counterparty.ChannelId != "" || previousChannel.ConnectionHops[0] != connectionHops[0] || // ChanOpenInit will only set a single connection hop previousChannel.Version != counterpartyVersion { - return "", nil, sdkerrors.Wrap(types.ErrInvalidChannel, "channel fields mismatch previous channel fields") + return "", sdkerrors.Wrap(types.ErrInvalidChannel, "channel fields mismatch previous channel fields") } if previousChannel.State != types.INIT { - return "", nil, sdkerrors.Wrapf(types.ErrInvalidChannelState, "previous channel state is in %s, expected INIT", previousChannel.State) + return "", sdkerrors.Wrapf(types.ErrInvalidChannelState, "previous channel state is in %s, expected INIT", previousChannel.State) } } else { @@ -165,17 +151,13 @@ func (k Keeper) ChanOpenTry( channelID = k.GenerateChannelIdentifier(ctx) } - if !k.portKeeper.Authenticate(ctx, portCap, portID) { - return "", nil, sdkerrors.Wrapf(porttypes.ErrInvalidPort, "caller does not own port capability for port ID %s", portID) - } - connectionEnd, found := k.connectionKeeper.GetConnection(ctx, connectionHops[0]) if !found { - return "", nil, sdkerrors.Wrap(connectiontypes.ErrConnectionNotFound, connectionHops[0]) + return "", sdkerrors.Wrap(connectiontypes.ErrConnectionNotFound, connectionHops[0]) } if connectionEnd.GetState() != int32(connectiontypes.OPEN) { - return "", nil, sdkerrors.Wrapf( + return "", sdkerrors.Wrapf( connectiontypes.ErrInvalidConnectionState, "connection state is not OPEN (got %s)", connectiontypes.State(connectionEnd.GetState()).String(), ) @@ -183,7 +165,7 @@ func (k Keeper) ChanOpenTry( getVersions := connectionEnd.GetVersions() if len(getVersions) != 1 { - return "", nil, sdkerrors.Wrapf( + return "", sdkerrors.Wrapf( connectiontypes.ErrInvalidVersion, "single version must be negotiated on connection before opening channel, got: %v", getVersions, @@ -191,7 +173,7 @@ func (k Keeper) ChanOpenTry( } if !connectiontypes.VerifySupportedFeature(getVersions[0], order.String()) { - return "", nil, sdkerrors.Wrapf( + return "", sdkerrors.Wrapf( connectiontypes.ErrInvalidVersion, "connection version %s does not support channel ordering: %s", getVersions[0], order.String(), @@ -212,31 +194,10 @@ func (k Keeper) ChanOpenTry( ctx, connectionEnd, proofHeight, proofInit, counterparty.PortId, counterparty.ChannelId, expectedChannel, ); err != nil { - return "", nil, err - } - - var ( - capKey *capabilitytypes.Capability - err error - ) - - if !previousChannelFound { - capKey, err = k.scopedKeeper.NewCapability(ctx, host.ChannelCapabilityPath(portID, channelID)) - if err != nil { - return "", nil, sdkerrors.Wrapf(err, "could not create channel capability for port ID %s and channel ID %s", portID, channelID) - } - - } else { - // capability initialized in ChanOpenInit - capKey, found = k.scopedKeeper.GetCapability(ctx, host.ChannelCapabilityPath(portID, channelID)) - if !found { - return "", nil, sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, - "capability not found for existing channel, portID (%s) channelID (%s)", portID, channelID, - ) - } + return "", err } - return channelID, capKey, nil + return channelID, nil } // WriteOpenTryChannel writes a channel which has successfully passed the OpenTry handshake step. @@ -279,7 +240,6 @@ func (k Keeper) ChanOpenAck( ctx sdk.Context, portID, channelID string, - chanCap *capabilitytypes.Capability, counterpartyVersion, counterpartyChannelID string, proofTry []byte, @@ -297,10 +257,6 @@ func (k Keeper) ChanOpenAck( ) } - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", portID, channelID) - } - connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { return sdkerrors.Wrap(connectiontypes.ErrConnectionNotFound, channel.ConnectionHops[0]) @@ -369,7 +325,6 @@ func (k Keeper) ChanOpenConfirm( ctx sdk.Context, portID, channelID string, - chanCap *capabilitytypes.Capability, proofAck []byte, proofHeight exported.Height, ) error { @@ -385,10 +340,6 @@ func (k Keeper) ChanOpenConfirm( ) } - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", portID, channelID) - } - connectionEnd, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0]) if !found { return sdkerrors.Wrap(connectiontypes.ErrConnectionNotFound, channel.ConnectionHops[0]) @@ -456,12 +407,7 @@ func (k Keeper) ChanCloseInit( ctx sdk.Context, portID, channelID string, - chanCap *capabilitytypes.Capability, ) error { - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", portID, channelID) - } - channel, found := k.GetChannel(ctx, portID, channelID) if !found { return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) @@ -505,14 +451,9 @@ func (k Keeper) ChanCloseConfirm( ctx sdk.Context, portID, channelID string, - chanCap *capabilitytypes.Capability, proofInit []byte, proofHeight exported.Height, ) error { - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - return sdkerrors.Wrap(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)") - } - channel, found := k.GetChannel(ctx, portID, channelID) if !found { return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) diff --git a/sei-ibc-go/modules/core/04-channel/keeper/keeper.go b/sei-ibc-go/modules/core/04-channel/keeper/keeper.go index cdc980916d..e679709c96 100644 --- a/sei-ibc-go/modules/core/04-channel/keeper/keeper.go +++ b/sei-ibc-go/modules/core/04-channel/keeper/keeper.go @@ -7,8 +7,6 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/codec" sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" paramtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/types" db "github.com/tendermint/tm-db" @@ -32,15 +30,12 @@ type Keeper struct { paramSpace paramtypes.Subspace clientKeeper types.ClientKeeper connectionKeeper types.ConnectionKeeper - portKeeper types.PortKeeper - scopedKeeper capabilitykeeper.ScopedKeeper } // NewKeeper creates a new IBC channel Keeper instance func NewKeeper( cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, clientKeeper types.ClientKeeper, connectionKeeper types.ConnectionKeeper, - portKeeper types.PortKeeper, scopedKeeper capabilitykeeper.ScopedKeeper, ) Keeper { return Keeper{ storeKey: key, @@ -48,8 +43,6 @@ func NewKeeper( paramSpace: paramSpace, clientKeeper: clientKeeper, connectionKeeper: connectionKeeper, - portKeeper: portKeeper, - scopedKeeper: scopedKeeper, } } @@ -447,16 +440,6 @@ func (k Keeper) GetChannelConnection(ctx sdk.Context, portID, channelID string) return connectionID, connection, nil } -// LookupModuleByChannel will return the IBCModule along with the capability associated with a given channel defined by its portID and channelID -func (k Keeper) LookupModuleByChannel(ctx sdk.Context, portID, channelID string) (string, *capabilitytypes.Capability, error) { - modules, cap, err := k.scopedKeeper.LookupModules(ctx, host.ChannelCapabilityPath(portID, channelID)) - if err != nil { - return "", nil, err - } - - return porttypes.GetModuleOwner(modules), cap, nil -} - // common functionality for IteratePacketCommitment and IteratePacketAcknowledgement func (k Keeper) iterateHashes(_ sdk.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64, hash []byte) bool) { defer func() { _ = iterator.Close() }() diff --git a/sei-ibc-go/modules/core/04-channel/keeper/packet.go b/sei-ibc-go/modules/core/04-channel/keeper/packet.go index 86bc4c6b50..6dce584c08 100644 --- a/sei-ibc-go/modules/core/04-channel/keeper/packet.go +++ b/sei-ibc-go/modules/core/04-channel/keeper/packet.go @@ -6,12 +6,10 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" clienttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/02-client/types" connectiontypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/03-connection/types" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" ) @@ -26,7 +24,6 @@ var ErrInboundDisabled = sdkerrors.Register("ibc-channel", 103, "ibc inbound dis // chain. func (k Keeper) SendPacket( ctx sdk.Context, - channelCap *capabilitytypes.Capability, packet exported.PacketI, ) error { // outbound gating: disallow sending packets when outbound disabled @@ -50,10 +47,6 @@ func (k Keeper) SendPacket( ) } - if !k.scopedKeeper.AuthenticateCapability(ctx, channelCap, host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel())) { - return sdkerrors.Wrapf(types.ErrChannelCapabilityNotFound, "caller does not own capability for channel, port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel()) - } - if packet.GetDestPort() != channel.Counterparty.PortId { return sdkerrors.Wrapf( types.ErrInvalidPacket, @@ -163,7 +156,6 @@ func GetPacketTimeoutErrorMessage(message string, latestTimestamp uint64, timeou // sent on the corresponding channel end on the counterparty chain. func (k Keeper) RecvPacket( ctx sdk.Context, - chanCap *capabilitytypes.Capability, packet exported.PacketI, proof []byte, proofHeight exported.Height, @@ -185,15 +177,6 @@ func (k Keeper) RecvPacket( ) } - // Authenticate capability to ensure caller has authority to receive packet on this channel - capName := host.ChannelCapabilityPath(packet.GetDestPort(), packet.GetDestChannel()) - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrapf( - types.ErrInvalidChannelCapability, - "channel capability failed authentication for capability name %s", capName, - ) - } - // packet must come from the channel's counterparty if packet.GetSourcePort() != channel.Counterparty.PortId { return sdkerrors.Wrapf( @@ -340,7 +323,6 @@ func (k Keeper) RecvPacket( // previously by RecvPacket. func (k Keeper) WriteAcknowledgement( ctx sdk.Context, - chanCap *capabilitytypes.Capability, packet exported.PacketI, acknowledgement exported.Acknowledgement, ) error { @@ -356,15 +338,6 @@ func (k Keeper) WriteAcknowledgement( ) } - // Authenticate capability to ensure caller has authority to receive packet on this channel - capName := host.ChannelCapabilityPath(packet.GetDestPort(), packet.GetDestChannel()) - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrapf( - types.ErrInvalidChannelCapability, - "channel capability failed authentication for capability name %s", capName, - ) - } - // NOTE: IBC app modules might have written the acknowledgement synchronously on // the OnRecvPacket callback so we need to check if the acknowledgement is already // set on the store and return an error if so. @@ -410,7 +383,6 @@ func (k Keeper) WriteAcknowledgement( // It will also increment NextSequenceAck in case of ORDERED channels. func (k Keeper) AcknowledgePacket( ctx sdk.Context, - chanCap *capabilitytypes.Capability, packet exported.PacketI, acknowledgement []byte, proof []byte, @@ -431,15 +403,6 @@ func (k Keeper) AcknowledgePacket( ) } - // Authenticate capability to ensure caller has authority to receive packet on this channel - capName := host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel()) - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrapf( - types.ErrInvalidChannelCapability, - "channel capability failed authentication for capability name %s", capName, - ) - } - // packet must have been sent to the channel's counterparty if packet.GetDestPort() != channel.Counterparty.PortId { return sdkerrors.Wrapf( diff --git a/sei-ibc-go/modules/core/04-channel/keeper/timeout.go b/sei-ibc-go/modules/core/04-channel/keeper/timeout.go index 4e2d094c09..c8cb068375 100644 --- a/sei-ibc-go/modules/core/04-channel/keeper/timeout.go +++ b/sei-ibc-go/modules/core/04-channel/keeper/timeout.go @@ -6,11 +6,9 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" connectiontypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/03-connection/types" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" ) @@ -35,9 +33,6 @@ func (k Keeper) TimeoutPacket( ) } - // NOTE: TimeoutPacket is called by the AnteHandler which acts upon the packet.Route(), - // so the capability authentication can be omitted here - if packet.GetDestPort() != channel.Counterparty.PortId { return sdkerrors.Wrapf( types.ErrInvalidPacket, @@ -135,7 +130,6 @@ func (k Keeper) TimeoutPacket( // CONTRACT: this function must be called in the IBC handler func (k Keeper) TimeoutExecuted( ctx sdk.Context, - chanCap *capabilitytypes.Capability, packet exported.PacketI, ) error { channel, found := k.GetChannel(ctx, packet.GetSourcePort(), packet.GetSourceChannel()) @@ -143,14 +137,6 @@ func (k Keeper) TimeoutExecuted( return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel()) } - capName := host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel()) - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrapf( - types.ErrChannelCapabilityNotFound, - "caller does not own capability for channel with capability name %s", capName, - ) - } - k.deletePacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) if channel.Ordering == types.ORDERED { @@ -182,7 +168,6 @@ func (k Keeper) TimeoutExecuted( // never be received (even if the timeoutHeight has not yet been reached). func (k Keeper) TimeoutOnClose( ctx sdk.Context, - chanCap *capabilitytypes.Capability, packet exported.PacketI, proof, proofClosed []byte, @@ -194,14 +179,6 @@ func (k Keeper) TimeoutOnClose( return sdkerrors.Wrapf(types.ErrChannelNotFound, "port ID (%s) channel ID (%s)", packet.GetSourcePort(), packet.GetSourceChannel()) } - capName := host.ChannelCapabilityPath(packet.GetSourcePort(), packet.GetSourceChannel()) - if !k.scopedKeeper.AuthenticateCapability(ctx, chanCap, capName) { - return sdkerrors.Wrapf( - types.ErrInvalidChannelCapability, - "channel capability failed authentication with capability name %s", capName, - ) - } - if packet.GetDestPort() != channel.Counterparty.PortId { return sdkerrors.Wrapf( types.ErrInvalidPacket, diff --git a/sei-ibc-go/modules/core/04-channel/types/errors.go b/sei-ibc-go/modules/core/04-channel/types/errors.go index e30f6740df..5079cdee25 100644 --- a/sei-ibc-go/modules/core/04-channel/types/errors.go +++ b/sei-ibc-go/modules/core/04-channel/types/errors.go @@ -6,23 +6,21 @@ import ( // IBC channel sentinel errors var ( - ErrChannelExists = sdkerrors.Register(SubModuleName, 2, "channel already exists") - ErrChannelNotFound = sdkerrors.Register(SubModuleName, 3, "channel not found") - ErrInvalidChannel = sdkerrors.Register(SubModuleName, 4, "invalid channel") - ErrInvalidChannelState = sdkerrors.Register(SubModuleName, 5, "invalid channel state") - ErrInvalidChannelOrdering = sdkerrors.Register(SubModuleName, 6, "invalid channel ordering") - ErrInvalidCounterparty = sdkerrors.Register(SubModuleName, 7, "invalid counterparty channel") - ErrInvalidChannelCapability = sdkerrors.Register(SubModuleName, 8, "invalid channel capability") - ErrChannelCapabilityNotFound = sdkerrors.Register(SubModuleName, 9, "channel capability not found") - ErrSequenceSendNotFound = sdkerrors.Register(SubModuleName, 10, "sequence send not found") - ErrSequenceReceiveNotFound = sdkerrors.Register(SubModuleName, 11, "sequence receive not found") - ErrSequenceAckNotFound = sdkerrors.Register(SubModuleName, 12, "sequence acknowledgement not found") - ErrInvalidPacket = sdkerrors.Register(SubModuleName, 13, "invalid packet") - ErrPacketTimeout = sdkerrors.Register(SubModuleName, 14, "packet timeout") - ErrTooManyConnectionHops = sdkerrors.Register(SubModuleName, 15, "too many connection hops") - ErrInvalidAcknowledgement = sdkerrors.Register(SubModuleName, 16, "invalid acknowledgement") - ErrAcknowledgementExists = sdkerrors.Register(SubModuleName, 17, "acknowledgement for packet already exists") - ErrInvalidChannelIdentifier = sdkerrors.Register(SubModuleName, 18, "invalid channel identifier") + ErrChannelExists = sdkerrors.Register(SubModuleName, 2, "channel already exists") + ErrChannelNotFound = sdkerrors.Register(SubModuleName, 3, "channel not found") + ErrInvalidChannel = sdkerrors.Register(SubModuleName, 4, "invalid channel") + ErrInvalidChannelState = sdkerrors.Register(SubModuleName, 5, "invalid channel state") + ErrInvalidChannelOrdering = sdkerrors.Register(SubModuleName, 6, "invalid channel ordering") + ErrInvalidCounterparty = sdkerrors.Register(SubModuleName, 7, "invalid counterparty channel") + ErrSequenceSendNotFound = sdkerrors.Register(SubModuleName, 10, "sequence send not found") + ErrSequenceReceiveNotFound = sdkerrors.Register(SubModuleName, 11, "sequence receive not found") + ErrSequenceAckNotFound = sdkerrors.Register(SubModuleName, 12, "sequence acknowledgement not found") + ErrInvalidPacket = sdkerrors.Register(SubModuleName, 13, "invalid packet") + ErrPacketTimeout = sdkerrors.Register(SubModuleName, 14, "packet timeout") + ErrTooManyConnectionHops = sdkerrors.Register(SubModuleName, 15, "too many connection hops") + ErrInvalidAcknowledgement = sdkerrors.Register(SubModuleName, 16, "invalid acknowledgement") + ErrAcknowledgementExists = sdkerrors.Register(SubModuleName, 17, "acknowledgement for packet already exists") + ErrInvalidChannelIdentifier = sdkerrors.Register(SubModuleName, 18, "invalid channel identifier") // packets already relayed errors ErrPacketReceived = sdkerrors.Register(SubModuleName, 19, "packet already received") diff --git a/sei-ibc-go/modules/core/04-channel/types/expected_keepers.go b/sei-ibc-go/modules/core/04-channel/types/expected_keepers.go index 5520389506..595513ec58 100644 --- a/sei-ibc-go/modules/core/04-channel/types/expected_keepers.go +++ b/sei-ibc-go/modules/core/04-channel/types/expected_keepers.go @@ -2,7 +2,6 @@ package types import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" connectiontypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/03-connection/types" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" @@ -71,8 +70,3 @@ type ConnectionKeeper interface { nextSequenceRecv uint64, ) error } - -// PortKeeper expected account IBC port keeper -type PortKeeper interface { - Authenticate(ctx sdk.Context, key *capabilitytypes.Capability, portID string) bool -} diff --git a/sei-ibc-go/modules/core/05-port/keeper/keeper.go b/sei-ibc-go/modules/core/05-port/keeper/keeper.go index 116992825d..20a4ca0ff5 100644 --- a/sei-ibc-go/modules/core/05-port/keeper/keeper.go +++ b/sei-ibc-go/modules/core/05-port/keeper/keeper.go @@ -1,79 +1,13 @@ package keeper -import ( - "fmt" - - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" - "github.com/sei-protocol/seilog" - - "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/05-port/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" -) - -var logger = seilog.NewLogger("ibc-go", "modules", "core", "05-port", "keeper") +import "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/05-port/types" // Keeper defines the IBC connection keeper type Keeper struct { Router *types.Router - - scopedKeeper capabilitykeeper.ScopedKeeper } // NewKeeper creates a new IBC connection Keeper instance -func NewKeeper(sck capabilitykeeper.ScopedKeeper) Keeper { - return Keeper{ - scopedKeeper: sck, - } -} - -// IsBound checks a given port ID is already bounded. -func (k Keeper) IsBound(ctx sdk.Context, portID string) bool { - _, ok := k.scopedKeeper.GetCapability(ctx, host.PortPath(portID)) - return ok -} - -// BindPort binds to a port and returns the associated capability. -// Ports must be bound statically when the chain starts in `app.go`. -// The capability must then be passed to a module which will need to pass -// it as an extra parameter when calling functions on the IBC module. -func (k *Keeper) BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability { - if err := host.PortIdentifierValidator(portID); err != nil { - panic(err.Error()) - } - - if k.IsBound(ctx, portID) { - panic(fmt.Sprintf("port %s is already bound", portID)) - } - - key, err := k.scopedKeeper.NewCapability(ctx, host.PortPath(portID)) - if err != nil { - panic(err.Error()) - } - - logger.Info("port binded", "port", portID) - return key -} - -// Authenticate authenticates a capability key against a port ID -// by checking if the memory address of the capability was previously -// generated and bound to the port (provided as a parameter) which the capability -// is being authenticated against. -func (k Keeper) Authenticate(ctx sdk.Context, key *capabilitytypes.Capability, portID string) bool { - if err := host.PortIdentifierValidator(portID); err != nil { - panic(err.Error()) - } - - return k.scopedKeeper.AuthenticateCapability(ctx, key, host.PortPath(portID)) -} - -// LookupModuleByPort will return the IBCModule along with the capability associated with a given portID -func (k Keeper) LookupModuleByPort(ctx sdk.Context, portID string) (string, *capabilitytypes.Capability, error) { - modules, cap, err := k.scopedKeeper.LookupModules(ctx, host.PortPath(portID)) - if err != nil { - return "", nil, err - } - - return types.GetModuleOwner(modules), cap, nil +func NewKeeper() Keeper { + return Keeper{} } diff --git a/sei-ibc-go/modules/core/05-port/types/module.go b/sei-ibc-go/modules/core/05-port/types/module.go index 969fa68b7c..eed2e94ee9 100644 --- a/sei-ibc-go/modules/core/05-port/types/module.go +++ b/sei-ibc-go/modules/core/05-port/types/module.go @@ -2,7 +2,6 @@ package types import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" @@ -21,7 +20,6 @@ type IBCModule interface { connectionHops []string, portID string, channelID string, - channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, version string, ) error @@ -40,7 +38,6 @@ type IBCModule interface { connectionHops []string, portID, channelID string, - channelCap *capabilitytypes.Capability, counterparty channeltypes.Counterparty, counterpartyVersion string, ) (version string, err error) @@ -103,13 +100,11 @@ type IBCModule interface { type ICS4Wrapper interface { SendPacket( ctx sdk.Context, - chanCap *capabilitytypes.Capability, packet exported.PacketI, ) error WriteAcknowledgement( ctx sdk.Context, - chanCap *capabilitytypes.Capability, packet exported.PacketI, ack exported.Acknowledgement, ) error diff --git a/sei-ibc-go/modules/core/05-port/types/utils.go b/sei-ibc-go/modules/core/05-port/types/utils.go deleted file mode 100644 index a12f2ef7f5..0000000000 --- a/sei-ibc-go/modules/core/05-port/types/utils.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -import "fmt" - -// GetModuleOwner enforces that only IBC and the module bound to port can own the capability -// while future implementations may allow multiple modules to bind to a port, currently we -// only allow one module to be bound to a port at any given time -func GetModuleOwner(modules []string) string { - if len(modules) != 2 { - panic(fmt.Sprintf("capability should only be owned by port or channel owner and ibc module, multiple owners currently not supported, owners: %v", modules)) - } - - if modules[0] == "ibc" { - return modules[1] - } - return modules[0] -} diff --git a/sei-ibc-go/modules/core/24-host/keys.go b/sei-ibc-go/modules/core/24-host/keys.go index 858766488e..e71b1da517 100644 --- a/sei-ibc-go/modules/core/24-host/keys.go +++ b/sei-ibc-go/modules/core/24-host/keys.go @@ -27,20 +27,19 @@ var ( // KVStore key prefixes for IBC const ( - KeyClientState = "clientState" - KeyConsensusStatePrefix = "consensusStates" - KeyConnectionPrefix = "connections" - KeyChannelEndPrefix = "channelEnds" - KeyChannelPrefix = "channels" - KeyPortPrefix = "ports" - KeySequencePrefix = "sequences" - KeyChannelCapabilityPrefix = "capabilities" - KeyNextSeqSendPrefix = "nextSequenceSend" - KeyNextSeqRecvPrefix = "nextSequenceRecv" - KeyNextSeqAckPrefix = "nextSequenceAck" - KeyPacketCommitmentPrefix = "commitments" - KeyPacketAckPrefix = "acks" - KeyPacketReceiptPrefix = "receipts" + KeyClientState = "clientState" + KeyConsensusStatePrefix = "consensusStates" + KeyConnectionPrefix = "connections" + KeyChannelEndPrefix = "channelEnds" + KeyChannelPrefix = "channels" + KeyPortPrefix = "ports" + KeySequencePrefix = "sequences" + KeyNextSeqSendPrefix = "nextSequenceSend" + KeyNextSeqRecvPrefix = "nextSequenceRecv" + KeyNextSeqAckPrefix = "nextSequenceAck" + KeyPacketCommitmentPrefix = "commitments" + KeyPacketAckPrefix = "acks" + KeyPacketReceiptPrefix = "receipts" ) // FullClientPath returns the full path of a specific client path in the format: @@ -136,12 +135,6 @@ func ChannelKey(portID, channelID string) []byte { return []byte(ChannelPath(portID, channelID)) } -// ChannelCapabilityPath defines the path under which capability keys associated -// with a channel are stored -func ChannelCapabilityPath(portID, channelID string) string { - return fmt.Sprintf("%s/%s", KeyChannelCapabilityPrefix, channelPath(portID, channelID)) -} - // NextSequenceSendPath defines the next send sequence counter store path func NextSequenceSendPath(portID, channelID string) string { return fmt.Sprintf("%s/%s", KeyNextSeqSendPrefix, channelPath(portID, channelID)) @@ -225,11 +218,3 @@ func channelPath(portID, channelID string) string { func sequencePath(sequence uint64) string { return fmt.Sprintf("%s/%d", KeySequencePrefix, sequence) } - -// ICS05 -// The following paths are the keys to the store as defined in https://github.com/cosmos/ibc/tree/master/spec/core/ics-005-port-allocation#store-paths - -// PortPath defines the path under which ports paths are stored on the capability module -func PortPath(portID string) string { - return fmt.Sprintf("%s/%s", KeyPortPrefix, portID) -} diff --git a/sei-ibc-go/modules/core/keeper/keeper.go b/sei-ibc-go/modules/core/keeper/keeper.go index fe9687d6ed..ca41f7ca79 100644 --- a/sei-ibc-go/modules/core/keeper/keeper.go +++ b/sei-ibc-go/modules/core/keeper/keeper.go @@ -6,7 +6,6 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/codec" sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" paramtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/types" clientkeeper "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/02-client/keeper" @@ -41,7 +40,6 @@ type Keeper struct { func NewKeeper( cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace, stakingKeeper clienttypes.StakingKeeper, upgradeKeeper clienttypes.UpgradeKeeper, - scopedKeeper capabilitykeeper.ScopedKeeper, ) *Keeper { // register paramSpace at top level keeper // set KeyTable if it has not already been set @@ -62,14 +60,10 @@ func NewKeeper( panic(fmt.Errorf("cannot initialize IBC keeper: empty upgrade keeper")) } - if reflect.DeepEqual(capabilitykeeper.ScopedKeeper{}, scopedKeeper) { - panic(fmt.Errorf("cannot initialize IBC keeper: empty scoped keeper")) - } - clientKeeper := clientkeeper.NewKeeper(cdc, key, paramSpace, stakingKeeper, upgradeKeeper) connectionKeeper := connectionkeeper.NewKeeper(cdc, key, paramSpace, clientKeeper) - portKeeper := portkeeper.NewKeeper(scopedKeeper) - channelKeeper := channelkeeper.NewKeeper(cdc, key, paramSpace, clientKeeper, connectionKeeper, portKeeper, scopedKeeper) + portKeeper := portkeeper.NewKeeper() + channelKeeper := channelkeeper.NewKeeper(cdc, key, paramSpace, clientKeeper, connectionKeeper) return &Keeper{ cdc: cdc, diff --git a/sei-wasmd/app/app.go b/sei-wasmd/app/app.go index 3d05e3ca67..6dfb587e9f 100644 --- a/sei-wasmd/app/app.go +++ b/sei-wasmd/app/app.go @@ -37,9 +37,6 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank" bankkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/keeper" banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" distr "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution" distrclient "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/client" distrkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/keeper" @@ -99,8 +96,9 @@ import ( ) const ( - appName = "WasmApp" - feegrantStoreKeyName = "feegrant" + appName = "WasmApp" + capabilityStoreKeyName = "capability" + feegrantStoreKeyName = "feegrant" ) // We pull these out so we can set them with LDFLAGS in the Makefile @@ -165,7 +163,6 @@ var ( auth.AppModuleBasic{}, genutil.AppModuleBasic{}, bank.AppModuleBasic{}, - capability.AppModuleBasic{}, staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, @@ -219,25 +216,20 @@ type WasmApp struct { memKeys map[string]*sdk.MemoryStoreKey // keepers - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - capabilityKeeper *capabilitykeeper.Keeper - stakingKeeper stakingkeeper.Keeper - slashingKeeper slashingkeeper.Keeper - mintKeeper mintkeeper.Keeper - distrKeeper distrkeeper.Keeper - govKeeper govkeeper.Keeper - upgradeKeeper upgradekeeper.Keeper - paramsKeeper paramskeeper.Keeper - evidenceKeeper evidencekeeper.Keeper - ibcKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly - transferKeeper ibctransferkeeper.Keeper - authzKeeper authzkeeper.Keeper - wasmKeeper wasm.Keeper - - scopedIBCKeeper capabilitykeeper.ScopedKeeper - scopedTransferKeeper capabilitykeeper.ScopedKeeper - scopedWasmKeeper capabilitykeeper.ScopedKeeper + accountKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + stakingKeeper stakingkeeper.Keeper + slashingKeeper slashingkeeper.Keeper + mintKeeper mintkeeper.Keeper + distrKeeper distrkeeper.Keeper + govKeeper govkeeper.Keeper + upgradeKeeper upgradekeeper.Keeper + paramsKeeper paramskeeper.Keeper + evidenceKeeper evidencekeeper.Keeper + ibcKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly + transferKeeper ibctransferkeeper.Keeper + authzKeeper authzkeeper.Keeper + wasmKeeper wasm.Keeper // the module manager mm *module.Manager @@ -274,11 +266,11 @@ func NewWasmApp( authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, + evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilityStoreKeyName, feegrantStoreKeyName, authzkeeper.StoreKey, wasm.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey, banktypes.DeferredCacheStoreKey) + memKeys := sdk.NewMemoryStoreKeys(banktypes.DeferredCacheStoreKey) app := &WasmApp{ BaseApp: bApp, @@ -301,17 +293,6 @@ func NewWasmApp( // set the BaseApp's parameter store bApp.SetParamStore(app.paramsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramskeeper.ConsensusParamsKeyTable())) - // add capability keeper and ScopeToModule for ibc module - app.capabilityKeeper = capabilitykeeper.NewKeeper( - appCodec, - keys[capabilitytypes.StoreKey], - memKeys[capabilitytypes.MemStoreKey], - ) - scopedIBCKeeper := app.capabilityKeeper.ScopeToModule(ibchost.ModuleName) - scopedTransferKeeper := app.capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) - scopedWasmKeeper := app.capabilityKeeper.ScopeToModule(wasm.ModuleName) - app.capabilityKeeper.Seal() - // add keepers app.accountKeeper = authkeeper.NewAccountKeeper( appCodec, @@ -380,7 +361,6 @@ func NewWasmApp( app.getSubspace(ibchost.ModuleName), app.stakingKeeper, app.upgradeKeeper, - scopedIBCKeeper, ) // register the proposal types @@ -398,10 +378,8 @@ func NewWasmApp( app.getSubspace(ibctransfertypes.ModuleName), app.ibcKeeper.ChannelKeeper, app.ibcKeeper.ChannelKeeper, - &app.ibcKeeper.PortKeeper, app.accountKeeper, app.bankKeeper, - scopedTransferKeeper, ) transferModule := transfer.NewAppModule(app.transferKeeper) transferIBCModule := transfer.NewIBCModule(app.transferKeeper) @@ -434,8 +412,6 @@ func NewWasmApp( app.stakingKeeper, app.distrKeeper, app.ibcKeeper.ChannelKeeper, - &app.ibcKeeper.PortKeeper, - scopedWasmKeeper, app.upgradeKeeper, app.transferKeeper, app.MsgServiceRouter(), @@ -480,7 +456,6 @@ func NewWasmApp( auth.NewAppModule(appCodec, app.accountKeeper, nil), vesting.NewAppModule(app.accountKeeper, app.bankKeeper, app.upgradeKeeper), bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper), - capability.NewAppModule(appCodec, *app.capabilityKeeper), gov.NewAppModule(appCodec, app.govKeeper, app.accountKeeper, app.bankKeeper), mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper), slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), @@ -497,13 +472,9 @@ func NewWasmApp( // NOTE: The genutils module 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. // NOTE: wasm module should be at the end as it can call other module functionality direct or via message dispatching during // genesis phase. For example bank transfer, auth account check, staking, ... app.mm.SetOrderInitGenesis( - capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, @@ -572,10 +543,6 @@ func NewWasmApp( } } - app.scopedIBCKeeper = scopedIBCKeeper - app.scopedTransferKeeper = scopedTransferKeeper - app.scopedWasmKeeper = scopedWasmKeeper - if loadLatest { if err := app.LoadLatestVersion(); err != nil { tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err)) @@ -601,7 +568,6 @@ func (app *WasmApp) ProcessProposalHandler(ctx sdk.Context, req *abci.RequestPro } func (app *WasmApp) FinalizeBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) { - capability.BeginBlocker(ctx, *app.capabilityKeeper) distr.BeginBlocker(ctx, []abci.VoteInfo{}, app.distrKeeper) slashing.BeginBlocker(ctx, []abci.VoteInfo{}, app.slashingKeeper) evidence.BeginBlocker(ctx, []abci.Misbehavior{}, app.evidenceKeeper) @@ -752,10 +718,6 @@ func (app *WasmApp) AppCodec() codec.Codec { return app.appCodec } -func (app *WasmApp) GetCapabilityKeeper() *capabilitykeeper.Keeper { - return app.capabilityKeeper -} - func (app *WasmApp) GetDistrKeeper() *distrkeeper.Keeper { return &app.distrKeeper } diff --git a/sei-wasmd/app/test_access.go b/sei-wasmd/app/test_access.go index 0f3de10b79..6129dae306 100644 --- a/sei-wasmd/app/test_access.go +++ b/sei-wasmd/app/test_access.go @@ -10,7 +10,6 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/codec" bankkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/keeper" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" stakingkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/keeper" ibctransferkeeper "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/apps/transfer/keeper" ibckeeper "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/keeper" @@ -39,18 +38,6 @@ func (s TestSupport) AppCodec() codec.Codec { return s.app.appCodec } -func (s TestSupport) ScopedWasmIBCKeeper() capabilitykeeper.ScopedKeeper { - return s.app.scopedWasmKeeper -} - -func (s TestSupport) ScopeIBCKeeper() capabilitykeeper.ScopedKeeper { - return s.app.scopedIBCKeeper -} - -func (s TestSupport) ScopedTransferKeeper() capabilitykeeper.ScopedKeeper { - return s.app.scopedTransferKeeper -} - func (s TestSupport) StakingKeeper() stakingkeeper.Keeper { return s.app.stakingKeeper } diff --git a/sei-wasmd/app/test_helpers.go b/sei-wasmd/app/test_helpers.go index e8057d7b49..44dca3d100 100644 --- a/sei-wasmd/app/test_helpers.go +++ b/sei-wasmd/app/test_helpers.go @@ -26,8 +26,6 @@ import ( authtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/types" bankkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/keeper" banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution" distrkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/keeper" "github.com/sei-protocol/sei-chain/sei-cosmos/x/evidence" @@ -172,10 +170,6 @@ func SetupWithGenesisValSet(t *testing.T, chainID string, valSet *tmtypes.Valida }, ) require.NoError(t, err) - // This line is necessary due to the capability module which has a map as well as store usages, - // and because the initChain runs 3 times (deliver, prepare, process proposal), - // we need to make sure to first commit the last one so the proper values are persisted from the - // memory map into the store. app.SetProcessProposalStateToCommit() // commit genesis changes @@ -384,7 +378,7 @@ func SignCheckDeliver( // ibc testing package causes checkState and deliverState to diverge in block time. func SignAndDeliver( t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, - ibcKeeper *ibckeeper.Keeper, stakingKeeper stakingkeeper.Keeper, capabilityKeeper *capabilitykeeper.Keeper, distrKeeper *distrkeeper.Keeper, slashingKeeper *slashingkeeper.Keeper, evidenceKeeper *evidencekeeper.Keeper, header tmproto.Header, msgs []sdk.Msg, + ibcKeeper *ibckeeper.Keeper, stakingKeeper stakingkeeper.Keeper, distrKeeper *distrkeeper.Keeper, slashingKeeper *slashingkeeper.Keeper, evidenceKeeper *evidencekeeper.Keeper, header tmproto.Header, msgs []sdk.Msg, chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { tx, err := seiapp.GenTx( @@ -401,7 +395,6 @@ func SignAndDeliver( // Simulate a sending a transaction and committing a block ctx := app.GetContextForDeliverTx([]byte{}).WithBlockHeader(header) - capability.BeginBlocker(ctx, *capabilityKeeper) distribution.BeginBlocker(ctx, []abci.VoteInfo{}, *distrKeeper) slashing.BeginBlocker(ctx, []abci.VoteInfo{}, *slashingKeeper) evidence.BeginBlocker(ctx, []abci.Misbehavior{}, *evidenceKeeper) diff --git a/sei-wasmd/x/wasm/ibc.go b/sei-wasmd/x/wasm/ibc.go index b97bc86e37..c371d296fe 100644 --- a/sei-wasmd/x/wasm/ibc.go +++ b/sei-wasmd/x/wasm/ibc.go @@ -7,10 +7,8 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" porttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/05-port/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" wasmvmtypes "github.com/sei-protocol/sei-chain/sei-wasmvm/types" types "github.com/sei-protocol/sei-chain/sei-wasmd/x/wasm/types" @@ -34,11 +32,9 @@ func (i IBCHandler) OnChanOpenInit( connectionHops []string, portID string, channelID string, - chanCap *capabilitytypes.Capability, counterParty channeltypes.Counterparty, version string, ) error { - // ensure port, version, capability if err := ValidateChannelParams(channelID); err != nil { return err } @@ -60,14 +56,7 @@ func (i IBCHandler) OnChanOpenInit( }, } _, err = i.keeper.OnOpenChannel(ctx, contractAddr, msg) - if err != nil { - return err - } - // Claim channel capability passed back by IBC module - if err := i.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return sdkerrors.Wrap(err, "claim capability") - } - return nil + return err } // OnChanOpenTry implements the IBCModule interface @@ -76,11 +65,9 @@ func (i IBCHandler) OnChanOpenTry( order channeltypes.Order, connectionHops []string, portID, channelID string, - chanCap *capabilitytypes.Capability, counterParty channeltypes.Counterparty, counterpartyVersion string, ) (string, error) { - // ensure port, version, capability if err := ValidateChannelParams(channelID); err != nil { return "", err } @@ -112,17 +99,6 @@ func (i IBCHandler) OnChanOpenTry( version = counterpartyVersion } - // Module may have already claimed capability in OnChanOpenInit in the case of crossing hellos - // (ie chainA and chainB both call ChanOpenInit before one of them calls ChanOpenTry) - // If module can already authenticate the capability then module already owns it so we don't need to claim - // Otherwise, module does not have channel capability and we must claim it from IBC - if !i.keeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - // Only claim channel capability passed back by IBC module if we do not already own it - if err := i.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return "", sdkerrors.Wrap(err, "claim capability") - } - } - return version, nil } diff --git a/sei-wasmd/x/wasm/keeper/genesis_test.go b/sei-wasmd/x/wasm/keeper/genesis_test.go index dadcce0200..bba8bbffe0 100644 --- a/sei-wasmd/x/wasm/keeper/genesis_test.go +++ b/sei-wasmd/x/wasm/keeper/genesis_test.go @@ -669,7 +669,7 @@ func setupKeeper(t *testing.T) (*Keeper, sdk.Context, []sdk.StoreKey) { wasmConfig := wasmTypes.DefaultWasmConfig() pk := paramskeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, keyParams, tkeyParams) - srcKeeper := NewKeeper(encodingConfig.Marshaler, keyWasm, paramskeeper.Keeper{}, pk.Subspace(wasmTypes.ModuleName), authkeeper.AccountKeeper{}, nil, stakingkeeper.Keeper{}, distributionkeeper.Keeper{}, nil, nil, nil, upgradekeeper.Keeper{}, nil, nil, nil, tempDir, wasmConfig, SupportedFeatures) + srcKeeper := NewKeeper(encodingConfig.Marshaler, keyWasm, paramskeeper.Keeper{}, pk.Subspace(wasmTypes.ModuleName), authkeeper.AccountKeeper{}, nil, stakingkeeper.Keeper{}, distributionkeeper.Keeper{}, nil, upgradekeeper.Keeper{}, nil, nil, nil, tempDir, wasmConfig, SupportedFeatures) return &srcKeeper, ctx, []sdk.StoreKey{keyWasm, keyParams} } diff --git a/sei-wasmd/x/wasm/keeper/handler_plugin.go b/sei-wasmd/x/wasm/keeper/handler_plugin.go index 79158d34aa..dfcf4e1ecc 100644 --- a/sei-wasmd/x/wasm/keeper/handler_plugin.go +++ b/sei-wasmd/x/wasm/keeper/handler_plugin.go @@ -9,7 +9,6 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" wasmvmtypes "github.com/sei-protocol/sei-chain/sei-wasmvm/types" "github.com/sei-protocol/sei-chain/sei-wasmd/x/wasm/types" @@ -35,7 +34,6 @@ type SDKMessageHandler struct { func NewDefaultMessageHandler( router MessageRouter, channelKeeper types.ChannelKeeper, - capabilityKeeper types.CapabilityKeeper, bankKeeper types.Burner, unpacker codectypes.AnyUnpacker, portSource types.ICS20TransferPortSource, @@ -47,7 +45,7 @@ func NewDefaultMessageHandler( } return NewMessageHandlerChain( NewSDKMessageHandler(router, encoders), - NewIBCRawPacketHandler(channelKeeper, capabilityKeeper), + NewIBCRawPacketHandler(channelKeeper), NewBurnCoinMessageHandler(bankKeeper), ) } @@ -142,12 +140,11 @@ func (m MessageHandlerChain) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAd // IBCRawPacketHandler handels IBC.SendPacket messages which are published to an IBC channel. type IBCRawPacketHandler struct { - channelKeeper types.ChannelKeeper - capabilityKeeper types.CapabilityKeeper + channelKeeper types.ChannelKeeper } -func NewIBCRawPacketHandler(chk types.ChannelKeeper, cak types.CapabilityKeeper) IBCRawPacketHandler { - return IBCRawPacketHandler{channelKeeper: chk, capabilityKeeper: cak} +func NewIBCRawPacketHandler(chk types.ChannelKeeper) IBCRawPacketHandler { + return IBCRawPacketHandler{channelKeeper: chk} } // DispatchMsg publishes a raw IBC packet onto the channel. @@ -174,10 +171,6 @@ func (h IBCRawPacketHandler) DispatchMsg(ctx sdk.Context, _ sdk.AccAddress, cont if !ok { return nil, nil, sdkerrors.Wrap(channeltypes.ErrInvalidChannel, "not found") } - channelCap, ok := h.capabilityKeeper.GetCapability(ctx, host.ChannelCapabilityPath(contractIBCPortID, contractIBCChannelID)) - if !ok { - return nil, nil, sdkerrors.Wrap(channeltypes.ErrChannelCapabilityNotFound, "module does not own channel capability") - } packet := channeltypes.NewPacket( msg.IBC.SendPacket.Data, sequence, @@ -188,7 +181,7 @@ func (h IBCRawPacketHandler) DispatchMsg(ctx sdk.Context, _ sdk.AccAddress, cont ConvertWasmIBCTimeoutHeightToCosmosHeight(msg.IBC.SendPacket.Timeout.Block), msg.IBC.SendPacket.Timeout.Timestamp, ) - return nil, nil, h.channelKeeper.SendPacket(ctx, channelCap, packet) + return nil, nil, h.channelKeeper.SendPacket(ctx, packet) } var _ Messenger = MessageHandlerFunc(nil) diff --git a/sei-wasmd/x/wasm/keeper/handler_plugin_test.go b/sei-wasmd/x/wasm/keeper/handler_plugin_test.go index 7268d77303..20a2e55c9c 100644 --- a/sei-wasmd/x/wasm/keeper/handler_plugin_test.go +++ b/sei-wasmd/x/wasm/keeper/handler_plugin_test.go @@ -8,7 +8,6 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" clienttypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/02-client/types" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" ibcexported "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" @@ -239,21 +238,15 @@ func TestIBCRawPacketHandler(t *testing.T) { ), }, true }, - SendPacketFn: func(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error { + SendPacketFn: func(ctx sdk.Context, packet ibcexported.PacketI) error { capturedPacket = packet return nil }, } - capKeeper := &wasmtesting.MockCapabilityKeeper{ - GetCapabilityFn: func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - return &capabilitytypes.Capability{}, true - }, - } specs := map[string]struct { srcMsg wasmvmtypes.SendPacketMsg chanKeeper types.ChannelKeeper - capKeeper types.CapabilityKeeper expPacketSent channeltypes.Packet expErr *sdkerrors.Error }{ @@ -264,7 +257,6 @@ func TestIBCRawPacketHandler(t *testing.T) { Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}}, }, chanKeeper: chanKeeper, - capKeeper: capKeeper, expPacketSent: channeltypes.Packet{ Sequence: 1, SourcePort: ibcPort, @@ -288,26 +280,12 @@ func TestIBCRawPacketHandler(t *testing.T) { }, expErr: channeltypes.ErrSequenceSendNotFound, }, - "capability not found returns error": { - srcMsg: wasmvmtypes.SendPacketMsg{ - ChannelID: "channel-1", - Data: []byte("myData"), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}}, - }, - chanKeeper: chanKeeper, - capKeeper: wasmtesting.MockCapabilityKeeper{ - GetCapabilityFn: func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - return nil, false - }, - }, - expErr: channeltypes.ErrChannelCapabilityNotFound, - }, } for name, spec := range specs { t.Run(name, func(t *testing.T) { capturedPacket = nil // when - h := NewIBCRawPacketHandler(spec.chanKeeper, spec.capKeeper) + h := NewIBCRawPacketHandler(spec.chanKeeper) data, evts, gotErr := h.DispatchMsg(ctx, RandomAccountAddress(t), ibcPort, wasmvmtypes.CosmosMsg{IBC: &wasmvmtypes.IBCMsg{SendPacket: &spec.srcMsg}}, wasmvmtypes.MessageInfo{}, types.CodeInfo{}) // then require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) diff --git a/sei-wasmd/x/wasm/keeper/ibc.go b/sei-wasmd/x/wasm/keeper/ibc.go index 2dab5b602b..e350ded533 100644 --- a/sei-wasmd/x/wasm/keeper/ibc.go +++ b/sei-wasmd/x/wasm/keeper/ibc.go @@ -5,32 +5,10 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" - host "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/24-host" "github.com/sei-protocol/sei-chain/sei-wasmd/x/wasm/types" ) -// bindIbcPort will reserve the port. -// returns a string name of the port or error if we cannot bind it. -// this will fail if call twice. -func (k Keeper) bindIbcPort(ctx sdk.Context, portID string) error { - cap := k.portKeeper.BindPort(ctx, portID) - return k.ClaimCapability(ctx, cap, host.PortPath(portID)) -} - -// ensureIbcPort is like registerIbcPort, but it checks if we already hold the port -// before calling register, so this is safe to call multiple times. -// Returns success if we already registered or just registered and error if we cannot -// (lack of permissions or someone else has it) -func (k Keeper) ensureIbcPort(ctx sdk.Context, contractAddr sdk.AccAddress) (string, error) { - portID := PortIDForContract(contractAddr) - if _, ok := k.capabilityKeeper.GetCapability(ctx, host.PortPath(portID)); ok { - return portID, nil - } - return portID, k.bindIbcPort(ctx, portID) -} - const portIDPrefix = "wasm." func PortIDForContract(addr sdk.AccAddress) string { @@ -43,14 +21,3 @@ func ContractFromPortID(portID string) (sdk.AccAddress, error) { } return sdk.AccAddressFromBech32(portID[len(portIDPrefix):]) } - -// AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function -func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool { - return k.capabilityKeeper.AuthenticateCapability(ctx, cap, name) -} - -// ClaimCapability allows the transfer module to claim a capability -// that IBC module passes to it -func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - return k.capabilityKeeper.ClaimCapability(ctx, cap, name) -} diff --git a/sei-wasmd/x/wasm/keeper/ibc_test.go b/sei-wasmd/x/wasm/keeper/ibc_test.go index cc702786f9..792a5c70e4 100644 --- a/sei-wasmd/x/wasm/keeper/ibc_test.go +++ b/sei-wasmd/x/wasm/keeper/ibc_test.go @@ -10,19 +10,16 @@ import ( "github.com/stretchr/testify/require" ) -func TestDontBindPortNonIBCContract(t *testing.T) { +func TestNonIBCContractHasNoPort(t *testing.T) { ctx, keepers := CreateTestInput(t, false, SupportedFeatures) - example := InstantiateHackatomExampleContract(t, ctx, keepers) // ensure we bound the port - _, _, err := keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) - require.Error(t, err) + example := InstantiateHackatomExampleContract(t, ctx, keepers) + require.Empty(t, keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) } -func TestBindingPortForIBCContractOnInstantiate(t *testing.T) { +func TestIBCContractPortOnInstantiate(t *testing.T) { ctx, keepers := CreateTestInput(t, false, SupportedFeatures) - example := InstantiateIBCReflectContract(t, ctx, keepers) // ensure we bound the port - owner, _, err := keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) - require.NoError(t, err) - require.Equal(t, "wasm", owner) + example := InstantiateIBCReflectContract(t, ctx, keepers) + require.Equal(t, PortIDForContract(example.Contract), keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) initMsgBz := IBCReflectInitMsg{ ReflectCodeID: example.ReflectCodeID, @@ -35,9 +32,7 @@ func TestBindingPortForIBCContractOnInstantiate(t *testing.T) { require.NotEqual(t, example.Contract, addr) portID2 := PortIDForContract(addr) - owner, _, err = keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, portID2) - require.NoError(t, err) - require.Equal(t, "wasm", owner) + require.Equal(t, portID2, keepers.WasmKeeper.GetContractInfo(ctx, addr).IBCPortID) } func TestContractFromPortID(t *testing.T) { diff --git a/sei-wasmd/x/wasm/keeper/keeper.go b/sei-wasmd/x/wasm/keeper/keeper.go index 325497ff22..4da19a36b8 100644 --- a/sei-wasmd/x/wasm/keeper/keeper.go +++ b/sei-wasmd/x/wasm/keeper/keeper.go @@ -76,8 +76,6 @@ type Keeper struct { cdc codec.Codec accountKeeper types.AccountKeeper bank CoinTransferrer - portKeeper types.PortKeeper - capabilityKeeper types.CapabilityKeeper paramsKeeper types.ParamsKeeper upgradeKeeper types.UpgradeKeeper wasmVM types.WasmerEngine @@ -108,8 +106,6 @@ func NewKeeper( stakingKeeper types.StakingKeeper, distKeeper types.DistributionKeeper, channelKeeper types.ChannelKeeper, - portKeeper types.PortKeeper, - capabilityKeeper types.CapabilityKeeper, upgradeKeeper types.UpgradeKeeper, portSource types.ICS20TransferPortSource, router MessageRouter, @@ -155,10 +151,8 @@ func NewKeeper( rpcWasmVM155: NewVMWrapper(rpcWasmer155), accountKeeper: accountKeeper, bank: NewBankCoinTransferrer(bankKeeper), - portKeeper: portKeeper, - capabilityKeeper: capabilityKeeper, upgradeKeeper: upgradeKeeper, - messenger: NewDefaultMessageHandler(router, channelKeeper, capabilityKeeper, bankKeeper, cdc, portSource), + messenger: NewDefaultMessageHandler(router, channelKeeper, bankKeeper, cdc, portSource), queryGasLimit: wasmConfig.SmartQueryGasLimit, paramSpace: paramSpace, gasRegister: NewDefaultWasmGasRegister(), @@ -368,12 +362,7 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A return nil, nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) } if report.HasIBCEntryPoints { - // register IBC port - ibcPort, err := k.ensureIbcPort(ctx, contractAddress) - if err != nil { - return nil, nil, err - } - contractInfo.IBCPortID = ibcPort + contractInfo.IBCPortID = PortIDForContract(contractAddress) } // store contract before dispatch so that contract could be called back @@ -468,12 +457,7 @@ func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller // prevent update to non ibc contract return nil, sdkerrors.Wrap(types.ErrMigrationFailed, "requires ibc callbacks") case report.HasIBCEntryPoints && contractInfo.IBCPortID == "": - // add ibc port - ibcPort, err := k.ensureIbcPort(ctx, contractAddress) - if err != nil { - return nil, err - } - contractInfo.IBCPortID = ibcPort + contractInfo.IBCPortID = PortIDForContract(contractAddress) } env := types.NewEnv(ctx, contractAddress) diff --git a/sei-wasmd/x/wasm/keeper/options_test.go b/sei-wasmd/x/wasm/keeper/options_test.go index dfb71bd146..e483e53ad5 100644 --- a/sei-wasmd/x/wasm/keeper/options_test.go +++ b/sei-wasmd/x/wasm/keeper/options_test.go @@ -91,7 +91,7 @@ func TestConstructorOptions(t *testing.T) { } for name, spec := range specs { t.Run(name, func(t *testing.T) { - k := NewKeeper(nil, nil, nil, paramtypes.NewSubspace(nil, nil, nil, nil, ""), authkeeper.AccountKeeper{}, nil, stakingkeeper.Keeper{}, distributionkeeper.Keeper{}, nil, nil, nil, upgradekeeper.Keeper{}, nil, nil, nil, "tempDir", types.DefaultWasmConfig(), SupportedFeatures, spec.srcOpt) + k := NewKeeper(nil, nil, nil, paramtypes.NewSubspace(nil, nil, nil, nil, ""), authkeeper.AccountKeeper{}, nil, stakingkeeper.Keeper{}, distributionkeeper.Keeper{}, nil, upgradekeeper.Keeper{}, nil, nil, nil, "tempDir", types.DefaultWasmConfig(), SupportedFeatures, spec.srcOpt) spec.verify(t, k) }) } diff --git a/sei-wasmd/x/wasm/keeper/test_common.go b/sei-wasmd/x/wasm/keeper/test_common.go index 8ae832bb56..51986ad4a5 100644 --- a/sei-wasmd/x/wasm/keeper/test_common.go +++ b/sei-wasmd/x/wasm/keeper/test_common.go @@ -23,9 +23,6 @@ import ( "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank" bankkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/keeper" banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability" - capabilitykeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/keeper" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution" distrclient "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/client" distributionkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/keeper" @@ -70,7 +67,6 @@ import ( var ModuleBasics = module.NewBasicManager( auth.AppModuleBasic{}, bank.AppModuleBasic{}, - capability.AppModuleBasic{}, staking.AppModuleBasic{}, mint.AppModuleBasic{}, distribution.AppModuleBasic{}, @@ -203,7 +199,7 @@ func createTestInput( minttypes.StoreKey, distributiontypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, - capabilitytypes.StoreKey, authzkeeper.StoreKey, + authzkeeper.StoreKey, types.StoreKey, ) ms := store.NewCommitMultiStore(db) @@ -215,11 +211,6 @@ func createTestInput( ms.MountStoreWithDB(v, sdk.StoreTypeTransient, db) } - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - for _, v := range memKeys { - ms.MountStoreWithDB(v, sdk.StoreTypeMemory, db) - } - require.NoError(t, ms.LoadLatestVersion()) ctx := sdk.NewContext(ms, tmproto.Header{ @@ -245,7 +236,6 @@ func createTestInput( distributiontypes.ModuleName, slashingtypes.ModuleName, ibctransfertypes.ModuleName, - capabilitytypes.ModuleName, ibchost.ModuleName, govtypes.ModuleName, types.ModuleName, @@ -329,21 +319,12 @@ func createTestInput( faucet.Fund(ctx, distrAcc.GetAddress(), sdk.NewCoin("stake", sdk.NewInt(2000000))) accountKeeper.SetModuleAccount(ctx, distrAcc) - capabilityKeeper := capabilitykeeper.NewKeeper( - appCodec, - keys[capabilitytypes.StoreKey], - memKeys[capabilitytypes.MemStoreKey], - ) - scopedIBCKeeper := capabilityKeeper.ScopeToModule(ibchost.ModuleName) - scopedWasmKeeper := capabilityKeeper.ScopeToModule(types.ModuleName) - ibcKeeper := ibckeeper.NewKeeper( appCodec, keys[ibchost.StoreKey], subspace(ibchost.ModuleName), stakingKeeper, upgradeKeeper, - scopedIBCKeeper, ) router := baseapp.NewRouter() @@ -372,8 +353,6 @@ func createTestInput( stakingKeeper, distKeeper, ibcKeeper.ChannelKeeper, - &ibcKeeper.PortKeeper, - scopedWasmKeeper, upgradekeeper.Keeper{}, wasmtesting.MockIBCTransferKeeper{}, msgRouter, diff --git a/sei-wasmd/x/wasm/keeper/wasmtesting/mock_keepers.go b/sei-wasmd/x/wasm/keeper/wasmtesting/mock_keepers.go index f8195085aa..5f980fe49f 100644 --- a/sei-wasmd/x/wasm/keeper/wasmtesting/mock_keepers.go +++ b/sei-wasmd/x/wasm/keeper/wasmtesting/mock_keepers.go @@ -2,7 +2,6 @@ package wasmtesting import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" channeltypes "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/04-channel/types" ibcexported "github.com/sei-protocol/sei-chain/sei-ibc-go/modules/core/exported" @@ -12,8 +11,8 @@ import ( type MockChannelKeeper struct { GetChannelFn func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) GetNextSequenceSendFn func(ctx sdk.Context, portID, channelID string) (uint64, bool) - SendPacketFn func(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error - ChanCloseInitFn func(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error + SendPacketFn func(ctx sdk.Context, packet ibcexported.PacketI) error + ChanCloseInitFn func(ctx sdk.Context, portID, channelID string) error GetAllChannelsFn func(ctx sdk.Context) []channeltypes.IdentifiedChannel IterateChannelsFn func(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) SetChannelFn func(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) @@ -40,18 +39,18 @@ func (m *MockChannelKeeper) GetNextSequenceSend(ctx sdk.Context, portID, channel return m.GetNextSequenceSendFn(ctx, portID, channelID) } -func (m *MockChannelKeeper) SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error { +func (m *MockChannelKeeper) SendPacket(ctx sdk.Context, packet ibcexported.PacketI) error { if m.SendPacketFn == nil { panic("not supposed to be called!") } - return m.SendPacketFn(ctx, channelCap, packet) + return m.SendPacketFn(ctx, packet) } -func (m *MockChannelKeeper) ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error { +func (m *MockChannelKeeper) ChanCloseInit(ctx sdk.Context, portID, channelID string) error { if m.ChanCloseInitFn == nil { panic("not supposed to be called!") } - return m.ChanCloseInitFn(ctx, portID, channelID, chanCap) + return m.ChanCloseInitFn(ctx, portID, channelID) } func (m *MockChannelKeeper) IterateChannels(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) { @@ -79,33 +78,6 @@ func MockChannelKeeperIterator(s []channeltypes.IdentifiedChannel) func(ctx sdk. } } -type MockCapabilityKeeper struct { - GetCapabilityFn func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) - ClaimCapabilityFn func(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - AuthenticateCapabilityFn func(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool -} - -func (m MockCapabilityKeeper) GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - if m.GetCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.GetCapabilityFn(ctx, name) -} - -func (m MockCapabilityKeeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - if m.ClaimCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.ClaimCapabilityFn(ctx, cap, name) -} - -func (m MockCapabilityKeeper) AuthenticateCapability(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool { - if m.AuthenticateCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.AuthenticateCapabilityFn(ctx, capability, name) -} - var _ types.ICS20TransferPortSource = &MockIBCTransferKeeper{} type MockIBCTransferKeeper struct { diff --git a/sei-wasmd/x/wasm/types/expected_keepers.go b/sei-wasmd/x/wasm/types/expected_keepers.go index ef1c03da42..0221d4d54a 100644 --- a/sei-wasmd/x/wasm/types/expected_keepers.go +++ b/sei-wasmd/x/wasm/types/expected_keepers.go @@ -5,7 +5,6 @@ import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" authtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/types" paramstypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/types" stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" @@ -74,8 +73,8 @@ type StakingKeeper interface { type ChannelKeeper interface { GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) - SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error - ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error + SendPacket(ctx sdk.Context, packet ibcexported.PacketI) error + ChanCloseInit(ctx sdk.Context, portID, channelID string) error GetAllChannels(ctx sdk.Context) (channels []channeltypes.IdentifiedChannel) IterateChannels(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) SetChannel(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) @@ -91,17 +90,6 @@ type ConnectionKeeper interface { GetConnection(ctx sdk.Context, connectionID string) (connection connectiontypes.ConnectionEnd, found bool) } -// PortKeeper defines the expected IBC port keeper -type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability -} - -type CapabilityKeeper interface { - GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) - ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - AuthenticateCapability(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool -} - type ParamsKeeper interface { GetCosmosGasParams(ctx sdk.Context) paramstypes.CosmosGasParams } diff --git a/sei-wasmd/x/wasm/types/exported_keepers.go b/sei-wasmd/x/wasm/types/exported_keepers.go index e14e5676fe..aae2ba6588 100644 --- a/sei-wasmd/x/wasm/types/exported_keepers.go +++ b/sei-wasmd/x/wasm/types/exported_keepers.go @@ -2,7 +2,6 @@ package types import ( sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" wasmvmtypes "github.com/sei-protocol/sei-chain/sei-wasmvm/types" ) @@ -90,9 +89,4 @@ type IBCContractKeeper interface { contractAddr sdk.AccAddress, msg wasmvmtypes.IBCPacketTimeoutMsg, ) error - // ClaimCapability allows the transfer module to claim a capability - // that IBC module passes to it - ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function - AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool } diff --git a/tools/utils/helper.go b/tools/utils/helper.go index 4cf8fcd319..9de35374b2 100644 --- a/tools/utils/helper.go +++ b/tools/utils/helper.go @@ -7,7 +7,6 @@ import ( authtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/types" authzkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/authz/keeper" banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" - capabilitytypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/capability/types" distrtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/distribution/types" evidencetypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/evidence/types" govtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/gov/types" @@ -25,13 +24,16 @@ import ( tokenfactorytypes "github.com/sei-protocol/sei-chain/x/tokenfactory/types" ) -const feegrantStoreKeyName = "feegrant" +const ( + capabilityStoreKeyName = "capability" + feegrantStoreKeyName = "feegrant" +) var ModuleKeys = sdk.NewKVStoreKeys( authtypes.StoreKey, authzkeeper.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, feegrantStoreKeyName, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, oracletypes.StoreKey, + evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilityStoreKeyName, oracletypes.StoreKey, evmtypes.StoreKey, wasm.StoreKey, epochmoduletypes.StoreKey, tokenfactorytypes.StoreKey, ) @@ -39,7 +41,7 @@ var Modules = []string{ "authz", "acc", "bank", - "capability", + capabilityStoreKeyName, "distribution", "epoch", "evidence", diff --git a/wasmbinding/message_plugin.go b/wasmbinding/message_plugin.go index acc288c397..f3d0d3fca9 100644 --- a/wasmbinding/message_plugin.go +++ b/wasmbinding/message_plugin.go @@ -35,7 +35,6 @@ func (r *CustomRouter) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { func CustomMessageHandler( router wasmkeeper.MessageRouter, channelKeeper wasmtypes.ChannelKeeper, - capabilityKeeper wasmtypes.CapabilityKeeper, bankKeeper wasmtypes.Burner, evmKeeper *evmkeeper.Keeper, unpacker codectypes.AnyUnpacker, @@ -48,7 +47,7 @@ func CustomMessageHandler( }) return wasmkeeper.NewMessageHandlerChain( wasmkeeper.NewSDKMessageHandler(&CustomRouter{MessageRouter: router, evmKeeper: evmKeeper}, encoders), - wasmkeeper.NewIBCRawPacketHandler(channelKeeper, capabilityKeeper), + wasmkeeper.NewIBCRawPacketHandler(channelKeeper), wasmkeeper.NewBurnCoinMessageHandler(bankKeeper), ) } diff --git a/wasmbinding/wasm.go b/wasmbinding/wasm.go index 5c5efb0aaf..79f312a3c1 100644 --- a/wasmbinding/wasm.go +++ b/wasmbinding/wasm.go @@ -24,7 +24,6 @@ func RegisterCustomPlugins( _ *authkeeper.AccountKeeper, router wasmkeeper.MessageRouter, channelKeeper wasmtypes.ChannelKeeper, - capabilityKeeper wasmtypes.CapabilityKeeper, bankKeeper wasmtypes.Burner, unpacker codectypes.AnyUnpacker, portSource wasmtypes.ICS20TransferPortSource, @@ -41,7 +40,7 @@ func RegisterCustomPlugins( Custom: CustomQuerier(wasmQueryPlugin), }) messengerHandlerOpt := wasmkeeper.WithMessageHandler( - CustomMessageHandler(router, channelKeeper, capabilityKeeper, bankKeeper, evmKeeper, unpacker, portSource), + CustomMessageHandler(router, channelKeeper, bankKeeper, evmKeeper, unpacker, portSource), ) return []wasm.Option{