l2_engine_api.go 19.9 KB
Newer Older
1
package engineapi
2 3 4

import (
	"context"
5 6
	"crypto/sha256"
	"encoding/binary"
7 8
	"errors"
	"fmt"
9
	"math/big"
10 11
	"time"

12
	"github.com/ethereum-optimism/optimism/op-service/eth"
13
	"github.com/ethereum/go-ethereum/beacon/engine"
14
	"github.com/ethereum/go-ethereum/common"
15
	"github.com/ethereum/go-ethereum/consensus"
16
	"github.com/ethereum/go-ethereum/core/state"
17
	"github.com/ethereum/go-ethereum/core/types"
18
	"github.com/ethereum/go-ethereum/core/vm"
19
	"github.com/ethereum/go-ethereum/log"
20
	"github.com/ethereum/go-ethereum/params"
21 22
)

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
type EngineBackend interface {
	CurrentSafeBlock() *types.Header
	CurrentFinalBlock() *types.Header
	GetBlockByHash(hash common.Hash) *types.Block
	GetBlock(hash common.Hash, number uint64) *types.Block
	HasBlockAndState(hash common.Hash, number uint64) bool
	GetCanonicalHash(n uint64) common.Hash

	GetVMConfig() *vm.Config
	Config() *params.ChainConfig
	// Engine retrieves the chain's consensus engine.
	Engine() consensus.Engine

	StateAt(root common.Hash) (*state.StateDB, error)

	InsertBlockWithoutSetHead(block *types.Block) error
	SetCanonical(head *types.Block) (common.Hash, error)
	SetFinalized(header *types.Header)
	SetSafe(header *types.Header)
42 43

	consensus.ChainHeaderReader
44 45
}

46 47 48
// L2EngineAPI wraps an engine actor, and implements the RPC backend required to serve the engine API.
// This re-implements some of the Geth API work, but changes the API backend so we can deterministically
// build and control the L2 block contents to reach very specific edge cases as desired for testing.
49 50 51 52 53
type L2EngineAPI struct {
	log     log.Logger
	backend EngineBackend

	// L2 block building data
54 55 56 57
	blockProcessor *BlockProcessor
	pendingIndices map[common.Address]uint64 // per account, how many txs from the pool were already included in the block, since the pool is lagging behind block mining.
	l2ForceEmpty   bool                      // when no additional txs may be processed (i.e. when sequencer drift runs out)
	l2TxFailed     []*types.Transaction      // log of failed transactions which could not be included
58 59 60 61 62 63 64 65 66 67

	payloadID engine.PayloadID // ID of payload that is currently being built
}

func NewL2EngineAPI(log log.Logger, backend EngineBackend) *L2EngineAPI {
	return &L2EngineAPI{
		log:     log,
		backend: backend,
	}
}
68 69

var (
70 71
	STATUS_INVALID = &eth.ForkchoiceUpdatedResult{PayloadStatus: eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, PayloadID: nil}
	STATUS_SYNCING = &eth.ForkchoiceUpdatedResult{PayloadStatus: eth.PayloadStatusV1{Status: eth.ExecutionSyncing}, PayloadID: nil}
72 73
)

74
// computePayloadId computes a pseudo-random payloadid, based on the parameters.
75
func computePayloadId(headBlockHash common.Hash, params *eth.PayloadAttributes) engine.PayloadID {
76 77 78 79 80 81
	// Hash
	hasher := sha256.New()
	hasher.Write(headBlockHash[:])
	_ = binary.Write(hasher, binary.BigEndian, params.Timestamp)
	hasher.Write(params.PrevRandao[:])
	hasher.Write(params.SuggestedFeeRecipient[:])
82 83
	_ = binary.Write(hasher, binary.BigEndian, params.NoTxPool)
	_ = binary.Write(hasher, binary.BigEndian, uint64(len(params.Transactions)))
84 85 86 87
	for _, tx := range params.Transactions {
		_ = binary.Write(hasher, binary.BigEndian, uint64(len(tx))) // length-prefix to avoid collisions
		hasher.Write(tx)
	}
88
	_ = binary.Write(hasher, binary.BigEndian, *params.GasLimit)
89
	var out engine.PayloadID
90 91 92 93
	copy(out[:], hasher.Sum(nil)[:8])
	return out
}

94
func (ea *L2EngineAPI) RemainingBlockGas() uint64 {
95 96 97 98
	if ea.blockProcessor == nil {
		return 0
	}
	return ea.blockProcessor.gasPool.Gas()
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
}

