engine_backend.go 7.18 KB
Newer Older
1 2 3 4 5 6
package l2

import (
	"fmt"
	"math/big"

7
	"github.com/ethereum-optimism/optimism/op-program/client/l2/engineapi"
8
	"github.com/ethereum-optimism/optimism/op-service/eth"
9 10 11 12 13
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/consensus"
	"github.com/ethereum/go-ethereum/consensus/beacon"
	"github.com/ethereum/go-ethereum/core/rawdb"
	"github.com/ethereum/go-ethereum/core/state"
14
	"github.com/ethereum/go-ethereum/core/stateless"
15 16 17 18 19
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/core/vm"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/params"
20
	"github.com/ethereum/go-ethereum/triedb"
21 22 23
)

type OracleBackedL2Chain struct {
24 25 26 27 28 29 30 31 32
	log        log.Logger
	oracle     Oracle
	chainCfg   *params.ChainConfig
	engine     consensus.Engine
	oracleHead *types.Header
	head       *types.Header
	safe       *types.Header
	finalized  *types.Header
	vmCfg      vm.Config
33

34 35 36 37
	// Block by number cache
	hashByNum            map[uint64]common.Hash
	earliestIndexedBlock *types.Header

38 39 40 41 42
	// Inserted blocks
	blocks map[common.Hash]*types.Block
	db     ethdb.KeyValueStore
}

43 44 45
// Must implement CachingEngineBackend, not just EngineBackend to ensure that blocks are stored when they are created
// and don't need to be re-executed when sent back via execution_newPayload.
var _ engineapi.CachingEngineBackend = (*OracleBackedL2Chain)(nil)
46

47
func NewOracleBackedL2Chain(logger log.Logger, oracle Oracle, precompileOracle engineapi.PrecompileOracle, chainCfg *params.ChainConfig, l2OutputRoot common.Hash) (*OracleBackedL2Chain, error) {
48 49 50 51 52 53
	output := oracle.OutputByRoot(l2OutputRoot)
	outputV0, ok := output.(*eth.OutputV0)
	if !ok {
		return nil, fmt.Errorf("unsupported L2 output version: %d", output.Version())
	}
	head := oracle.BlockByHash(outputV0.BlockHash)
54
	logger.Info("Loaded L2 head", "hash", head.Hash(), "number", head.Number())
55 56 57 58 59 60
	return &OracleBackedL2Chain{
		log:      logger,
		oracle:   oracle,
		chainCfg: chainCfg,
		engine:   beacon.New(nil),

61 62 63 64 65
		hashByNum: map[uint64]common.Hash{
			head.NumberU64(): head.Hash(),
		},
		earliestIndexedBlock: head.Header(),

66
		// Treat the agreed starting head as finalized - nothing before it can be disputed
67 68 69 70 71 72
		head:       head.Header(),
		safe:       head.Header(),
		finalized:  head.Header(),
		oracleHead: head.Header(),
		blocks:     make(map[common.Hash]*types.Block),
		db:         NewOracleBackedDB(oracle),
73
		vmCfg: vm.Config{
74
			PrecompileOverrides: engineapi.CreatePrecompileOverrides(precompileOracle),
75
		},
76 77 78 79 80 81 82 83
	}, nil
}

func (o *OracleBackedL2Chain) CurrentHeader() *types.Header {
	return o.head
}

func (o *OracleBackedL2Chain) GetHeaderByNumber(n uint64) *types.Header {
84
	if o.head.Number.Uint64() < n {
85 86
		return nil
	}
87 88 89 90 91 92
	hash, ok := o.hashByNum[n]
	if ok {
		return o.GetHeaderByHash(hash)
	}
	// Walk back from current head to the requested block number
	h := o.head
93 94
	for h.Number.Uint64() > n {
		h = o.GetHeaderByHash(h.ParentHash)
95
		o.hashByNum[h.Number.Uint64()] = h.Hash()
96
	}
97
	o.earliestIndexedBlock = h
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
	return h
}

func (o *OracleBackedL2Chain) GetTd(hash common.Hash, number uint64) *big.Int {
	// Difficulty is always 0 post-merge and bedrock starts post-merge so total difficulty also always 0
	return common.Big0
}

func (o *OracleBackedL2Chain) CurrentSafeBlock() *types.Header {
	return o.safe
}

func (o *OracleBackedL2Chain) CurrentFinalBlock() *types.Header {
	return o.finalized
}

func (o *OracleBackedL2Chain) GetHeaderByHash(hash common.Hash) *types.Header {
115
	return o.GetBlockByHash(hash).Header()
116 117 118 119 120 121 122 123 124
}

