l2_engine_api_tests.go 16.1 KB
Newer Older
1 2 3 4
package test

import (
	"context"
5
	"math/big"
6 7
	"testing"

8 9 10 11 12 13 14
	"github.com/stretchr/testify/require"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/params"

15
	"github.com/ethereum-optimism/optimism/op-node/rollup"
16
	"github.com/ethereum-optimism/optimism/op-node/rollup/derive"
17
	"github.com/ethereum-optimism/optimism/op-program/client/l2/engineapi"
18
	"github.com/ethereum-optimism/optimism/op-service/eth"
19
	"github.com/ethereum-optimism/optimism/op-service/testlog"
20 21 22 23 24
)

var gasLimit = eth.Uint64Quantity(30_000_000)
var feeRecipient = common.Address{}

25
func RunEngineAPITests(t *testing.T, createBackend func(t *testing.T) engineapi.EngineBackend) {
26 27 28 29 30 31 32
	t.Run("CreateBlock", func(t *testing.T) {
		api := newTestHelper(t, createBackend)

		block := api.addBlock()
		api.assert.Equal(block.BlockHash, api.headHash(), "should create and import new block")
	})

33 34 35 36
	zero := uint64(0)
	rollupCfg := &rollup.Config{
		RegolithTime: &zero, // activate Regolith upgrade
	}
37 38
	t.Run("IncludeRequiredTransactions", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
39
		genesis := api.backend.CurrentHeader()
40

41
		txData, err := derive.L1InfoDeposit(rollupCfg, eth.SystemConfig{}, 1, eth.HeaderBlockInfo(genesis), 0)
42 43 44 45 46 47
		api.assert.NoError(err)
		tx := types.NewTx(txData)
		block := api.addBlock(tx)
		api.assert.Equal(block.BlockHash, api.headHash(), "should create and import new block")
		imported := api.backend.GetBlockByHash(block.BlockHash)
		api.assert.Len(imported.Transactions(), 1, "should include transaction")
48 49 50 51 52 53 54 55 56

		api.assert.NotEqual(genesis.Root, block.StateRoot)
		newState, err := api.backend.StateAt(common.Hash(block.StateRoot))
		require.NoError(t, err, "imported block state should be available")
		require.NotNil(t, newState)
	})

	t.Run("RejectCreatingBlockWithInvalidRequiredTransaction", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
57
		genesis := api.backend.CurrentHeader()
58

59
		txData, err := derive.L1InfoDeposit(rollupCfg, eth.SystemConfig{}, 1, eth.HeaderBlockInfo(genesis), 0)
60 61 62 63 64 65
		api.assert.NoError(err)
		txData.Gas = uint64(gasLimit + 1)
		tx := types.NewTx(txData)
		txRlp, err := tx.MarshalBinary()
		api.assert.NoError(err)

Danyal Prout's avatar
Danyal Prout committed
66 67
		nextBlockTime := eth.Uint64Quantity(genesis.Time + 1)

68
		var w *types.Withdrawals
Danyal Prout's avatar
Danyal Prout committed
69
		if api.backend.Config().IsCanyon(uint64(nextBlockTime)) {
70
			w = &types.Withdrawals{}
Danyal Prout's avatar
Danyal Prout committed
71 72 73
		}

		result, err := api.engine.ForkchoiceUpdatedV2(api.ctx, &eth.ForkchoiceState{
74 75 76 77
			HeadBlockHash:      genesis.Hash(),
			SafeBlockHash:      genesis.Hash(),
			FinalizedBlockHash: genesis.Hash(),
		}, &eth.PayloadAttributes{
Danyal Prout's avatar
Danyal Prout committed
78
			Timestamp:             nextBlockTime,
79 80 81 82 83
			PrevRandao:            eth.Bytes32(genesis.MixDigest),
			SuggestedFeeRecipient: feeRecipient,
			Transactions:          []eth.Data{txRlp},
			NoTxPool:              true,
			GasLimit:              &gasLimit,
Danyal Prout's avatar
Danyal Prout committed
84
			Withdrawals:           w,
85 86 87
		})
		api.assert.Error(err)
		api.assert.Equal(eth.ExecutionInvalid, result.PayloadStatus.Status)
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
	})

	t.Run("IgnoreUpdateHeadToOlderBlock", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
		genesisHash := api.headHash()
		api.addBlock()
		block := api.addBlock()
		api.assert.Equal(block.BlockHash, api.headHash(), "should have extended chain")

		api.forkChoiceUpdated(genesisHash, genesisHash, genesisHash)
		api.assert.Equal(block.BlockHash, api.headHash(), "should not have reset chain head")
	})

	t.Run("AllowBuildingOnOlderBlock", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
103
		genesis := api.backend.CurrentHeader()
104 105 106 107 108 109 110
		api.addBlock()
		block := api.addBlock()
		api.assert.Equal(block.BlockHash, api.headHash(), "should have extended chain")

		payloadID := api.startBlockBuilding(genesis, eth.Uint64Quantity(genesis.Time+3))
		api.assert.Equal(block.BlockHash, api.headHash(), "should not reset chain head when building starts")

111 112
		envelope := api.getPayload(payloadID)
		payload := envelope.ExecutionPayload
113 114
		api.assert.Equal(genesis.Hash(), payload.ParentHash, "should have old block as parent")

115
		api.newPayload(envelope)
116 117 118 119 120 121 122
		api.forkChoiceUpdated(payload.BlockHash, genesis.Hash(), genesis.Hash())
		api.assert.Equal(payload.BlockHash, api.headHash(), "should reorg to block built on old parent")
	})

	t.Run("RejectInvalidBlockHash", func(t *testing.T) {
		api := newTestHelper(t, createBackend)

123
		var w *types.Withdrawals
Danyal Prout's avatar
Danyal Prout committed
124
		if api.backend.Config().IsCanyon(uint64(0)) {
125
			w = &types.Withdrawals{}
Danyal Prout's avatar
Danyal Prout committed
126 127
		}

128
		// Invalid because BlockHash won't be correct (among many other reasons)
Danyal Prout's avatar
Danyal Prout committed
129 130 131 132
		block := &eth.ExecutionPayload{
			Withdrawals: w,
		}
		r, err := api.engine.NewPayloadV2(api.ctx, block)
133 134 135 136 137 138
		api.assert.NoError(err)
		api.assert.Equal(eth.ExecutionInvalidBlockHash, r.Status)
	})

	t.Run("RejectBlockWithInvalidStateTransition", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
139
		genesis := api.backend.CurrentHeader()
140 141 142

		// Build a valid block
		payloadID := api.startBlockBuilding(genesis, eth.Uint64Quantity(genesis.Time+2))
143
		envelope := api.getPayload(payloadID)
144 145

		// But then make it invalid by changing the state root
146
		envelope.ExecutionPayload.StateRoot = eth.Bytes32(genesis.TxHash)
147
		updateBlockHash(envelope)
148

149
		r, err := api.callNewPayload(envelope)
150 151 152 153 154 155
		api.assert.NoError(err)
		api.assert.Equal(eth.ExecutionInvalid, r.Status)
	})

	t.Run("RejectBlockWithSameTimeAsParent", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
156
		genesis := api.backend.CurrentHeader()
157

158 159
		// Start with a valid time
		payloadID := api.startBlockBuilding(genesis, eth.Uint64Quantity(genesis.Time+1))
160
		envelope := api.getPayload(payloadID)
161

162
		// Then make it invalid to check NewPayload rejects it
163
		envelope.ExecutionPayload.Timestamp = eth.Uint64Quantity(genesis.Time)
164
		updateBlockHash(envelope)
165

166
		r, err := api.callNewPayload(envelope)
167 168 169 170 171 172
		api.assert.NoError(err)
		api.assert.Equal(eth.ExecutionInvalid, r.Status)
	})

	t.Run("RejectBlockWithTimeBeforeParent", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
173
		genesis := api.backend.CurrentHeader()
174

175 176
		// Start with a valid time
		payloadID := api.startBlockBuilding(genesis, eth.Uint64Quantity(genesis.Time+1))
177
		envelope := api.getPayload(payloadID)
178

179
		// Then make it invalid to check NewPayload rejects it
180
		envelope.ExecutionPayload.Timestamp = eth.Uint64Quantity(genesis.Time - 1)
181
		updateBlockHash(envelope)
182

183
		r, err := api.callNewPayload(envelope)
184 185 186 187
		api.assert.NoError(err)
		api.assert.Equal(eth.ExecutionInvalid, r.Status)
	})

