Skip to content
2 changes: 1 addition & 1 deletion simapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ func NewSimApp(
app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[circuittypes.StoreKey]), logger), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec())
app.BaseApp.SetCircuitBreaker(&app.CircuitKeeper)

app.AuthzKeeper = authzkeeper.NewKeeper(runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), appCodec, app.MsgServiceRouter(), app.AuthKeeper)
app.AuthzKeeper = authzkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), logger), appCodec, app.MsgServiceRouter(), app.AuthKeeper)

groupConfig := group.DefaultConfig()
/*
Expand Down
1 change: 1 addition & 0 deletions x/authz/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### API Breaking Changes

* [#19490](https://github.com/cosmos/cosmos-sdk/pull/19490) `appmodule.Environment` is received on the Keeper to get access to different application services
* [#18737](https://github.com/cosmos/cosmos-sdk/pull/18737) Update the keeper method `DequeueAndDeleteExpiredGrants` to take a limit argument for the number of grants to prune.
* [#16509](https://github.com/cosmos/cosmos-sdk/pull/16509) `AcceptResponse` has been moved to sdk/types/authz and the `Updated` field is now of the type `sdk.Msg` instead of `authz.Authorization`.

Expand Down
2 changes: 1 addition & 1 deletion x/authz/keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

// InitGenesis initializes new authz genesis
func (k Keeper) InitGenesis(ctx context.Context, data *authz.GenesisState) {
now := sdk.UnwrapSDKContext(ctx).HeaderInfo().Time
now := k.environment.HeaderService.GetHeaderInfo(ctx).Time
for _, entry := range data.Authorization {
// ignore expired authorizations
if entry.Expiration != nil && entry.Expiration.Before(now) {
Expand Down
3 changes: 2 additions & 1 deletion x/authz/keeper/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func (suite *GenesisTestSuite) SetupTest() {
storeService := runtime.NewKVStoreService(key)
testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test"))
suite.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1})
env := runtime.NewEnvironment(storeService, log.NewNopLogger())

suite.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{})

Expand All @@ -68,7 +69,7 @@ func (suite *GenesisTestSuite) SetupTest() {
msr := suite.baseApp.MsgServiceRouter()
msr.SetInterfaceRegistry(suite.encCfg.InterfaceRegistry)

suite.keeper = keeper.NewKeeper(storeService, suite.encCfg.Codec, msr, suite.accountKeeper)
suite.keeper = keeper.NewKeeper(env, suite.encCfg.Codec, msr, suite.accountKeeper)
}

func (suite *GenesisTestSuite) TestImportExportGenesis() {
Expand Down
6 changes: 3 additions & 3 deletions x/authz/keeper/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (k Keeper) Grants(ctx context.Context, req *authz.QueryGrantsRequest) (*aut
}, nil
}

store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
key := grantStoreKey(grantee, granter, "")
grantsStore := prefix.NewStore(store, key)

Expand Down Expand Up @@ -100,7 +100,7 @@ func (k Keeper) GranterGrants(ctx context.Context, req *authz.QueryGranterGrants
return nil, err
}

store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
authzStore := prefix.NewStore(store, grantStoreKey(nil, granter, ""))

grants, pageRes, err := query.GenericFilteredPaginate(k.cdc, authzStore, req.Pagination, func(key []byte, auth *authz.Grant) (*authz.GrantAuthorization, error) {
Expand Down Expand Up @@ -151,7 +151,7 @@ func (k Keeper) GranteeGrants(ctx context.Context, req *authz.QueryGranteeGrants
return nil, err
}

store := prefix.NewStore(runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx)), GrantKey)
store := prefix.NewStore(runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)), GrantKey)

authorizations, pageRes, err := query.GenericFilteredPaginate(k.cdc, store, req.Pagination, func(key []byte, auth *authz.Grant) (*authz.GrantAuthorization, error) {
auth1, err := auth.GetAuthorization()
Expand Down
80 changes: 37 additions & 43 deletions x/authz/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import (
"strconv"
"time"

abci "github.com/cometbft/cometbft/abci/types"
"github.com/cosmos/gogoproto/proto"

corestoretypes "cosmossdk.io/core/store"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/event"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
Expand All @@ -30,31 +30,30 @@ import (
const gasCostPerIteration = uint64(20)

type Keeper struct {
storeService corestoretypes.KVStoreService
cdc codec.Codec
router baseapp.MessageRouter
authKeeper authz.AccountKeeper
environment appmodule.Environment
cdc codec.Codec
router baseapp.MessageRouter
authKeeper authz.AccountKeeper
}

// NewKeeper constructs a message authorization Keeper
func NewKeeper(storeService corestoretypes.KVStoreService, cdc codec.Codec, router baseapp.MessageRouter, ak authz.AccountKeeper) Keeper {
func NewKeeper(env appmodule.Environment, cdc codec.Codec, router baseapp.MessageRouter, ak authz.AccountKeeper) Keeper {
return Keeper{
storeService: storeService,
cdc: cdc,
router: router,
authKeeper: ak,
environment: env,
cdc: cdc,
router: router,
authKeeper: ak,
}
}

// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx context.Context) log.Logger {
sdkCtx := sdk.UnwrapSDKContext(ctx)
return sdkCtx.Logger().With("module", fmt.Sprintf("x/%s", authz.ModuleName))
func (k Keeper) Logger() log.Logger {
return k.environment.Logger.With("module", fmt.Sprintf("x/%s", authz.ModuleName))
}

// getGrant returns grant stored at skey.
func (k Keeper) getGrant(ctx context.Context, skey []byte) (grant authz.Grant, found bool) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)

bz, err := store.Get(skey)
if err != nil {
Expand Down Expand Up @@ -86,7 +85,7 @@ func (k Keeper) update(ctx context.Context, grantee, granter sdk.AccAddress, upd
}

grant.Authorization = any
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
return store.Set(skey, k.cdc.MustMarshal(&grant))
}

Expand Down Expand Up @@ -165,16 +164,16 @@ func (k Keeper) DispatchActions(ctx context.Context, grantee sdk.AccAddress, msg
results[i] = msgResp.Data

// emit the events from the dispatched actions
events := msgResp.Events
sdkEvents := make([]sdk.Event, 0, len(events))
for _, event := range events {
e := event
e.Attributes = append(e.Attributes, abci.EventAttribute{Key: "authz_msg_index", Value: strconv.Itoa(i)})

sdkEvents = append(sdkEvents, sdk.Event(e))
for i = range msgResp.Events {
err := k.environment.EventService.EventManager(ctx).EmitKV(
"dispatch actions",
event.NewAttribute("authz_msg_index", strconv.Itoa(i)),
)
if err != nil {
return nil, err
}
}

sdkCtx.EventManager().EmitEvents(sdkEvents)
}

return results, nil
Expand All @@ -184,12 +183,11 @@ func (k Keeper) DispatchActions(ctx context.Context, grantee sdk.AccAddress, msg
// with the provided expiration time and insert authorization key into the grants queue. If there is an existing authorization grant for the
// same `sdk.Msg` type, this grant overwrites that.
func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress, authorization authz.Authorization, expiration *time.Time) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
msgType := authorization.MsgTypeURL()
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
skey := grantStoreKey(grantee, granter, msgType)

grant, err := authz.NewGrant(sdkCtx.HeaderInfo().Time, authorization, expiration)
grant, err := authz.NewGrant(k.environment.HeaderService.GetHeaderInfo(ctx).Time, authorization, expiration)
if err != nil {
return err
}
Expand Down Expand Up @@ -222,7 +220,7 @@ func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress,
return err
}

return sdkCtx.EventManager().EmitTypedEvent(&authz.EventGrant{
return k.environment.EventService.EventManager(ctx).Emit(&authz.EventGrant{
MsgTypeUrl: authorization.MsgTypeURL(),
Granter: granter.String(),
Grantee: grantee.String(),
Expand All @@ -232,7 +230,7 @@ func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress,
// DeleteGrant revokes any authorization for the provided message type granted to the grantee
// by the granter.
func (k Keeper) DeleteGrant(ctx context.Context, grantee, granter sdk.AccAddress, msgType string) error {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
skey := grantStoreKey(grantee, granter, msgType)
grant, found := k.getGrant(ctx, skey)
if !found {
Expand All @@ -251,8 +249,7 @@ func (k Keeper) DeleteGrant(ctx context.Context, grantee, granter sdk.AccAddress
return err
}

sdkCtx := sdk.UnwrapSDKContext(ctx)
return sdkCtx.EventManager().EmitTypedEvent(&authz.EventRevoke{
return k.environment.EventService.EventManager(ctx).Emit(&authz.EventRevoke{
MsgTypeUrl: msgType,
Granter: granter.String(),
Grantee: grantee.String(),
Expand All @@ -261,7 +258,7 @@ func (k Keeper) DeleteGrant(ctx context.Context, grantee, granter sdk.AccAddress

// GetAuthorizations Returns list of `Authorizations` granted to the grantee by the granter.
func (k Keeper) GetAuthorizations(ctx context.Context, grantee, granter sdk.AccAddress) ([]authz.Authorization, error) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
key := grantStoreKey(grantee, granter, "")
iter := storetypes.KVStorePrefixIterator(store, key)
defer iter.Close()
Expand Down Expand Up @@ -290,9 +287,8 @@ func (k Keeper) GetAuthorizations(ctx context.Context, grantee, granter sdk.AccA
// - A grant is found, but it is expired.
// - There was an error getting the authorization from the grant.
func (k Keeper) GetAuthorization(ctx context.Context, grantee, granter sdk.AccAddress, msgType string) (authz.Authorization, *time.Time) {
sdkCtx := sdk.UnwrapSDKContext(ctx)
grant, found := k.getGrant(ctx, grantStoreKey(grantee, granter, msgType))
if !found || (grant.Expiration != nil && grant.Expiration.Before(sdkCtx.HeaderInfo().Time)) {
if !found || (grant.Expiration != nil && grant.Expiration.Before(k.environment.HeaderService.GetHeaderInfo(ctx).Time)) {
return nil, nil
}

Expand All @@ -311,7 +307,7 @@ func (k Keeper) GetAuthorization(ctx context.Context, grantee, granter sdk.AccAd
func (k Keeper) IterateGrants(ctx context.Context,
handler func(granterAddr, granteeAddr sdk.AccAddress, grant authz.Grant) bool,
) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, GrantKey)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
Expand All @@ -325,7 +321,7 @@ func (k Keeper) IterateGrants(ctx context.Context,
}

func (k Keeper) getGrantQueueItem(ctx context.Context, expiration time.Time, granter, grantee sdk.AccAddress) (*authz.GrantQueueItem, error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
bz, err := store.Get(GrantQueueKey(expiration, granter, grantee))
if err != nil {
return nil, err
Expand All @@ -345,7 +341,7 @@ func (k Keeper) getGrantQueueItem(ctx context.Context, expiration time.Time, gra
func (k Keeper) setGrantQueueItem(ctx context.Context, expiration time.Time,
granter, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem,
) error {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
bz, err := k.cdc.Marshal(queueItems)
if err != nil {
return err
Expand All @@ -366,7 +362,7 @@ func (k Keeper) insertIntoGrantQueue(ctx context.Context, granter, grantee sdk.A

// removeFromGrantQueue removes a grant key from the grant queue
func (k Keeper) removeFromGrantQueue(ctx context.Context, grantKey []byte, granter, grantee sdk.AccAddress, expiration time.Time) error {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
key := GrantQueueKey(expiration, granter, grantee)
bz, err := store.Get(key)
if err != nil {
Expand All @@ -385,9 +381,8 @@ func (k Keeper) removeFromGrantQueue(ctx context.Context, grantKey []byte, grant
_, _, msgType := parseGrantStoreKey(grantKey)
queueItems := queueItem.MsgTypeUrls

sdkCtx := sdk.UnwrapSDKContext(ctx)
for index, typeURL := range queueItems {
sdkCtx.GasMeter().ConsumeGas(gasCostPerIteration, "grant queue")
k.environment.GasService.GetGasMeter(ctx).Consume(gasCostPerIteration, "grant queue")

if typeURL == msgType {
end := len(queueItem.MsgTypeUrls) - 1
Expand All @@ -408,10 +403,9 @@ func (k Keeper) removeFromGrantQueue(ctx context.Context, grantKey []byte, grant

// DequeueAndDeleteExpiredGrants deletes expired grants from the state and grant queue.
func (k Keeper) DequeueAndDeleteExpiredGrants(ctx context.Context, limit int) error {
store := k.storeService.OpenKVStore(ctx)
sdkCtx := sdk.UnwrapSDKContext(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)

iterator, err := store.Iterator(GrantQueuePrefix, storetypes.InclusiveEndBytes(GrantQueueTimePrefix(sdkCtx.HeaderInfo().Time)))
iterator, err := store.Iterator(GrantQueuePrefix, storetypes.InclusiveEndBytes(GrantQueueTimePrefix(k.environment.HeaderService.GetHeaderInfo(ctx).Time)))
if err != nil {
return err
}
Expand Down
3 changes: 2 additions & 1 deletion x/authz/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func (s *TestSuite) SetupTest() {
testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test"))
s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now().Round(0).UTC()})
s.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{})
env := runtime.NewEnvironment(storeService, log.NewNopLogger())

s.baseApp = baseapp.NewBaseApp(
"authz",
Expand All @@ -74,7 +75,7 @@ func (s *TestSuite) SetupTest() {
banktypes.RegisterInterfaces(s.encCfg.InterfaceRegistry)
banktypes.RegisterMsgServer(s.baseApp.MsgServiceRouter(), s.bankKeeper)

s.authzKeeper = authzkeeper.NewKeeper(storeService, s.encCfg.Codec, s.baseApp.MsgServiceRouter(), s.accountKeeper)
s.authzKeeper = authzkeeper.NewKeeper(env, s.encCfg.Codec, s.baseApp.MsgServiceRouter(), s.accountKeeper)

queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, s.encCfg.InterfaceRegistry)
authz.RegisterQueryServer(queryHelper, s.authzKeeper)
Expand Down
2 changes: 1 addition & 1 deletion x/authz/keeper/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ func NewMigrator(keeper Keeper) Migrator {

// Migrate1to2 migrates from version 1 to 2.
func (m Migrator) Migrate1to2(ctx context.Context) error {
return v2.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc)
return v2.MigrateStore(ctx, m.keeper.environment, m.keeper.cdc)
}
6 changes: 4 additions & 2 deletions x/authz/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,10 @@ func (k Keeper) PruneExpiredGrants(ctx context.Context, msg *authz.MsgPruneExpir
return nil, err
}

sdkCtx := sdk.UnwrapSDKContext(ctx)
_ = sdkCtx.EventManager().EmitTypedEvent(&authz.EventPruneExpiredGrants{Pruner: msg.Pruner})
err := k.environment.EventService.EventManager(ctx).Emit(&authz.EventPruneExpiredGrants{Pruner: msg.Pruner})
if err != nil {
return nil, err
}

return &authz.MsgPruneExpiredGrantsResponse{}, nil
}
Expand Down
15 changes: 6 additions & 9 deletions x/authz/migrations/v2/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,38 @@ package v2
import (
"context"

corestoretypes "cosmossdk.io/core/store"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/authz"
"cosmossdk.io/x/authz/internal/conv"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
sdk "github.com/cosmos/cosmos-sdk/types"
)

// MigrateStore performs in-place store migrations from v0.45 to v0.46. The
// migration includes:
//
// - pruning expired authorizations
// - create secondary index for pruning expired authorizations
func MigrateStore(ctx context.Context, storeService corestoretypes.KVStoreService, cdc codec.BinaryCodec) error {
store := storeService.OpenKVStore(ctx)
sdkCtx := sdk.UnwrapSDKContext(ctx)
err := addExpiredGrantsIndex(sdkCtx, runtime.KVStoreAdapter(store), cdc)
func MigrateStore(ctx context.Context, env appmodule.Environment, cdc codec.BinaryCodec) error {
err := addExpiredGrantsIndex(ctx, env, cdc)
if err != nil {
return err
}

return nil
}

func addExpiredGrantsIndex(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec) error {
func addExpiredGrantsIndex(ctx context.Context, env appmodule.Environment, cdc codec.BinaryCodec) error {
store := runtime.KVStoreAdapter(env.KVStoreService.OpenKVStore(ctx))
grantsStore := prefix.NewStore(store, GrantPrefix)

grantsIter := grantsStore.Iterator(nil, nil)
defer grantsIter.Close()

queueItems := make(map[string][]string)
now := ctx.HeaderInfo().Time
now := env.HeaderService.GetHeaderInfo(ctx).Time
for ; grantsIter.Valid(); grantsIter.Next() {
var grant authz.Grant
bz := grantsIter.Value()
Expand Down
4 changes: 3 additions & 1 deletion x/authz/migrations/v2/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

govtypes "cosmossdk.io/api/cosmos/gov/v1beta1"
"cosmossdk.io/core/header"
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/authz"
v2 "cosmossdk.io/x/authz/migrations/v2"
Expand Down Expand Up @@ -104,6 +105,7 @@ func TestMigration(t *testing.T) {

storeService := runtime.NewKVStoreService(authzKey)
store := storeService.OpenKVStore(ctx)
env := runtime.NewEnvironment(storeService, log.NewNopLogger())

for _, g := range grants {
grant := g.authorization()
Expand All @@ -112,7 +114,7 @@ func TestMigration(t *testing.T) {
}

ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(1 * time.Hour)})
require.NoError(t, v2.MigrateStore(ctx, storeService, cdc))
require.NoError(t, v2.MigrateStore(ctx, env, cdc))

bz, err := store.Get(v2.GrantStoreKey(grantee1, granter2, genericMsgType))
require.NoError(t, err)
Expand Down
Loading