cache_test.go 2.24 KB
Newer Older
1 2 3 4 5 6
package l2

import (
	"math/rand"
	"testing"

7
	"github.com/ethereum-optimism/optimism/op-program/client/l2/test"
8
	"github.com/ethereum-optimism/optimism/op-service/eth"
Sabnock01's avatar
Sabnock01 committed
9
	"github.com/ethereum-optimism/optimism/op-service/testutils"
10 11 12 13 14 15 16 17
	"github.com/ethereum/go-ethereum/common"
	"github.com/stretchr/testify/require"
)

// Should be an Oracle implementation
var _ Oracle = (*CachingOracle)(nil)

func TestBlockByHash(t *testing.T) {
18
	stub, _ := test.NewStubOracle(t)
19 20 21 22 23 24
	oracle := NewCachingOracle(stub)

	rng := rand.New(rand.NewSource(1))
	block, _ := testutils.RandomBlock(rng, 1)

	// Initial call retrieves from the stub
25
	stub.Blocks[block.Hash()] = block
26 27 28 29
	actual := oracle.BlockByHash(block.Hash())
	require.Equal(t, block, actual)

	// Later calls should retrieve from cache
30
	delete(stub.Blocks, block.Hash())
31 32 33 34 35
	actual = oracle.BlockByHash(block.Hash())
	require.Equal(t, block, actual)
}

func TestNodeByHash(t *testing.T) {
36
	stub, stateStub := test.NewStubOracle(t)
37 38 39 40 41 42
	oracle := NewCachingOracle(stub)

	node := []byte{12, 3, 4}
	hash := common.Hash{0xaa}

	// Initial call retrieves from the stub
43
	stateStub.Data[hash] = node
44 45 46 47
	actual := oracle.NodeByHash(hash)
	require.Equal(t, node, actual)

	// Later calls should retrieve from cache
48
	delete(stateStub.Data, hash)
49 50 51 52 53
	actual = oracle.NodeByHash(hash)
	require.Equal(t, node, actual)
}

func TestCodeByHash(t *testing.T) {
54
	stub, stateStub := test.NewStubOracle(t)
55 56 57 58 59 60
	oracle := NewCachingOracle(stub)

	node := []byte{12, 3, 4}
	hash := common.Hash{0xaa}

	// Initial call retrieves from the stub
61
	stateStub.Code[hash] = node
62 63 64 65
	actual := oracle.CodeByHash(hash)
	require.Equal(t, node, actual)

	// Later calls should retrieve from cache
66
	delete(stateStub.Code, hash)
67 68 69
	actual = oracle.CodeByHash(hash)
	require.Equal(t, node, actual)
}
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

func TestOutputByRoot(t *testing.T) {
	stub, _ := test.NewStubOracle(t)
	oracle := NewCachingOracle(stub)

	rng := rand.New(rand.NewSource(1))
	output := testutils.RandomOutputV0(rng)

	// Initial call retrieves from the stub
	root := common.Hash(eth.OutputRoot(output))
	stub.Outputs[root] = output
	actual := oracle.OutputByRoot(root)
	require.Equal(t, output, actual)

	// Later calls should retrieve from cache
	delete(stub.Outputs, root)
	actual = oracle.OutputByRoot(root)
	require.Equal(t, output, actual)
}