188 189
	t.Run("RejectCreateBlockWithSameTimeAsParent", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
190
		genesis := api.backend.CurrentHeader()
191

Danyal Prout's avatar
Danyal Prout committed
192
		result, err := api.engine.ForkchoiceUpdatedV2(api.ctx, &eth.ForkchoiceState{
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
			HeadBlockHash:      genesis.Hash(),
			SafeBlockHash:      genesis.Hash(),
			FinalizedBlockHash: genesis.Hash(),
		}, &eth.PayloadAttributes{
			Timestamp:             eth.Uint64Quantity(genesis.Time),
			PrevRandao:            eth.Bytes32(genesis.MixDigest),
			SuggestedFeeRecipient: feeRecipient,
			Transactions:          nil,
			NoTxPool:              true,
			GasLimit:              &gasLimit,
		})
		api.assert.Error(err)
		api.assert.Equal(eth.ExecutionInvalid, result.PayloadStatus.Status)
	})

	t.Run("RejectCreateBlockWithTimeBeforeParent", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
210
		genesis := api.backend.CurrentHeader()
211

Danyal Prout's avatar
Danyal Prout committed
212
		result, err := api.engine.ForkchoiceUpdatedV2(api.ctx, &eth.ForkchoiceState{
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
			HeadBlockHash:      genesis.Hash(),
			SafeBlockHash:      genesis.Hash(),
			FinalizedBlockHash: genesis.Hash(),
		}, &eth.PayloadAttributes{
			Timestamp:             eth.Uint64Quantity(genesis.Time - 1),
			PrevRandao:            eth.Bytes32(genesis.MixDigest),
			SuggestedFeeRecipient: feeRecipient,
			Transactions:          nil,
			NoTxPool:              true,
			GasLimit:              &gasLimit,
		})
		api.assert.Error(err)
		api.assert.Equal(eth.ExecutionInvalid, result.PayloadStatus.Status)
	})

	t.Run("RejectCreateBlockWithGasLimitAboveMax", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
230
		genesis := api.backend.CurrentHeader()
231 232 233

		gasLimit := eth.Uint64Quantity(params.MaxGasLimit + 1)

Danyal Prout's avatar
Danyal Prout committed
234
		result, err := api.engine.ForkchoiceUpdatedV2(api.ctx, &eth.ForkchoiceState{
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
			HeadBlockHash:      genesis.Hash(),
			SafeBlockHash:      genesis.Hash(),
			FinalizedBlockHash: genesis.Hash(),
		}, &eth.PayloadAttributes{
			Timestamp:             eth.Uint64Quantity(genesis.Time + 1),
			PrevRandao:            eth.Bytes32(genesis.MixDigest),
			SuggestedFeeRecipient: feeRecipient,
			Transactions:          nil,
			NoTxPool:              true,
			GasLimit:              &gasLimit,
		})
		api.assert.Error(err)
		api.assert.Equal(eth.ExecutionInvalid, result.PayloadStatus.Status)
	})

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
	t.Run("UpdateSafeAndFinalizedHead", func(t *testing.T) {
		api := newTestHelper(t, createBackend)

		finalized := api.addBlock()
		safe := api.addBlock()
		head := api.addBlock()

		api.forkChoiceUpdated(head.BlockHash, safe.BlockHash, finalized.BlockHash)
		api.assert.Equal(head.BlockHash, api.headHash(), "should update head block")
		api.assert.Equal(safe.BlockHash, api.safeHash(), "should update safe block")
		api.assert.Equal(finalized.BlockHash, api.finalHash(), "should update finalized block")
	})

	t.Run("RejectSafeHeadWhenNotAncestor", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
265
		genesis := api.backend.CurrentHeader()
266 267 268 269 270 271 272

		api.addBlock()
		chainA2 := api.addBlock()
		chainA3 := api.addBlock()

		chainB1 := api.addBlockWithParent(genesis, eth.Uint64Quantity(genesis.Time+3))

Danyal Prout's avatar
Danyal Prout committed
273
		result, err := api.engine.ForkchoiceUpdatedV2(api.ctx, &eth.ForkchoiceState{
274 275 276 277 278 279 280 281 282 283 284
			HeadBlockHash:      chainA3.BlockHash,
			SafeBlockHash:      chainB1.BlockHash,
			FinalizedBlockHash: chainA2.BlockHash,
		}, nil)
		api.assert.ErrorContains(err, "Invalid forkchoice state", "should return error from forkChoiceUpdated")
		api.assert.Equal(eth.ExecutionInvalid, result.PayloadStatus.Status, "forkChoiceUpdated should return invalid")
		api.assert.Nil(result.PayloadID, "should not provide payload ID when invalid")
	})

	t.Run("RejectFinalizedHeadWhenNotAncestor", func(t *testing.T) {
		api := newTestHelper(t, createBackend)
285
		genesis := api.backend.CurrentHeader()
286 287 288 289 290 291 292

		api.addBlock()
		chainA2 := api.addBlock()
		chainA3 := api.addBlock()

		chainB1 := api.addBlockWithParent(genesis, eth.Uint64Quantity(genesis.Time+3))

Danyal Prout's avatar
Danyal Prout committed
293
		result, err := api.engine.ForkchoiceUpdatedV2(api.ctx, &eth.ForkchoiceState{
294 295 296 297 298 299 300 301 302 303 304
			HeadBlockHash:      chainA3.BlockHash,
			SafeBlockHash:      chainA2.BlockHash,
			FinalizedBlockHash: chainB1.BlockHash,
		}, nil)
		api.assert.ErrorContains(err, "Invalid forkchoice state", "should return error from forkChoiceUpdated")
		api.assert.Equal(eth.ExecutionInvalid, result.PayloadStatus.Status, "forkChoiceUpdated should return invalid")
		api.assert.Nil(result.PayloadID, "should not provide payload ID when invalid")
	})
}

