github.com/cosmos/cosmos-sdk@v0.50.10/x/authz/migrations/v2/store.go (about)

     1  package v2
     2  
     3  import (
     4  	"context"
     5  
     6  	corestoretypes "cosmossdk.io/core/store"
     7  	"cosmossdk.io/store/prefix"
     8  	storetypes "cosmossdk.io/store/types"
     9  
    10  	"github.com/cosmos/cosmos-sdk/codec"
    11  	"github.com/cosmos/cosmos-sdk/internal/conv"
    12  	"github.com/cosmos/cosmos-sdk/runtime"
    13  	sdk "github.com/cosmos/cosmos-sdk/types"
    14  	"github.com/cosmos/cosmos-sdk/x/authz"
    15  )
    16  
    17  // MigrateStore performs in-place store migrations from v0.45 to v0.46. The
    18  // migration includes:
    19  //
    20  // - pruning expired authorizations
    21  // - create secondary index for pruning expired authorizations
    22  func MigrateStore(ctx context.Context, storeService corestoretypes.KVStoreService, cdc codec.BinaryCodec) error {
    23  	store := storeService.OpenKVStore(ctx)
    24  	sdkCtx := sdk.UnwrapSDKContext(ctx)
    25  	err := addExpiredGrantsIndex(sdkCtx, runtime.KVStoreAdapter(store), cdc)
    26  	if err != nil {
    27  		return err
    28  	}
    29  
    30  	return nil
    31  }
    32  
    33  func addExpiredGrantsIndex(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec) error {
    34  	grantsStore := prefix.NewStore(store, GrantPrefix)
    35  
    36  	grantsIter := grantsStore.Iterator(nil, nil)
    37  	defer grantsIter.Close()
    38  
    39  	queueItems := make(map[string][]string)
    40  	now := ctx.BlockTime()
    41  	for ; grantsIter.Valid(); grantsIter.Next() {
    42  		var grant authz.Grant
    43  		bz := grantsIter.Value()
    44  		if err := cdc.Unmarshal(bz, &grant); err != nil {
    45  			return err
    46  		}
    47  
    48  		// delete expired authorization
    49  		// before 0.46 Expiration was required so it's safe to dereference
    50  		if grant.Expiration.Before(now) {
    51  			grantsStore.Delete(grantsIter.Key())
    52  		} else {
    53  			granter, grantee, msgType := ParseGrantKey(grantsIter.Key())
    54  			// before 0.46 expiration was not a pointer, so now it's safe to dereference
    55  			key := GrantQueueKey(*grant.Expiration, granter, grantee)
    56  
    57  			queueItem, ok := queueItems[conv.UnsafeBytesToStr(key)]
    58  			if !ok {
    59  				queueItems[string(key)] = []string{msgType}
    60  			} else {
    61  				queueItem = append(queueItem, msgType)
    62  				queueItems[string(key)] = queueItem
    63  			}
    64  		}
    65  	}
    66  
    67  	for key, v := range queueItems {
    68  		bz, err := cdc.Marshal(&authz.GrantQueueItem{
    69  			MsgTypeUrls: v,
    70  		})
    71  		if err != nil {
    72  			return err
    73  		}
    74  		store.Set(conv.UnsafeStrToBytes(key), bz)
    75  	}
    76  
    77  	return nil
    78  }