github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/x/staking/keeper/historical_info.go (about) 1 package keeper 2 3 import ( 4 sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types" 5 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/staking/types" 6 ) 7 8 // GetHistoricalInfo gets the historical info at a given height 9 func (k Keeper) GetHistoricalInfo(ctx sdk.Context, height int64) (types.HistoricalInfo, bool) { 10 store := ctx.KVStore(k.storeKey) 11 key := types.GetHistoricalInfoKey(height) 12 13 value := store.Get(key) 14 if value == nil { 15 return types.HistoricalInfo{}, false 16 } 17 18 hi := types.MustUnmarshalHistoricalInfo(k.cdc, value) 19 return hi, true 20 } 21 22 // SetHistoricalInfo sets the historical info at a given height 23 func (k Keeper) SetHistoricalInfo(ctx sdk.Context, height int64, hi types.HistoricalInfo) { 24 store := ctx.KVStore(k.storeKey) 25 key := types.GetHistoricalInfoKey(height) 26 27 value := types.MustMarshalHistoricalInfo(k.cdc, hi) 28 store.Set(key, value) 29 } 30 31 // DeleteHistoricalInfo deletes the historical info at a given height 32 func (k Keeper) DeleteHistoricalInfo(ctx sdk.Context, height int64) { 33 store := ctx.KVStore(k.storeKey) 34 key := types.GetHistoricalInfoKey(height) 35 36 store.Delete(key) 37 } 38 39 // TrackHistoricalInfo saves the latest historical-info and deletes the oldest 40 // heights that are below pruning height 41 func (k Keeper) TrackHistoricalInfo(ctx sdk.Context) { 42 entryNum := k.HistoricalEntries(ctx) 43 44 // Prune store to ensure we only have parameter-defined historical entries. 45 // In most cases, this will involve removing a single historical entry. 46 // In the rare scenario when the historical entries gets reduced to a lower value k' 47 // from the original value k. k - k' entries must be deleted from the store. 48 // Since the entries to be deleted are always in a continuous range, we can iterate 49 // over the historical entries starting from the most recent version to be pruned 50 // and then return at the first empty entry. 51 for i := ctx.BlockHeight() - int64(entryNum); i >= 0; i-- { 52 _, found := k.GetHistoricalInfo(ctx, i) 53 if found { 54 k.DeleteHistoricalInfo(ctx, i) 55 } else { 56 break 57 } 58 } 59 60 // if there is no need to persist historicalInfo, return 61 if entryNum == 0 { 62 return 63 } 64 65 // Create HistoricalInfo struct 66 lastVals := k.GetLastValidators(ctx) 67 historicalEntry := types.NewHistoricalInfo(ctx.BlockHeader(), lastVals) 68 69 // Set latest HistoricalInfo at current height 70 k.SetHistoricalInfo(ctx, ctx.BlockHeight(), historicalEntry) 71 }