// Updates the block hash to the expected value based on the other fields in the payload
305
func updateBlockHash(envelope *eth.ExecutionPayloadEnvelope) {
306
	// And fix up the block hash
307 308
	newHash, _ := envelope.CheckBlockHash()
	envelope.ExecutionPayload.BlockHash = newHash
309 310 311 312 313 314 315 316 317 318
}

type testHelper struct {
	t       *testing.T
	ctx     context.Context
	engine  *engineapi.L2EngineAPI
	backend engineapi.EngineBackend
	assert  *require.Assertions
}

319
func newTestHelper(t *testing.T, createBackend func(t *testing.T) engineapi.EngineBackend) *testHelper {
320
	logger := testlog.Logger(t, log.LevelDebug)
321
	ctx := context.Background()
322
	backend := createBackend(t)
323
	api := engineapi.NewL2EngineAPI(logger, backend, nil)
324 325 326 327 328 329 330 331 332 333 334
	test := &testHelper{
		t:       t,
		ctx:     ctx,
		engine:  api,
		backend: backend,
		assert:  require.New(t),
	}
	return test
}

func (h *testHelper) headHash() common.Hash {
335
	return h.backend.CurrentHeader().Hash()
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
}

func (h *testHelper) safeHash() common.Hash {
	return h.backend.CurrentSafeBlock().Hash()
}

