cache.go 2.04 KB
Newer Older
1 2 3
package l2

import (
4
	"github.com/ethereum-optimism/optimism/op-service/eth"
5 6
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
7
	"github.com/hashicorp/golang-lru/v2/simplelru"
8 9
)

10 11 12
// blockCacheSize should be set large enough to handle the pipeline reset process of walking back from L2 head to find
// the L1 origin that is old enough to start buffering channel data from.
const blockCacheSize = 3_000
13 14 15
const nodeCacheSize = 100_000
const codeCacheSize = 10_000

16
type CachingOracle struct {
17 18 19 20 21
	oracle  Oracle
	blocks  *simplelru.LRU[common.Hash, *types.Block]
	nodes   *simplelru.LRU[common.Hash, []byte]
	codes   *simplelru.LRU[common.Hash, []byte]
	outputs *simplelru.LRU[common.Hash, eth.Output]
22 23 24
}

func NewCachingOracle(oracle Oracle) *CachingOracle {
25 26 27
	blockLRU, _ := simplelru.NewLRU[common.Hash, *types.Block](blockCacheSize, nil)
	nodeLRU, _ := simplelru.NewLRU[common.Hash, []byte](nodeCacheSize, nil)
	codeLRU, _ := simplelru.NewLRU[common.Hash, []byte](codeCacheSize, nil)
28
	outputLRU, _ := simplelru.NewLRU[common.Hash, eth.Output](codeCacheSize, nil)
29
	return &CachingOracle{
30 31 32 33 34
		oracle:  oracle,
		blocks:  blockLRU,
		nodes:   nodeLRU,
		codes:   codeLRU,
		outputs: outputLRU,
35 36 37
	}
}

38 39
func (o *CachingOracle) NodeByHash(nodeHash common.Hash) []byte {
	node, ok := o.nodes.Get(nodeHash)
40 41 42 43
	if ok {
		return node
	}
	node = o.oracle.NodeByHash(nodeHash)
44
	o.nodes.Add(nodeHash, node)
45 46 47
	return node
}

48 49
func (o *CachingOracle) CodeByHash(codeHash common.Hash) []byte {
	code, ok := o.codes.Get(codeHash)
50 51 52 53
	if ok {
		return code
	}
	code = o.oracle.CodeByHash(codeHash)
54
	o.codes.Add(codeHash, code)
55 56 57
	return code
}

58 59
func (o *CachingOracle) BlockByHash(blockHash common.Hash) *types.Block {
	block, ok := o.blocks.Get(blockHash)
60 61 62 63
	if ok {
		return block
	}
	block = o.oracle.BlockByHash(blockHash)
64
	o.blocks.Add(blockHash, block)
65 66
	return block
}
67 68 69 70 71 72 73 74 75 76

func (o *CachingOracle) OutputByRoot(root common.Hash) eth.Output {
	output, ok := o.outputs.Get(root)
	if ok {
		return output
	}
	output = o.oracle.OutputByRoot(root)
	o.outputs.Add(root, output)
	return output
}