forked from celestiaorg/celestia-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheight_indexer.go
58 lines (47 loc) · 1.45 KB
/
height_indexer.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
57
58
package store
import (
"context"
lru "github.com/hashicorp/golang-lru"
"github.com/ipfs/go-datastore"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
"github.com/celestiaorg/celestia-node/header"
)
// TODO(@Wondertan): There should be a more clever way to index heights, than just storing HeightToHash pair...
// heightIndexer simply stores and cashes mappings between header Height and Hash.
type heightIndexer struct {
ds datastore.Batching
cache *lru.ARCCache
}
// newHeightIndexer creates new heightIndexer.
func newHeightIndexer(ds datastore.Batching) (*heightIndexer, error) {
cache, err := lru.NewARC(DefaultIndexCacheSize)
if err != nil {
return nil, err
}
return &heightIndexer{
ds: ds,
cache: cache,
}, nil
}
// HashByHeight loads a header hash corresponding to the given height.
func (hi *heightIndexer) HashByHeight(ctx context.Context, h uint64) (tmbytes.HexBytes, error) {
if v, ok := hi.cache.Get(h); ok {
return v.(tmbytes.HexBytes), nil
}
val, err := hi.ds.Get(ctx, heightKey(h))
if err != nil {
return nil, err
}
hi.cache.Add(h, tmbytes.HexBytes(val))
return val, nil
}
// IndexTo saves mapping between header Height and Hash to the given batch.
func (hi *heightIndexer) IndexTo(ctx context.Context, batch datastore.Batch, headers ...*header.ExtendedHeader) error {
for _, h := range headers {
err := batch.Put(ctx, heightKey(uint64(h.Height)), h.Hash())
if err != nil {
return err
}
}
return nil
}