func (h *testHelper) finalHash() common.Hash {
	return h.backend.CurrentFinalBlock().Hash()
}

func (h *testHelper) Log(args ...any) {
	h.t.Log(args...)
}

func (h *testHelper) addBlock(txs ...*types.Transaction) *eth.ExecutionPayload {
351
	head := h.backend.CurrentHeader()
352 353 354 355
	return h.addBlockWithParent(head, eth.Uint64Quantity(head.Time+2), txs...)
}

func (h *testHelper) addBlockWithParent(head *types.Header, timestamp eth.Uint64Quantity, txs ...*types.Transaction) *eth.ExecutionPayload {
356
	prevHead := h.backend.CurrentHeader()
357 358
	id := h.startBlockBuilding(head, timestamp, txs...)

359 360 361
	envelope := h.getPayload(id)
	block := envelope.ExecutionPayload

362 363 364 365
	h.assert.Equal(timestamp, block.Timestamp, "should create block with correct timestamp")
	h.assert.Equal(head.Hash(), block.ParentHash, "should have correct parent")
	h.assert.Len(block.Transactions, len(txs))

366
	h.newPayload(envelope)
367 368

	// Should not have changed the chain head yet
369
	h.assert.Equal(prevHead, h.backend.CurrentHeader())
370 371

	h.forkChoiceUpdated(block.BlockHash, head.Hash(), head.Hash())
372
	h.assert.Equal(block.BlockHash, h.backend.CurrentHeader().Hash())
373 374 375 376 377
	return block
}