func (ea *L2EngineAPI) ForcedEmpty() bool {
	return ea.l2ForceEmpty
}

func (ea *L2EngineAPI) PendingIndices(from common.Address) uint64 {
	return ea.pendingIndices[from]
}

var (
	ErrNotBuildingBlock = errors.New("not currently building a block, cannot include tx from queue")
)

func (ea *L2EngineAPI) IncludeTx(tx *types.Transaction, from common.Address) error {
114
	if ea.blockProcessor == nil {
115 116 117 118 119 120 121 122
		return ErrNotBuildingBlock
	}
	if ea.l2ForceEmpty {
		ea.log.Info("Skipping including a transaction because e.L2ForceEmpty is true")
		// t.InvalidAction("cannot include any sequencer txs")
		return nil
	}

123 124 125
	err := ea.blockProcessor.CheckTxWithinGasLimit(tx)
	if err != nil {
		return err
126 127 128
	}

	ea.pendingIndices[from] = ea.pendingIndices[from] + 1 // won't retry the tx
129
	err = ea.blockProcessor.AddTx(tx)
130 131
	if err != nil {
		ea.l2TxFailed = append(ea.l2TxFailed, tx)
132
		return fmt.Errorf("invalid L2 block (tx %d): %w", len(ea.blockProcessor.transactions), err)
133 134 135 136
	}
	return nil
}

137
func (ea *L2EngineAPI) startBlock(parent common.Hash, params *eth.PayloadAttributes) error {
138 139
	if ea.blockProcessor != nil {
		ea.log.Warn("started building new block without ending previous block", "previous", ea.blockProcessor.header, "prev_payload_id", ea.payloadID)
140 141
	}

142
	processor, err := NewBlockProcessorFromPayloadAttributes(ea.backend, parent, params)
143
	if err != nil {
144
		return err
145
	}
146
	ea.blockProcessor = processor
147 148 149 150 151 152 153 154
	ea.pendingIndices = make(map[common.Address]uint64)
	ea.l2ForceEmpty = params.NoTxPool
	ea.payloadID = computePayloadId(parent, params)

	// pre-process the deposits
	for i, otx := range params.Transactions {
		var tx types.Transaction
		if err := tx.UnmarshalBinary(otx); err != nil {
Joshua Gutow's avatar
Joshua Gutow committed
155
			return fmt.Errorf("transaction %d is not valid: %w", i, err)
156
		}
157
		err := ea.blockProcessor.AddTx(&tx)
158 159 160 161 162 163
		if err != nil {
			ea.l2TxFailed = append(ea.l2TxFailed, &tx)
			return fmt.Errorf("failed to apply deposit transaction to L2 block (tx %d): %w", i, err)
		}
	}
	return nil
164 165 166
}

func (ea *L2EngineAPI) endBlock() (*types.Block, error) {
167
	if ea.blockProcessor == nil {
168 169
		return nil, fmt.Errorf("no block is being built currently (id %s)", ea.payloadID)
	}
170 171
	processor := ea.blockProcessor
	ea.blockProcessor = nil
172

173 174 175 176
	block, err := processor.Assemble()
	if err != nil {
		return nil, fmt.Errorf("assemble block: %w", err)
	}
177
	return block, nil
178 179 180
}

func (ea *L2EngineAPI) GetPayloadV1(ctx context.Context, payloadId eth.PayloadID) (*eth.ExecutionPayload, error) {
181 182 183 184 185
	res, err := ea.getPayload(ctx, payloadId)
	if err != nil {
		return nil, err
	}
	return res.ExecutionPayload, nil
186 187 188
}

func (ea *L2EngineAPI) GetPayloadV2(ctx context.Context, payloadId eth.PayloadID) (*eth.ExecutionPayloadEnvelope, error) {
189 190 191 192 193
	return ea.getPayload(ctx, payloadId)
}

func (ea *L2EngineAPI) GetPayloadV3(ctx context.Context, payloadId eth.PayloadID) (*eth.ExecutionPayloadEnvelope, error) {
	return ea.getPayload(ctx, payloadId)
194 195
}

196 197 198 199
func (ea *L2EngineAPI) config() *params.ChainConfig {
	return ea.backend.Config()
}

