block_cache.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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) Delete(hash common.Hash) {
  46. bc.mu.Lock()
  47. defer bc.mu.Unlock()
  48. if _, ok := bc.blocks[hash]; ok {
  49. delete(bc.blocks, hash)
  50. for i, h := range bc.hashes {
  51. if hash == h {
  52. bc.hashes = bc.hashes[:i+copy(bc.hashes[i:], bc.hashes[i+1:])]
  53. // or ? => bc.hashes = append(bc.hashes[:i], bc.hashes[i+1]...)
  54. break
  55. }
  56. }
  57. }
  58. }
  59. func (bc *BlockCache) Get(hash common.Hash) *types.Block {
  60. bc.mu.RLock()
  61. defer bc.mu.RUnlock()
  62. if block, haz := bc.blocks[hash]; haz {
  63. return block
  64. }
  65. return nil
  66. }
  67. func (bc *BlockCache) Has(hash common.Hash) bool {
  68. bc.mu.RLock()
  69. defer bc.mu.RUnlock()
  70. _, ok := bc.blocks[hash]
  71. return ok
  72. }
  73. func (bc *BlockCache) Each(cb func(int, *types.Block)) {
  74. bc.mu.Lock()
  75. defer bc.mu.Unlock()
  76. i := 0
  77. for _, block := range bc.blocks {
  78. cb(i, block)
  79. i++
  80. }
  81. }