func (h *testHelper) forkChoiceUpdated(head common.Hash, safe common.Hash, finalized common.Hash) {
	h.Log("forkChoiceUpdated", "head", head, "safe", safe, "finalized", finalized)
Danyal Prout's avatar
Danyal Prout committed
378
	result, err := h.engine.ForkchoiceUpdatedV2(h.ctx, &eth.ForkchoiceState{
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
		HeadBlockHash:      head,
		SafeBlockHash:      safe,
		FinalizedBlockHash: finalized,
	}, nil)
	h.assert.NoError(err)
	h.assert.Equal(eth.ExecutionValid, result.PayloadStatus.Status, "forkChoiceUpdated should return valid")
	h.assert.Nil(result.PayloadStatus.ValidationError, "should not have validation error when valid")
	h.assert.Nil(result.PayloadID, "should not provide payload ID when block building not requested")
}

func (h *testHelper) startBlockBuilding(head *types.Header, newBlockTimestamp eth.Uint64Quantity, txs ...*types.Transaction) *eth.PayloadID {
	h.Log("Start block building", "head", head.Hash(), "timestamp", newBlockTimestamp)
	var txData []eth.Data
	for _, tx := range txs {
		rlp, err := tx.MarshalBinary()
		h.assert.NoError(err, "Failed to marshall tx %v", tx)
		txData = append(txData, rlp)
	}
Danyal Prout's avatar
Danyal Prout committed
397

398
	attr := &eth.PayloadAttributes{
399 400 401 402 403 404
		Timestamp:             newBlockTimestamp,
		PrevRandao:            eth.Bytes32(head.MixDigest),
		SuggestedFeeRecipient: feeRecipient,
		Transactions:          txData,
		NoTxPool:              true,
		GasLimit:              &gasLimit,
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
	}
	n := new(big.Int).Add(head.Number, big.NewInt(1))
	if h.backend.Config().IsShanghai(n, uint64(newBlockTimestamp)) {
		attr.Withdrawals = &types.Withdrawals{}
	}
	if h.backend.Config().IsCancun(n, uint64(newBlockTimestamp)) {
		attr.ParentBeaconBlockRoot = &common.Hash{}
	}
	fcState := &eth.ForkchoiceState{
		HeadBlockHash:      head.Hash(),
		SafeBlockHash:      head.Hash(),
		FinalizedBlockHash: head.Hash(),
	}
	var result *eth.ForkchoiceUpdatedResult
	var err error
	if h.backend.Config().IsCancun(n, uint64(newBlockTimestamp)) {
		result, err = h.engine.ForkchoiceUpdatedV3(h.ctx, fcState, attr)
	} else if h.backend.Config().IsShanghai(n, uint64(newBlockTimestamp)) {
		result, err = h.engine.ForkchoiceUpdatedV2(h.ctx, fcState, attr)
	} else {
		result, err = h.engine.ForkchoiceUpdatedV1(h.ctx, fcState, attr)
	}
427 428 429 430 431 432 433
	h.assert.NoError(err)
	h.assert.Equal(eth.ExecutionValid, result.PayloadStatus.Status)
	id := result.PayloadID
	h.assert.NotNil(id)
	return id
}

434
func (h *testHelper) getPayload(id *eth.PayloadID) *eth.ExecutionPayloadEnvelope {
435
	h.Log("getPayload", "id", id)
436
	envelope, err := h.engine.GetPayloadV2(h.ctx, *id) // calls the same underlying function as V1 and V3
437
	h.assert.NoError(err)
Danyal Prout's avatar
Danyal Prout committed
438 439
	h.assert.NotNil(envelope)
	h.assert.NotNil(envelope.ExecutionPayload)
440
	return envelope
441 442
}

443 444 445 446 447 448 449 450 451 452 453 454
func (h *testHelper) callNewPayload(envelope *eth.ExecutionPayloadEnvelope) (*eth.PayloadStatusV1, error) {
	n := new(big.Int).SetUint64(uint64(envelope.ExecutionPayload.BlockNumber))
	if h.backend.Config().IsCancun(n, uint64(envelope.ExecutionPayload.Timestamp)) {
		return h.engine.NewPayloadV3(h.ctx, envelope.ExecutionPayload, []common.Hash{}, envelope.ParentBeaconBlockRoot)
	} else {
		return h.engine.NewPayloadV2(h.ctx, envelope.ExecutionPayload)
	}
}

func (h *testHelper) newPayload(envelope *eth.ExecutionPayloadEnvelope) {
	h.Log("newPayload", "hash", envelope.ExecutionPayload.BlockHash)
	r, err := h.callNewPayload(envelope)
455 456 457 458
	h.assert.NoError(err)
	h.assert.Equal(eth.ExecutionValid, r.Status)
	h.assert.Nil(r.ValidationError)
}