200
func (ea *L2EngineAPI) ForkchoiceUpdatedV1(ctx context.Context, state *eth.ForkchoiceState, attr *eth.PayloadAttributes) (*eth.ForkchoiceUpdatedResult, error) {
201 202 203 204 205 206 207 208 209
	if attr != nil {
		if attr.Withdrawals != nil {
			return STATUS_INVALID, engine.InvalidParams.With(errors.New("withdrawals not supported in V1"))
		}
		if ea.config().IsShanghai(ea.config().LondonBlock, uint64(attr.Timestamp)) {
			return STATUS_INVALID, engine.InvalidParams.With(errors.New("forkChoiceUpdateV1 called post-shanghai"))
		}
	}

210 211 212 213
	return ea.forkchoiceUpdated(ctx, state, attr)
}

func (ea *L2EngineAPI) ForkchoiceUpdatedV2(ctx context.Context, state *eth.ForkchoiceState, attr *eth.PayloadAttributes) (*eth.ForkchoiceUpdatedResult, error) {
214 215 216 217 218 219
	if attr != nil {
		if err := ea.verifyPayloadAttributes(attr); err != nil {
			return STATUS_INVALID, engine.InvalidParams.With(err)
		}
	}

220 221 222
	return ea.forkchoiceUpdated(ctx, state, attr)
}

223 224 225 226 227 228 229 230 231 232 233
// Ported from: https://github.com/ethereum-optimism/op-geth/blob/c50337a60a1309a0f1dca3bf33ed1bb38c46cdd7/eth/catalyst/api.go#L197C1-L205C1
func (ea *L2EngineAPI) ForkchoiceUpdatedV3(ctx context.Context, state *eth.ForkchoiceState, attr *eth.PayloadAttributes) (*eth.ForkchoiceUpdatedResult, error) {
	if attr != nil {
		if err := ea.verifyPayloadAttributes(attr); err != nil {
			return STATUS_INVALID, engine.InvalidParams.With(err)
		}
	}
	return ea.forkchoiceUpdated(ctx, state, attr)
}

// Ported from: https://github.com/ethereum-optimism/op-geth/blob/c50337a60a1309a0f1dca3bf33ed1bb38c46cdd7/eth/catalyst/api.go#L206-L218
234 235 236 237 238 239 240
func (ea *L2EngineAPI) verifyPayloadAttributes(attr *eth.PayloadAttributes) error {
	c := ea.config()

	// Verify withdrawals attribute for Shanghai.
	if err := checkAttribute(c.IsShanghai, attr.Withdrawals != nil, c.LondonBlock, uint64(attr.Timestamp)); err != nil {
		return fmt.Errorf("invalid withdrawals: %w", err)
	}
241 242 243 244 245
	// Verify beacon root attribute for Cancun.
	if err := checkAttribute(c.IsCancun, attr.ParentBeaconBlockRoot != nil, c.LondonBlock, uint64(attr.Timestamp)); err != nil {
		return fmt.Errorf("invalid parent beacon block root: %w", err)
	}

246 247 248 249 250 251 252 253 254 255 256 257 258
	return nil
}

func checkAttribute(active func(*big.Int, uint64) bool, exists bool, block *big.Int, time uint64) error {
	if active(block, time) && !exists {
		return errors.New("fork active, missing expected attribute")
	}
	if !active(block, time) && exists {
		return errors.New("fork inactive, unexpected attribute set")
	}
	return nil
}

259
func (ea *L2EngineAPI) NewPayloadV1(ctx context.Context, payload *eth.ExecutionPayload) (*eth.PayloadStatusV1, error) {
260 261 262 263
	if payload.Withdrawals != nil {
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.InvalidParams.With(errors.New("withdrawals not supported in V1"))
	}

264
	return ea.newPayload(ctx, payload, nil, nil)
265 266
}

