|
| 1 | +// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved. |
| 2 | +// See the file LICENSE for licensing terms. |
| 3 | + |
| 4 | +package database |
| 5 | + |
| 6 | +import ( |
| 7 | + "sync" |
| 8 | + |
| 9 | + "github.com/ava-labs/libevm/common" |
| 10 | +) |
| 11 | + |
| 12 | +// blockCache is a cache for block header and body. |
| 13 | +// It allows saving body and header separately via save while |
| 14 | +// fetching both body and header at once via get. |
| 15 | +type blockCache struct { |
| 16 | + bodyCache map[common.Hash][]byte |
| 17 | + headerCache map[common.Hash][]byte |
| 18 | + mu sync.RWMutex |
| 19 | +} |
| 20 | + |
| 21 | +func newBlockCache() *blockCache { |
| 22 | + return &blockCache{ |
| 23 | + bodyCache: make(map[common.Hash][]byte), |
| 24 | + headerCache: make(map[common.Hash][]byte), |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func (b *blockCache) get(blockHash common.Hash) ([]byte, []byte, bool) { |
| 29 | + b.mu.RLock() |
| 30 | + defer b.mu.RUnlock() |
| 31 | + bodyData, hasBody := b.bodyCache[blockHash] |
| 32 | + headerData, hasHeader := b.headerCache[blockHash] |
| 33 | + return bodyData, headerData, hasBody && hasHeader |
| 34 | +} |
| 35 | + |
| 36 | +func (b *blockCache) clear(blockHash common.Hash) { |
| 37 | + b.mu.Lock() |
| 38 | + defer b.mu.Unlock() |
| 39 | + delete(b.bodyCache, blockHash) |
| 40 | + delete(b.headerCache, blockHash) |
| 41 | +} |
| 42 | + |
| 43 | +func (b *blockCache) save(key []byte, blockHash common.Hash, value []byte) { |
| 44 | + b.mu.Lock() |
| 45 | + defer b.mu.Unlock() |
| 46 | + if isBodyKey(key) { |
| 47 | + b.bodyCache[blockHash] = value |
| 48 | + } else if isHeaderKey(key) { |
| 49 | + b.headerCache[blockHash] = value |
| 50 | + } |
| 51 | +} |
0 commit comments