func (o *OracleBackedL2Chain) GetBlockByHash(hash common.Hash) *types.Block {
	// Check inserted blocks
	block, ok := o.blocks[hash]
	if ok {
		return block
	}
	// Retrieve from the oracle
125
	return o.oracle.BlockByHash(hash)
126 127 128
}

func (o *OracleBackedL2Chain) GetBlock(hash common.Hash, number uint64) *types.Block {
129 130 131 132 133 134 135 136
	var block *types.Block
	if o.oracleHead.Number.Uint64() < number {
		// For blocks above the chain head, only consider newly built blocks
		// Avoids requesting an unknown block from the oracle which would panic.
		block = o.blocks[hash]
	} else {
		block = o.GetBlockByHash(hash)
	}
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
	if block == nil {
		return nil
	}
	if block.NumberU64() != number {
		return nil
	}
	return block
}

func (o *OracleBackedL2Chain) GetHeader(hash common.Hash, u uint64) *types.Header {
	block := o.GetBlock(hash, u)
	return block.Header()
}

func (o *OracleBackedL2Chain) HasBlockAndState(hash common.Hash, number uint64) bool {
	block := o.GetBlock(hash, number)
	return block != nil
}

func (o *OracleBackedL2Chain) GetCanonicalHash(n uint64) common.Hash {
	header := o.GetHeaderByNumber(n)
	if header == nil {
		return common.Hash{}
	}
	return header.Hash()
}

func (o *OracleBackedL2Chain) GetVMConfig() *vm.Config {
	return &o.vmCfg
}

func (o *OracleBackedL2Chain) Config() *params.ChainConfig {
	return o.chainCfg
}

func (o *OracleBackedL2Chain) Engine() consensus.Engine {
	return o.engine
}

func (o *OracleBackedL2Chain) StateAt(root common.Hash) (*state.StateDB, error) {
177
	stateDB, err := state.New(root, state.NewDatabase(triedb.NewDatabase(rawdb.NewDatabase(o.db), nil), nil))
178 179 180 181 182
	if err != nil {
		return nil, err
	}
	stateDB.MakeSinglethreaded()
	return stateDB, nil
183 184
}

185
func (o *OracleBackedL2Chain) InsertBlockWithoutSetHead(block *types.Block, makeWitness bool) (*stateless.Witness, error) {
186 187
	processor, err := engineapi.NewBlockProcessorFromHeader(o, block.Header())
	if err != nil {
188
		return nil, err
189 190 191 192
	}
	for i, tx := range block.Transactions() {
		err = processor.AddTx(tx)
		if err != nil {
193
			return nil, fmt.Errorf("invalid transaction (%d): %w", i, err)
194 195
		}
	}
196
	expected, err := o.AssembleAndInsertBlockWithoutSetHead(processor)
197
	if err != nil {
198
		return nil, fmt.Errorf("invalid block: %w", err)
199 200
	}
	if expected.Hash() != block.Hash() {
201
		return nil, fmt.Errorf("block root mismatch, expected: %v, actual: %v", expected.Hash(), block.Hash())
202
	}
203 204 205 206 207 208 209 210
	return nil, nil
}

func (o *OracleBackedL2Chain) AssembleAndInsertBlockWithoutSetHead(processor *engineapi.BlockProcessor) (*types.Block, error) {
	block, err := processor.Assemble()
	if err != nil {
		return nil, fmt.Errorf("invalid block: %w", err)
	}
211 212
	err = processor.Commit()
	if err != nil {
213
		return nil, fmt.Errorf("commit block: %w", err)
214 215
	}
	o.blocks[block.Hash()] = block
216
	return block, nil
217 218 219
}

func (o *OracleBackedL2Chain) SetCanonical(head *types.Block) (common.Hash, error) {
220
	oldHead := o.head
221
	o.head = head.Header()
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

	// Remove canonical hashes after the new header
	for n := head.NumberU64() + 1; n <= oldHead.Number.Uint64(); n++ {
		delete(o.hashByNum, n)
	}

	// Add new canonical blocks to the block by number cache
	// Since the original head is added to the block number cache and acts as the finalized block,
	// at some point we must reach the existing canonical chain and can stop updating.
	h := o.head
	for {
		newHash := h.Hash()
		prevHash, ok := o.hashByNum[h.Number.Uint64()]
		if ok && prevHash == newHash {
			// Connected with the existing canonical chain so stop updating
			break
		}
		o.hashByNum[h.Number.Uint64()] = newHash
		h = o.GetHeaderByHash(h.ParentHash)
	}
242 243 244 245 246 247 248 249 250 251
	return head.Hash(), nil
}

func (o *OracleBackedL2Chain) SetFinalized(header *types.Header) {
	o.finalized = header
}

func (o *OracleBackedL2Chain) SetSafe(header *types.Header) {
	o.safe = header
}