Danyal Prout's avatar
Danyal Prout committed
267
func (ea *L2EngineAPI) NewPayloadV2(ctx context.Context, payload *eth.ExecutionPayload) (*eth.PayloadStatusV1, error) {
268 269 270 271 272 273 274 275
	if ea.config().IsShanghai(new(big.Int).SetUint64(uint64(payload.BlockNumber)), uint64(payload.Timestamp)) {
		if payload.Withdrawals == nil {
			return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.InvalidParams.With(errors.New("nil withdrawals post-shanghai"))
		}
	} else if payload.Withdrawals != nil {
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.InvalidParams.With(errors.New("non-nil withdrawals pre-shanghai"))
	}

276
	return ea.newPayload(ctx, payload, nil, nil)
Danyal Prout's avatar
Danyal Prout committed
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
// Ported from: https://github.com/ethereum-optimism/op-geth/blob/c50337a60a1309a0f1dca3bf33ed1bb38c46cdd7/eth/catalyst/api.go#L486C1-L507
func (ea *L2EngineAPI) NewPayloadV3(ctx context.Context, params *eth.ExecutionPayload, versionedHashes []common.Hash, beaconRoot *common.Hash) (*eth.PayloadStatusV1, error) {
	if params.ExcessBlobGas == nil {
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.InvalidParams.With(errors.New("nil excessBlobGas post-cancun"))
	}
	if params.BlobGasUsed == nil {
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.InvalidParams.With(errors.New("nil params.BlobGasUsed post-cancun"))
	}
	if versionedHashes == nil {
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.InvalidParams.With(errors.New("nil versionedHashes post-cancun"))
	}
	if beaconRoot == nil {
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.InvalidParams.With(errors.New("nil parentBeaconBlockRoot post-cancun"))
	}

	if !ea.config().IsCancun(new(big.Int).SetUint64(uint64(params.BlockNumber)), uint64(params.Timestamp)) {
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid}, engine.UnsupportedFork.With(errors.New("newPayloadV3 called pre-cancun"))
	}

	return ea.newPayload(ctx, params, versionedHashes, beaconRoot)
}

func (ea *L2EngineAPI) getPayload(ctx context.Context, payloadId eth.PayloadID) (*eth.ExecutionPayloadEnvelope, error) {
302 303 304
	ea.log.Trace("L2Engine API request received", "method", "GetPayload", "id", payloadId)
	if ea.payloadID != payloadId {
		ea.log.Warn("unexpected payload ID requested for block building", "expected", ea.payloadID, "got", payloadId)
305
		return nil, engine.UnknownPayload
306 307 308 309
	}
	bl, err := ea.endBlock()
	if err != nil {
		ea.log.Error("failed to finish block building", "err", err)
310
		return nil, engine.UnknownPayload
311
	}
312 313 314 315 316 317 318

	payload, err := eth.BlockAsPayload(bl, ea.config().CanyonTime)
	if err != nil {
		return nil, err
	}

	return &eth.ExecutionPayloadEnvelope{ExecutionPayload: payload, ParentBeaconBlockRoot: bl.BeaconRoot()}, nil
319 320
}

