forked from babylonlabs-io/babylon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindexed_blocks.go
56 lines (48 loc) · 1.59 KB
/
indexed_blocks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package keeper
import (
"context"
"cosmossdk.io/store/prefix"
"github.com/babylonlabs-io/babylon/x/finality/types"
"github.com/cosmos/cosmos-sdk/runtime"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// IndexBlock indexes the current block, saves the corresponding indexed block
// to KVStore
func (k Keeper) IndexBlock(ctx context.Context) {
headerInfo := sdk.UnwrapSDKContext(ctx).HeaderInfo()
ib := &types.IndexedBlock{
Height: uint64(headerInfo.Height),
AppHash: headerInfo.AppHash,
Finalized: false,
}
k.SetBlock(ctx, ib)
// record the block height
types.RecordLastHeight(uint64(headerInfo.Height))
}
func (k Keeper) SetBlock(ctx context.Context, block *types.IndexedBlock) {
store := k.blockStore(ctx)
blockBytes := k.cdc.MustMarshal(block)
store.Set(sdk.Uint64ToBigEndian(block.Height), blockBytes)
}
func (k Keeper) HasBlock(ctx context.Context, height uint64) bool {
store := k.blockStore(ctx)
return store.Has(sdk.Uint64ToBigEndian(height))
}
func (k Keeper) GetBlock(ctx context.Context, height uint64) (*types.IndexedBlock, error) {
store := k.blockStore(ctx)
blockBytes := store.Get(sdk.Uint64ToBigEndian(height))
if len(blockBytes) == 0 {
return nil, types.ErrBlockNotFound
}
var block types.IndexedBlock
k.cdc.MustUnmarshal(blockBytes, &block)
return &block, nil
}
// blockStore returns the KVStore of the blocks
// prefix: BlockKey
// key: block height
// value: IndexedBlock
func (k Keeper) blockStore(ctx context.Context) prefix.Store {
storeAdapter := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
return prefix.NewStore(storeAdapter, types.BlockKey)
}