7 "github.com/golang/groupcache/lru"
8 "github.com/golang/groupcache/singleflight"
10 "github.com/vapor/protocol/bc"
11 "github.com/vapor/protocol/bc/types"
14 const maxCachedBlocks = 30
16 func newBlockCache(fillFn func(hash *bc.Hash) (*types.Block, error)) blockCache {
18 lru: lru.New(maxCachedBlocks),
23 type blockCache struct {
26 fillFn func(hash *bc.Hash) (*types.Block, error)
27 single singleflight.Group
30 func (c *blockCache) lookup(hash *bc.Hash) (*types.Block, error) {
31 if b, ok := c.get(hash); ok {
35 block, err := c.single.Do(hash.String(), func() (interface{}, error) {
36 b, err := c.fillFn(hash)
42 return nil, fmt.Errorf("There are no block with given hash %s", hash.String())
51 return block.(*types.Block), nil
54 func (c *blockCache) get(hash *bc.Hash) (*types.Block, bool) {
56 block, ok := c.lru.Get(*hash)
61 return block.(*types.Block), ok
64 func (c *blockCache) add(block *types.Block) {
66 c.lru.Add(block.Hash(), block)