block_cache.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package core
  2. import (
  3. "sync"
  4. "github.com/ethereum/go-ethereum/common"
  5. "github.com/ethereum/go-ethereum/core/types"
  6. )
  7. // BlockCache implements a caching mechanism specifically for blocks and uses FILO to pop
  8. type BlockCache struct {
  9. size int
  10. hashes []common.Hash
  11. blocks map[common.Hash]*types.Block
  12. mu sync.RWMutex
  13. }
  14. // Creates and returns a `BlockCache` with `size`. If `size` is smaller than 1 it will panic
  15. func NewBlockCache(size int) *BlockCache {
  16. if size < 1 {
  17. panic("block cache size not allowed to be smaller than 1")
  18. }
  19. bc := &BlockCache{size: size}
  20. bc.Clear()
  21. return bc
  22. }
  23. func (bc *BlockCache) Clear() {
  24. bc.blocks = make(map[common.Hash]*types.Block)
  25. bc.hashes = nil
  26. }
  27. func (bc *BlockCache) Push(block *types.Block) {
  28. bc.mu.Lock()
  29. defer bc.mu.Unlock()
  30. if len(bc.hashes) == bc.size {
  31. delete(bc.blocks, bc.hashes[0])
  32. // XXX There are a few other options on solving this
  33. // 1) use a poller / GC like mechanism to clean up untracked objects
  34. // 2) copy as below
  35. // re-use the slice and remove the reference to bc.hashes[0]
  36. // this will allow the element to be garbage collected.
  37. copy(bc.hashes, bc.hashes[1:])
  38. } else {
  39. bc.hashes = append(bc.hashes, common.Hash{})
  40. }
  41. hash := block.Hash()
  42. bc.blocks[hash] = block
  43. bc.hashes[len(bc.hashes)-1] = hash
  44. }
  45. func (bc *BlockCache) Get(hash common.Hash) *types.Block {
  46. bc.mu.RLock()
  47. defer bc.mu.RUnlock()
  48. if block, haz := bc.blocks[hash]; haz {
  49. return block
  50. }
  51. return nil
  52. }
  53. func (bc *BlockCache) Has(hash common.Hash) bool {
  54. _, ok := bc.blocks[hash]
  55. return ok
  56. }