321
func (ea *L2EngineAPI) forkchoiceUpdated(ctx context.Context, state *eth.ForkchoiceState, attr *eth.PayloadAttributes) (*eth.ForkchoiceUpdatedResult, error) {
322 323 324 325 326 327 328 329
	ea.log.Trace("L2Engine API request received", "method", "ForkchoiceUpdated", "head", state.HeadBlockHash, "finalized", state.FinalizedBlockHash, "safe", state.SafeBlockHash)
	if state.HeadBlockHash == (common.Hash{}) {
		ea.log.Warn("Forkchoice requested update to zero hash")
		return STATUS_INVALID, nil
	}
	// Check whether we have the block yet in our database or not. If not, we'll
	// need to either trigger a sync, or to reject this forkchoice update for a
	// reason.
330
	block := ea.backend.GetBlockByHash(state.HeadBlockHash)
331 332 333 334 335 336
	if block == nil {
		// TODO: syncing not supported yet
		return STATUS_SYNCING, nil
	}
	// Block is known locally, just sanity check that the beacon client does not
	// attempt to push us back to before the merge.
337
	// Note: Differs from op-geth implementation as pre-merge blocks are never supported here
338
	if block.Difficulty().BitLen() > 0 && block.NumberU64() > 0 {
339
		return STATUS_INVALID, errors.New("pre-merge blocks not supported")
340
	}
341
	valid := func(id *engine.PayloadID) *eth.ForkchoiceUpdatedResult {
342 343 344 345 346
		return &eth.ForkchoiceUpdatedResult{
			PayloadStatus: eth.PayloadStatusV1{Status: eth.ExecutionValid, LatestValidHash: &state.HeadBlockHash},
			PayloadID:     id,
		}
	}
347
	if ea.backend.GetCanonicalHash(block.NumberU64()) != state.HeadBlockHash {
348
		// Block is not canonical, set head.
349
		if latestValid, err := ea.backend.SetCanonical(block); err != nil {
350 351
			return &eth.ForkchoiceUpdatedResult{PayloadStatus: eth.PayloadStatusV1{Status: eth.ExecutionInvalid, LatestValidHash: &latestValid}}, err
		}
352
	} else if ea.backend.CurrentHeader().Hash() == state.HeadBlockHash {
353 354 355
		// If the specified head matches with our local head, do nothing and keep
		// generating the payload. It's a special corner case that a few slots are
		// missing and we are requested to generate the payload in slot.
356
	} else if ea.backend.Config().Optimism == nil { // minor L2Engine API divergence: allow proposers to reorg their own chain
357 358 359 360 361 362 363
		panic("engine not configured as optimism engine")
	}

	// If the beacon client also advertised a finalized block, mark the local
	// chain final and completely in PoS mode.
	if state.FinalizedBlockHash != (common.Hash{}) {
		// If the finalized block is not in our canonical tree, somethings wrong
364
		finalHeader := ea.backend.GetHeaderByHash(state.FinalizedBlockHash)
365
		if finalHeader == nil {
366
			ea.log.Warn("Final block not available in database", "hash", state.FinalizedBlockHash)
367
			return STATUS_INVALID, engine.InvalidForkChoiceState.With(errors.New("final block not available in database"))
368
		} else if ea.backend.GetCanonicalHash(finalHeader.Number.Uint64()) != state.FinalizedBlockHash {
369
			ea.log.Warn("Final block not in canonical chain", "number", block.NumberU64(), "hash", state.HeadBlockHash)
370
			return STATUS_INVALID, engine.InvalidForkChoiceState.With(errors.New("final block not in canonical chain"))
371 372
		}
		// Set the finalized block
373
		ea.backend.SetFinalized(finalHeader)
374 375 376
	}
	// Check if the safe block hash is in our canonical tree, if not somethings wrong
	if state.SafeBlockHash != (common.Hash{}) {
377
		safeHeader := ea.backend.GetHeaderByHash(state.SafeBlockHash)
378
		if safeHeader == nil {
379
			ea.log.Warn("Safe block not available in database")
380
			return STATUS_INVALID, engine.InvalidForkChoiceState.With(errors.New("safe block not available in database"))
381
		}
382
		if ea.backend.GetCanonicalHash(safeHeader.Number.Uint64()) != state.SafeBlockHash {
383
			ea.log.Warn("Safe block not in canonical chain")
384
			return STATUS_INVALID, engine.InvalidForkChoiceState.With(errors.New("safe block not in canonical chain"))
385 386
		}
		// Set the safe block
387
		ea.backend.SetSafe(safeHeader)
388 389 390 391 392 393 394 395
	}
	// If payload generation was requested, create a new block to be potentially
	// sealed by the beacon client. The payload will be requested later, and we
	// might replace it arbitrarily many times in between.
	if attr != nil {
		err := ea.startBlock(state.HeadBlockHash, attr)
		if err != nil {
			ea.log.Error("Failed to start block building", "err", err, "noTxPool", attr.NoTxPool, "txs", len(attr.Transactions), "timestamp", attr.Timestamp)
396
			return STATUS_INVALID, engine.InvalidPayloadAttributes.With(err)
397 398 399 400 401 402 403
		}

		return valid(&ea.payloadID), nil
	}
	return valid(nil), nil
}

Danyal Prout's avatar
Danyal Prout committed
404 405 406 407 408
func toGethWithdrawals(payload *eth.ExecutionPayload) []*types.Withdrawal {
	if payload.Withdrawals == nil {
		return nil
	}

Danyal Prout's avatar
Danyal Prout committed
409
	result := make([]*types.Withdrawal, 0, len(*payload.Withdrawals))
Danyal Prout's avatar
Danyal Prout committed
410 411 412 413 414 415 416 417 418 419 420 421 422

	for _, w := range *payload.Withdrawals {
		result = append(result, &types.Withdrawal{
			Index:     w.Index,
			Validator: w.Validator,
			Address:   w.Address,
			Amount:    w.Amount,
		})
	}

	return result
}

423
func (ea *L2EngineAPI) newPayload(ctx context.Context, payload *eth.ExecutionPayload, hashes []common.Hash, root *common.Hash) (*eth.PayloadStatusV1, error) {
424 425 426 427 428
	ea.log.Trace("L2Engine API request received", "method", "ExecutePayload", "number", payload.BlockNumber, "hash", payload.BlockHash)
	txs := make([][]byte, len(payload.Transactions))
	for i, tx := range payload.Transactions {
		txs[i] = tx
	}
429
	block, err := engine.ExecutableDataToBlock(engine.ExecutableData{
430 431 432 433 434 435 436 437 438 439 440 441 442 443
		ParentHash:    payload.ParentHash,
		FeeRecipient:  payload.FeeRecipient,
		StateRoot:     common.Hash(payload.StateRoot),
		ReceiptsRoot:  common.Hash(payload.ReceiptsRoot),
		LogsBloom:     payload.LogsBloom[:],
		Random:        common.Hash(payload.PrevRandao),
		Number:        uint64(payload.BlockNumber),
		GasLimit:      uint64(payload.GasLimit),
		GasUsed:       uint64(payload.GasUsed),
		Timestamp:     uint64(payload.Timestamp),
		ExtraData:     payload.ExtraData,
		BaseFeePerGas: payload.BaseFeePerGas.ToBig(),
		BlockHash:     payload.BlockHash,
		Transactions:  txs,
Danyal Prout's avatar
Danyal Prout committed
444
		Withdrawals:   toGethWithdrawals(payload),
445 446 447 448
		ExcessBlobGas: (*uint64)(payload.ExcessBlobGas),
		BlobGasUsed:   (*uint64)(payload.BlobGasUsed),
	}, hashes, root)

449 450 451 452 453 454
	if err != nil {
		log.Debug("Invalid NewPayload params", "params", payload, "error", err)
		return &eth.PayloadStatusV1{Status: eth.ExecutionInvalidBlockHash}, nil
	}
	// If we already have the block locally, ignore the entire execution and just
	// return a fake success.
455
	if block := ea.backend.GetBlock(payload.BlockHash, uint64(payload.BlockNumber)); block != nil {
456 457 458 459 460 461 462
		ea.log.Warn("Ignoring already known beacon payload", "number", payload.BlockNumber, "hash", payload.BlockHash, "age", common.PrettyAge(time.Unix(int64(block.Time()), 0)))
		hash := block.Hash()
		return &eth.PayloadStatusV1{Status: eth.ExecutionValid, LatestValidHash: &hash}, nil
	}

	// TODO: skipping invalid ancestor check (i.e. not remembering previously failed blocks)

463
	parent := ea.backend.GetBlock(block.ParentHash(), block.NumberU64()-1)
464 465 466 467
	if parent == nil {
		// TODO: hack, saying we accepted if we don't know the parent block. Might want to return critical error if we can't actually sync.
		return &eth.PayloadStatusV1{Status: eth.ExecutionAccepted, LatestValidHash: nil}, nil
	}
468 469 470 471 472 473 474

	if block.Time() <= parent.Time() {
		log.Warn("Invalid timestamp", "parent", block.Time(), "block", block.Time())
		return ea.invalid(errors.New("invalid timestamp"), parent.Header()), nil
	}

	if !ea.backend.HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
475 476 477
		ea.log.Warn("State not available, ignoring new payload")
		return &eth.PayloadStatusV1{Status: eth.ExecutionAccepted}, nil
	}
478 479
	log.Trace("Inserting block without sethead", "hash", block.Hash(), "number", block.Number)
	if err := ea.backend.InsertBlockWithoutSetHead(block); err != nil {
480 481 482 483 484 485 486 487 488
		ea.log.Warn("NewPayloadV1: inserting block failed", "error", err)
		// TODO not remembering the payload as invalid
		return ea.invalid(err, parent.Header()), nil
	}
	hash := block.Hash()
	return &eth.PayloadStatusV1{Status: eth.ExecutionValid, LatestValidHash: &hash}, nil
}

func (ea *L2EngineAPI) invalid(err error, latestValid *types.Header) *eth.PayloadStatusV1 {
489
	currentHash := ea.backend.CurrentHeader().Hash()
490 491 492 493 494 495 496 497 498 499 500
	if latestValid != nil {
		// Set latest valid hash to 0x0 if parent is PoW block
		currentHash = common.Hash{}
		if latestValid.Difficulty.BitLen() == 0 {
			// Otherwise set latest valid hash to parent hash
			currentHash = latestValid.Hash()
		}
	}
	errorMsg := err.Error()
	return &eth.PayloadStatusV1{Status: eth.ExecutionInvalid, LatestValidHash: &currentHash, ValidationError: &errorMsg}
}