batch_queue_test.go 35.3 KB
Newer Older
1 2 3 4
package derive

import (
	"context"
5
	"encoding/binary"
6
	"errors"
7
	"io"
8
	"math/big"
9 10 11
	"math/rand"
	"testing"

12
	"github.com/ethereum/go-ethereum/common"
13
	"github.com/ethereum/go-ethereum/common/hexutil"
14
	"github.com/ethereum/go-ethereum/core/types"
15
	"github.com/ethereum/go-ethereum/log"
16
	"github.com/stretchr/testify/require"
17 18

	"github.com/ethereum-optimism/optimism/op-node/rollup"
19
	"github.com/ethereum-optimism/optimism/op-service/eth"
20
	"github.com/ethereum-optimism/optimism/op-service/testlog"
Sabnock01's avatar
Sabnock01 committed
21
	"github.com/ethereum-optimism/optimism/op-service/testutils"
22 23
)

24 25
type fakeBatchQueueInput struct {
	i       int
26
	batches []Batch
27 28
	errors  []error
	origin  eth.L1BlockRef
29 30
}

31 32
func (f *fakeBatchQueueInput) Origin() eth.L1BlockRef {
	return f.origin
33 34
}

35 36 37 38 39 40
func (f *fakeBatchQueueInput) FlushChannel() {
	f.batches = nil
	f.errors = nil
	f.i = 0
}

41
func (f *fakeBatchQueueInput) NextBatch(ctx context.Context) (Batch, error) {
42 43 44 45 46 47 48
	if f.i >= len(f.batches) {
		return nil, io.EOF
	}
	b := f.batches[f.i]
	e := f.errors[f.i]
	f.i += 1
	return b, e
49 50
}

51 52 53 54 55 56
func mockHash(time uint64, layer uint8) common.Hash {
	hash := common.Hash{31: layer} // indicate L1 or L2
	binary.LittleEndian.PutUint64(hash[:], time)
	return hash
}

57
func b(chainId *big.Int, timestamp uint64, epoch eth.L1BlockRef) *SingularBatch {
58
	rng := rand.New(rand.NewSource(int64(timestamp)))
59 60 61 62
	signer := types.NewLondonSigner(chainId)
	tx := testutils.RandomTx(rng, new(big.Int).SetUint64(rng.Uint64()), signer)
	txData, _ := tx.MarshalBinary()
	return &SingularBatch{
63
		ParentHash:   mockHash(timestamp-2, 2),
64 65 66
		Timestamp:    timestamp,
		EpochNum:     rollup.Epoch(epoch.Number),
		EpochHash:    epoch.Hash,
67 68 69 70 71 72 73 74
		Transactions: []hexutil.Bytes{txData},
	}
}

func buildSpanBatches(t *testing.T, parent *eth.L2BlockRef, singularBatches []*SingularBatch, blockCounts []int, chainId *big.Int) []Batch {
	var spanBatches []Batch
	idx := 0
	for _, count := range blockCounts {
75
		span := initializedSpanBatch(singularBatches[idx:idx+count], uint64(0), chainId)
76 77 78 79 80 81
		spanBatches = append(spanBatches, span)
		idx += count
	}
	return spanBatches
}

82
func getDeltaTime(batchType int) *uint64 {
83 84 85 86 87 88 89 90 91 92 93 94
	minTs := uint64(0)
	if batchType == SpanBatchType {
		return &minTs
	}
	return nil
}

func l1InfoDepositTx(t *testing.T, l1BlockNum uint64) hexutil.Bytes {
	l1Info := L1BlockInfo{
		Number:  l1BlockNum,
		BaseFee: big.NewInt(0),
	}
95
	infoData, err := l1Info.marshalBinaryBedrock()
96 97 98 99 100 101 102 103 104
	require.NoError(t, err)
	depositTx := &types.DepositTx{
		Data: infoData,
	}
	txData, err := types.NewTx(depositTx).MarshalBinary()
	require.NoError(t, err)
	return txData
}

105
func singularBatchToPayload(t *testing.T, batch *SingularBatch, blockNumber uint64) eth.ExecutionPayloadEnvelope {
106 107
	txs := []hexutil.Bytes{l1InfoDepositTx(t, uint64(batch.EpochNum))}
	txs = append(txs, batch.Transactions...)
108 109 110 111 112 113 114 115
	return eth.ExecutionPayloadEnvelope{
		ExecutionPayload: &eth.ExecutionPayload{
			BlockHash:    mockHash(batch.Timestamp, 2),
			ParentHash:   batch.ParentHash,
			BlockNumber:  hexutil.Uint64(blockNumber),
			Timestamp:    hexutil.Uint64(batch.Timestamp),
			Transactions: txs,
		},
116 117 118 119 120 121 122 123 124 125 126
	}
}

func singularBatchToBlockRef(t *testing.T, batch *SingularBatch, blockNumber uint64) eth.L2BlockRef {
	return eth.L2BlockRef{
		Hash:       mockHash(batch.Timestamp, 2),
		Number:     blockNumber,
		ParentHash: batch.ParentHash,
		Time:       batch.Timestamp,
		L1Origin:   eth.BlockID{Hash: batch.EpochHash, Number: uint64(batch.EpochNum)},
	}
127 128 129 130
}

func L1Chain(l1Times []uint64) []eth.L1BlockRef {
	var out []eth.L1BlockRef
131
	var parentHash common.Hash
132
	for i, time := range l1Times {
133
		hash := mockHash(time, 1)
134 135 136 137 138 139 140 141 142 143 144
		out = append(out, eth.L1BlockRef{
			Hash:       hash,
			Number:     uint64(i),
			ParentHash: parentHash,
			Time:       time,
		})
		parentHash = hash
	}
	return out
}

145 146 147 148 149
func TestBatchQueue(t *testing.T) {
	tests := []struct {
		name string
		f    func(t *testing.T, batchType int)
	}{
150 151
		{"Missing", testBatchQueue_Missing},
		{"Shuffle", testBatchQueue_Shuffle},
152 153 154 155 156 157
	}
	for _, test := range tests {
		test := test
		t.Run(test.name+"_SingularBatch", func(t *testing.T) {
			test.f(t, SingularBatchType)
		})
158 159 160
		t.Run(test.name+"_SpanBatch", func(t *testing.T) {
			test.f(t, SpanBatchType)
		})
161
	}
162
}
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
type testableBatchStageFactory func(log.Logger, *rollup.Config, NextBatchProvider, SafeBlockFetcher) testableBatchStage

type testableBatchStage interface {
	SingularBatchProvider
	base() *baseBatchStage
}

func TestBatchStages(t *testing.T) {
	newBatchQueue := func(log log.Logger, cfg *rollup.Config, prev NextBatchProvider, l2 SafeBlockFetcher) testableBatchStage {
		return NewBatchQueue(log, cfg, prev, l2)
	}
	newBatchStage := func(log log.Logger, cfg *rollup.Config, prev NextBatchProvider, l2 SafeBlockFetcher) testableBatchStage {
		return NewBatchStage(log, cfg, prev, l2)
	}

	tests := []struct {
		name string
		f    func(*testing.T, int, testableBatchStageFactory)
	}{
		{"NewOrigin", testBatchStage_NewOrigin},
		{"Eager", testBatchStage_Eager},
		{"InvalidInternalAdvance", testBatchStage_InvalidInternalAdvance},
		{"AdvancedEpoch", testBatchStage_AdvancedEpoch},
		{"ResetOneBlockBeforeOrigin", testBatchStage_ResetOneBlockBeforeOrigin},
	}
189 190
	for _, test := range tests {
		test := test
191 192 193 194 195 196 197 198 199 200 201
		t.Run("BatchQueue_"+test.name+"_SingularBatch", func(t *testing.T) {
			test.f(t, SingularBatchType, newBatchQueue)
		})
		t.Run("BatchQueue_"+test.name+"_SpanBatch", func(t *testing.T) {
			test.f(t, SpanBatchType, newBatchQueue)
		})
		t.Run("BatchStage_"+test.name+"_SingularBatch", func(t *testing.T) {
			test.f(t, SingularBatchType, newBatchStage)
		})
		t.Run("BatchStage_"+test.name+"_SpanBatch", func(t *testing.T) {
			test.f(t, SpanBatchType, newBatchStage)
202 203 204 205
		})
	}
}

206
// testBatchStage_NewOrigin tests that the batch queue properly saves the new origin
207 208
// when the safehead's origin is ahead of the pipeline's origin (as is after a reset).
// This issue was fixed in https://github.com/ethereum-optimism/optimism/pull/3694
209
func testBatchStage_NewOrigin(t *testing.T, batchType int, newBatchStage testableBatchStageFactory) {
210
	log := testlog.Logger(t, log.LevelCrit)
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
	l1 := L1Chain([]uint64{10, 15, 20, 25})
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(10, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           20,
		L1Origin:       l1[2].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     2,
227
		DeltaTime:         getDeltaTime(batchType),
228 229 230
	}

	input := &fakeBatchQueueInput{
231
		batches: []Batch{nil},
232 233 234 235
		errors:  []error{io.EOF},
		origin:  l1[0],
	}

236 237
	bq := newBatchStage(log, cfg, input, nil)
	bqb := bq.base()
238
	_ = bq.Reset(context.Background(), l1[0], eth.SystemConfig{})
239
	require.Equal(t, []eth.L1BlockRef{l1[0]}, bqb.l1Blocks)
240 241 242

	// Prev Origin: 0; Safehead Origin: 2; Internal Origin: 0
	// Should return no data but keep the same origin
243
	data, _, err := bq.NextBatch(context.Background(), safeHead)
244 245
	require.Nil(t, data)
	require.Equal(t, io.EOF, err)
246 247
	require.Equal(t, []eth.L1BlockRef{l1[0]}, bqb.l1Blocks)
	require.Equal(t, l1[0], bqb.origin)
248 249 250 251

	// Prev Origin: 1; Safehead Origin: 2; Internal Origin: 0
	// Should wipe l1blocks + advance internal origin
	input.origin = l1[1]
252
	data, _, err = bq.NextBatch(context.Background(), safeHead)
253 254
	require.Nil(t, data)
	require.Equal(t, io.EOF, err)
255 256
	require.Empty(t, bqb.l1Blocks)
	require.Equal(t, l1[1], bqb.origin)
257 258 259 260

	// Prev Origin: 2; Safehead Origin: 2; Internal Origin: 1
	// Should add to l1Blocks + advance internal origin
	input.origin = l1[2]
261
	data, _, err = bq.NextBatch(context.Background(), safeHead)
262 263
	require.Nil(t, data)
	require.Equal(t, io.EOF, err)
264 265
	require.Equal(t, []eth.L1BlockRef{l1[2]}, bqb.l1Blocks)
	require.Equal(t, l1[2], bqb.origin)
266 267
}

268
// testBatchStage_ResetOneBlockBeforeOrigin tests that the batch queue properly
269 270
// prunes the l1Block recorded as part of a reset when the starting origin
// is exactly one block prior to the safe head origin.
271
func testBatchStage_ResetOneBlockBeforeOrigin(t *testing.T, batchType int, newBatchStage testableBatchStageFactory) {
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
	log := testlog.Logger(t, log.LevelTrace)
	l1 := L1Chain([]uint64{10, 15, 20, 25})
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(10, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           20,
		L1Origin:       l1[1].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     2,
		DeltaTime:         getDeltaTime(batchType),
	}

	input := &fakeBatchQueueInput{
		batches: []Batch{nil},
		errors:  []error{io.EOF},
		origin:  l1[0],
	}

298 299
	bq := newBatchStage(log, cfg, input, nil)
	bqb := bq.base()
300
	_ = bq.Reset(context.Background(), l1[0], eth.SystemConfig{})
301
	require.Equal(t, []eth.L1BlockRef{l1[0]}, bqb.l1Blocks)
302 303 304 305 306 307

	// Prev Origin: 0; Safehead Origin: 1; Internal Origin: 0
	// Should return no data but keep the same origin
	data, _, err := bq.NextBatch(context.Background(), safeHead)
	require.Nil(t, data)
	require.Equal(t, io.EOF, err)
308 309
	require.Equal(t, []eth.L1BlockRef{l1[0]}, bqb.l1Blocks)
	require.Equal(t, l1[0], bqb.origin)
310 311 312 313 314 315 316

	// Prev Origin: 1; Safehead Origin: 1; Internal Origin: 0
	// Should record new l1 origin in l1blocks, prune block 0 and advance internal origin
	input.origin = l1[1]
	data, _, err = bq.NextBatch(context.Background(), safeHead)
	require.Nil(t, data)
	require.Equalf(t, io.EOF, err, "expected io.EOF but got %v", err)
317 318
	require.Equal(t, []eth.L1BlockRef{l1[1]}, bqb.l1Blocks)
	require.Equal(t, l1[1], bqb.origin)
319 320 321 322 323 324 325

	// Prev Origin: 2; Safehead Origin: 1; Internal Origin: 1
	// Should add to l1Blocks + advance internal origin
	input.origin = l1[2]
	data, _, err = bq.NextBatch(context.Background(), safeHead)
	require.Nil(t, data)
	require.Equal(t, io.EOF, err)
326 327
	require.Equal(t, []eth.L1BlockRef{l1[1], l1[2]}, bqb.l1Blocks)
	require.Equal(t, l1[2], bqb.origin)
328 329
}

330
// testBatchStage_Eager adds a bunch of contiguous batches and asserts that
331
// enough calls to `NextBatch` return all of those batches.
332
func testBatchStage_Eager(t *testing.T, batchType int, newBatchStage testableBatchStageFactory) {
333
	log := testlog.Logger(t, log.LevelCrit)
334
	l1 := L1Chain([]uint64{10, 20, 30})
335
	chainId := big.NewInt(1234)
336 337 338 339 340 341 342
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(10, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           10,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
343 344 345 346 347 348 349 350
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     30,
351
		DeltaTime:         getDeltaTime(batchType),
352
		L2ChainID:         chainId,
353 354
	}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
	// expected output of BatchQueue.NextBatch()
	expectedOutputBatches := []*SingularBatch{
		b(cfg.L2ChainID, 12, l1[0]),
		b(cfg.L2ChainID, 14, l1[0]),
		b(cfg.L2ChainID, 16, l1[0]),
		b(cfg.L2ChainID, 18, l1[0]),
		b(cfg.L2ChainID, 20, l1[0]),
		b(cfg.L2ChainID, 22, l1[0]),
		nil,
	}
	// expected error of BatchQueue.NextBatch()
	expectedOutputErrors := []error{nil, nil, nil, nil, nil, nil, io.EOF}
	// errors will be returned by fakeBatchQueueInput.NextBatch()
	inputErrors := expectedOutputErrors
	// batches will be returned by fakeBatchQueueInput
	var inputBatches []Batch
	if batchType == SpanBatchType {
		spanBlockCounts := []int{1, 2, 3}
		inputErrors = []error{nil, nil, nil, io.EOF}
		inputBatches = buildSpanBatches(t, &safeHead, expectedOutputBatches, spanBlockCounts, chainId)
		inputBatches = append(inputBatches, nil)
	} else {
		for _, singularBatch := range expectedOutputBatches {
			inputBatches = append(inputBatches, singularBatch)
		}
	}
381

382
	input := &fakeBatchQueueInput{
383 384
		batches: inputBatches,
		errors:  inputErrors,
385
		origin:  l1[0],
386 387
	}

388
	bq := newBatchStage(log, cfg, input, nil)
389
	_ = bq.Reset(context.Background(), l1[0], eth.SystemConfig{})
390 391 392
	// Advance the origin
	input.origin = l1[1]

393
	for i := 0; i < len(expectedOutputBatches); i++ {
394
		b, _, e := bq.NextBatch(context.Background(), safeHead)
395 396 397 398 399
		require.ErrorIs(t, e, expectedOutputErrors[i])
		if b == nil {
			require.Nil(t, expectedOutputBatches[i])
		} else {
			require.Equal(t, expectedOutputBatches[i], b)
400
			safeHead.Number += 1
401
			safeHead.Time += cfg.BlockTime
402 403 404
			safeHead.Hash = mockHash(b.Timestamp, 2)
			safeHead.L1Origin = b.Epoch()
		}
405 406 407
	}
}

408
// testBatchStage_InvalidInternalAdvance asserts that we do not miss an epoch when generating batches.
409
// This is a regression test for CLI-3378.
410
func testBatchStage_InvalidInternalAdvance(t *testing.T, batchType int, newBatchStage testableBatchStageFactory) {
411
	log := testlog.Logger(t, log.LevelTrace)
412
	l1 := L1Chain([]uint64{5, 10, 15, 20, 25, 30})
413
	chainId := big.NewInt(1234)
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(10, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           10,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     2,
429
		DeltaTime:         getDeltaTime(batchType),
430
		L2ChainID:         chainId,
431 432
	}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	// expected output of BatchQueue.NextBatch()
	expectedOutputBatches := []*SingularBatch{
		b(cfg.L2ChainID, 12, l1[0]),
		b(cfg.L2ChainID, 14, l1[0]),
		b(cfg.L2ChainID, 16, l1[0]),
		b(cfg.L2ChainID, 18, l1[0]),
		b(cfg.L2ChainID, 20, l1[0]),
		b(cfg.L2ChainID, 22, l1[0]),
		nil,
	}
	// expected error of BatchQueue.NextBatch()
	expectedOutputErrors := []error{nil, nil, nil, nil, nil, nil, io.EOF}
	// errors will be returned by fakeBatchQueueInput.NextBatch()
	inputErrors := expectedOutputErrors
	// batches will be returned by fakeBatchQueueInput
	var inputBatches []Batch
	if batchType == SpanBatchType {
		spanBlockCounts := []int{1, 2, 3}
		inputErrors = []error{nil, nil, nil, io.EOF}
		inputBatches = buildSpanBatches(t, &safeHead, expectedOutputBatches, spanBlockCounts, chainId)
		inputBatches = append(inputBatches, nil)
	} else {
		for _, singularBatch := range expectedOutputBatches {
			inputBatches = append(inputBatches, singularBatch)
		}
	}
459

460
	// prepend a nil batch so we can load the safe head's epoch
461
	input := &fakeBatchQueueInput{
462 463
		batches: append([]Batch{nil}, inputBatches...),
		errors:  append([]error{io.EOF}, inputErrors...),
464 465 466
		origin:  l1[0],
	}

467
	bq := newBatchStage(log, cfg, input, nil)
468 469
	_ = bq.Reset(context.Background(), l1[0], eth.SystemConfig{})

470 471 472 473 474 475 476
	// first load base epoch
	b, _, e := bq.NextBatch(context.Background(), safeHead)
	require.ErrorIs(t, e, io.EOF)
	require.Nil(t, b)
	// then advance to origin 1 with batches
	input.origin = l1[1]

477
	// Load continuous batches for epoch 0
478
	for i := 0; i < len(expectedOutputBatches); i++ {
479
		t.Logf("Iteration %d", i)
480
		b, _, e := bq.NextBatch(context.Background(), safeHead)
481 482 483 484 485
		require.ErrorIs(t, e, expectedOutputErrors[i])
		if b == nil {
			require.Nil(t, expectedOutputBatches[i])
		} else {
			require.Equal(t, expectedOutputBatches[i], b)
486 487 488 489 490 491 492
			safeHead.Number += 1
			safeHead.Time += 2
			safeHead.Hash = mockHash(b.Timestamp, 2)
			safeHead.L1Origin = b.Epoch()
		}
	}

493
	// Advance to origin 2. No forced batches yet.
494
	input.origin = l1[2]
495
	b, _, e = bq.NextBatch(context.Background(), safeHead)
496 497 498 499 500
	require.ErrorIs(t, e, io.EOF)
	require.Nil(t, b)

	// Advance to origin 3. Should generate one empty batch.
	input.origin = l1[3]
501
	b, _, e = bq.NextBatch(context.Background(), safeHead)
502
	require.NoError(t, e)
503 504 505 506 507 508 509
	require.NotNil(t, b)
	require.Equal(t, safeHead.Time+2, b.Timestamp)
	require.Equal(t, rollup.Epoch(1), b.EpochNum)
	safeHead.Number += 1
	safeHead.Time += 2
	safeHead.Hash = mockHash(b.Timestamp, 2)
	safeHead.L1Origin = b.Epoch()
510
	b, _, e = bq.NextBatch(context.Background(), safeHead)
511 512 513 514 515
	require.ErrorIs(t, e, io.EOF)
	require.Nil(t, b)

	// Advance to origin 4. Should generate one empty batch.
	input.origin = l1[4]
516
	b, _, e = bq.NextBatch(context.Background(), safeHead)
517
	require.NoError(t, e)
518 519 520 521 522 523 524
	require.NotNil(t, b)
	require.Equal(t, rollup.Epoch(2), b.EpochNum)
	require.Equal(t, safeHead.Time+2, b.Timestamp)
	safeHead.Number += 1
	safeHead.Time += 2
	safeHead.Hash = mockHash(b.Timestamp, 2)
	safeHead.L1Origin = b.Epoch()
525
	b, _, e = bq.NextBatch(context.Background(), safeHead)
526 527 528 529
	require.ErrorIs(t, e, io.EOF)
	require.Nil(t, b)
}

530
func testBatchQueue_Missing(t *testing.T, batchType int) {
531
	log := testlog.Logger(t, log.LevelCrit)
532
	l1 := L1Chain([]uint64{10, 15, 20, 25})
533
	chainId := big.NewInt(1234)
534 535 536 537 538 539 540
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(10, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           10,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
541 542 543 544 545 546 547 548
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     2,
549
		DeltaTime:         getDeltaTime(batchType),
550
		L2ChainID:         chainId,
551 552
	}

553
	// The inputBatches at 18 and 20 are skipped to stop 22 from being eagerly processed.
554
	// This test checks that batch timestamp 12 & 14 are created, 16 is used, and 18 is advancing the epoch.
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	// Due to the large sequencer time drift 16 is perfectly valid to have epoch 0 as origin.a

	// expected output of BatchQueue.NextBatch()
	expectedOutputBatches := []*SingularBatch{
		b(cfg.L2ChainID, 16, l1[0]),
		b(cfg.L2ChainID, 22, l1[1]),
	}
	// errors will be returned by fakeBatchQueueInput.NextBatch()
	inputErrors := []error{nil, nil}
	// batches will be returned by fakeBatchQueueInput
	var inputBatches []Batch
	if batchType == SpanBatchType {
		spanBlockCounts := []int{1, 1}
		inputErrors = []error{nil, nil, nil, io.EOF}
		inputBatches = buildSpanBatches(t, &safeHead, expectedOutputBatches, spanBlockCounts, chainId)
	} else {
		for _, singularBatch := range expectedOutputBatches {
			inputBatches = append(inputBatches, singularBatch)
		}
	}
575

576
	input := &fakeBatchQueueInput{
577 578
		batches: inputBatches,
		errors:  inputErrors,
579 580
		origin:  l1[0],
	}
581

582
	bq := NewBatchQueue(log, cfg, input, nil)
583
	_ = bq.Reset(context.Background(), l1[0], eth.SystemConfig{})
584

585
	for i := 0; i < len(expectedOutputBatches); i++ {
586
		b, _, e := bq.NextBatch(context.Background(), safeHead)
587 588 589
		require.ErrorIs(t, e, NotEnoughData)
		require.Nil(t, b)
	}
590

591
	// advance origin. Underlying stage still has no more inputBatches
592 593
	// This is not enough to auto advance yet
	input.origin = l1[1]
594
	b, _, e := bq.NextBatch(context.Background(), safeHead)
595 596 597 598 599 600 601
	require.ErrorIs(t, e, io.EOF)
	require.Nil(t, b)

	// Advance the origin. At this point batch timestamps 12 and 14 will be created
	input.origin = l1[2]

	// Check for a generated batch at t = 12
602
	b, _, e = bq.NextBatch(context.Background(), safeHead)
603 604
	require.Nil(t, e)
	require.Equal(t, b.Timestamp, uint64(12))
605
	require.Empty(t, b.Transactions)
606
	require.Equal(t, rollup.Epoch(0), b.EpochNum)
607 608 609 610 611
	safeHead.Number += 1
	safeHead.Time += 2
	safeHead.Hash = mockHash(b.Timestamp, 2)

	// Check for generated batch at t = 14
612
	b, _, e = bq.NextBatch(context.Background(), safeHead)
613 614
	require.Nil(t, e)
	require.Equal(t, b.Timestamp, uint64(14))
615
	require.Empty(t, b.Transactions)
616
	require.Equal(t, rollup.Epoch(0), b.EpochNum)
617 618 619 620 621
	safeHead.Number += 1
	safeHead.Time += 2
	safeHead.Hash = mockHash(b.Timestamp, 2)

	// Check for the inputted batch at t = 16
622
	b, _, e = bq.NextBatch(context.Background(), safeHead)
623
	require.Nil(t, e)
624
	require.Equal(t, b, expectedOutputBatches[0])
625
	require.Equal(t, rollup.Epoch(0), b.EpochNum)
626 627 628 629
	safeHead.Number += 1
	safeHead.Time += 2
	safeHead.Hash = mockHash(b.Timestamp, 2)

630 631 632
	// Advance the origin. At this point the batch with timestamp 18 will be created
	input.origin = l1[3]

633
	// Check for the generated batch at t = 18. This batch advances the epoch
634 635
	// Note: We need one io.EOF returned from the bq that advances the internal L1 Blocks view
	// before the batch will be auto generated
636
	_, _, e = bq.NextBatch(context.Background(), safeHead)
637
	require.Equal(t, e, io.EOF)
638
	b, _, e = bq.NextBatch(context.Background(), safeHead)
639 640
	require.Nil(t, e)
	require.Equal(t, b.Timestamp, uint64(18))
641
	require.Empty(t, b.Transactions)
642
	require.Equal(t, rollup.Epoch(1), b.EpochNum)
643
}
644

645
// testBatchStage_AdvancedEpoch tests that batch queue derives consecutive valid batches with advancing epochs.
646
// Batch queue's l1blocks list should be updated along epochs.
647
func testBatchStage_AdvancedEpoch(t *testing.T, batchType int, newBatchStage testableBatchStageFactory) {
648
	log := testlog.Logger(t, log.LevelCrit)
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
	l1 := L1Chain([]uint64{0, 6, 12, 18, 24}) // L1 block time: 6s
	chainId := big.NewInt(1234)
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(4, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           4,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     30,
666
		DeltaTime:         getDeltaTime(batchType),
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
		L2ChainID:         chainId,
	}

	// expected output of BatchQueue.NextBatch()
	expectedOutputBatches := []*SingularBatch{
		// 3 L2 blocks per L1 block
		b(cfg.L2ChainID, 6, l1[1]),
		b(cfg.L2ChainID, 8, l1[1]),
		b(cfg.L2ChainID, 10, l1[1]),
		b(cfg.L2ChainID, 12, l1[2]),
		b(cfg.L2ChainID, 14, l1[2]),
		b(cfg.L2ChainID, 16, l1[2]),
		b(cfg.L2ChainID, 18, l1[3]),
		b(cfg.L2ChainID, 20, l1[3]),
		b(cfg.L2ChainID, 22, l1[3]),
		nil,
	}
	// expected error of BatchQueue.NextBatch()
	expectedOutputErrors := []error{nil, nil, nil, nil, nil, nil, nil, nil, nil, io.EOF}
	// errors will be returned by fakeBatchQueueInput.NextBatch()
	inputErrors := expectedOutputErrors
	// batches will be returned by fakeBatchQueueInput
	var inputBatches []Batch
	if batchType == SpanBatchType {
		spanBlockCounts := []int{2, 2, 2, 3}
		inputErrors = []error{nil, nil, nil, nil, io.EOF}
		inputBatches = buildSpanBatches(t, &safeHead, expectedOutputBatches, spanBlockCounts, chainId)
		inputBatches = append(inputBatches, nil)
	} else {
		for _, singularBatch := range expectedOutputBatches {
			inputBatches = append(inputBatches, singularBatch)
		}
	}

	// ChannelInReader origin number
	inputOriginNumber := 2
	input := &fakeBatchQueueInput{
		batches: inputBatches,
		errors:  inputErrors,
		origin:  l1[inputOriginNumber],
	}

709
	bq := newBatchStage(log, cfg, input, nil)
710 711 712 713 714 715 716 717 718
	_ = bq.Reset(context.Background(), l1[1], eth.SystemConfig{})

	for i := 0; i < len(expectedOutputBatches); i++ {
		expectedOutput := expectedOutputBatches[i]
		if expectedOutput != nil && uint64(expectedOutput.EpochNum) == l1[inputOriginNumber].Number {
			// Advance ChannelInReader origin if needed
			inputOriginNumber += 1
			input.origin = l1[inputOriginNumber]
		}
719
		b, _, e := bq.NextBatch(context.Background(), safeHead)
720 721 722 723 724 725 726 727 728 729 730 731 732
		require.ErrorIs(t, e, expectedOutputErrors[i])
		if b == nil {
			require.Nil(t, expectedOutput)
		} else {
			require.Equal(t, expectedOutput, b)
			safeHead.Number += 1
			safeHead.Time += cfg.BlockTime
			safeHead.Hash = mockHash(b.Timestamp, 2)
			safeHead.L1Origin = b.Epoch()
		}
	}
}

733 734
// testBatchQueue_Shuffle tests batch queue can reorder shuffled valid batches
func testBatchQueue_Shuffle(t *testing.T, batchType int) {
735
	log := testlog.Logger(t, log.LevelCrit)
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	l1 := L1Chain([]uint64{0, 6, 12, 18, 24}) // L1 block time: 6s
	chainId := big.NewInt(1234)
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(4, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           4,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     30,
753
		DeltaTime:         getDeltaTime(batchType),
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
		L2ChainID:         chainId,
	}

	// expected output of BatchQueue.NextBatch()
	expectedOutputBatches := []*SingularBatch{
		// 3 L2 blocks per L1 block
		b(cfg.L2ChainID, 6, l1[1]),
		b(cfg.L2ChainID, 8, l1[1]),
		b(cfg.L2ChainID, 10, l1[1]),
		b(cfg.L2ChainID, 12, l1[2]),
		b(cfg.L2ChainID, 14, l1[2]),
		b(cfg.L2ChainID, 16, l1[2]),
		b(cfg.L2ChainID, 18, l1[3]),
		b(cfg.L2ChainID, 20, l1[3]),
		b(cfg.L2ChainID, 22, l1[3]),
	}
	// expected error of BatchQueue.NextBatch()
	expectedOutputErrors := []error{nil, nil, nil, nil, nil, nil, nil, nil, nil, io.EOF}
	// errors will be returned by fakeBatchQueueInput.NextBatch()
	inputErrors := expectedOutputErrors
	// batches will be returned by fakeBatchQueueInput
	var inputBatches []Batch
	if batchType == SpanBatchType {
		spanBlockCounts := []int{2, 2, 2, 3}
		inputErrors = []error{nil, nil, nil, nil, io.EOF}
		inputBatches = buildSpanBatches(t, &safeHead, expectedOutputBatches, spanBlockCounts, chainId)
	} else {
		for _, singularBatch := range expectedOutputBatches {
			inputBatches = append(inputBatches, singularBatch)
		}
	}

	// Shuffle the order of input batches
	rand.Shuffle(len(inputBatches), func(i, j int) {
		inputBatches[i], inputBatches[j] = inputBatches[j], inputBatches[i]
	})
	inputBatches = append(inputBatches, nil)

	// ChannelInReader origin number
	inputOriginNumber := 2
	input := &fakeBatchQueueInput{
		batches: inputBatches,
		errors:  inputErrors,
		origin:  l1[inputOriginNumber],
	}

	bq := NewBatchQueue(log, cfg, input, nil)
	_ = bq.Reset(context.Background(), l1[1], eth.SystemConfig{})

	for i := 0; i < len(expectedOutputBatches); i++ {
		expectedOutput := expectedOutputBatches[i]
		if expectedOutput != nil && uint64(expectedOutput.EpochNum) == l1[inputOriginNumber].Number {
			// Advance ChannelInReader origin if needed
			inputOriginNumber += 1
			input.origin = l1[inputOriginNumber]
		}
		var b *SingularBatch
		var e error
		for j := 0; j < len(expectedOutputBatches); j++ {
			// Multiple NextBatch() executions may be required because the order of input is shuffled
814
			b, _, e = bq.NextBatch(context.Background(), safeHead)
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
			if !errors.Is(e, NotEnoughData) {
				break
			}
		}
		require.ErrorIs(t, e, expectedOutputErrors[i])
		if b == nil {
			require.Nil(t, expectedOutput)
		} else {
			require.Equal(t, expectedOutput, b)
			safeHead.Number += 1
			safeHead.Time += cfg.BlockTime
			safeHead.Hash = mockHash(b.Timestamp, 2)
			safeHead.L1Origin = b.Epoch()
		}
	}
}

func TestBatchQueueOverlappingSpanBatch(t *testing.T) {
833
	log := testlog.Logger(t, log.LevelCrit)
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
	l1 := L1Chain([]uint64{10, 20, 30})
	chainId := big.NewInt(1234)
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(10, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           10,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     30,
851
		DeltaTime:         getDeltaTime(SpanBatchType),
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
		L2ChainID:         chainId,
	}

	// expected output of BatchQueue.NextBatch()
	expectedOutputBatches := []*SingularBatch{
		b(cfg.L2ChainID, 12, l1[0]),
		b(cfg.L2ChainID, 14, l1[0]),
		b(cfg.L2ChainID, 16, l1[0]),
		b(cfg.L2ChainID, 18, l1[0]),
		b(cfg.L2ChainID, 20, l1[0]),
		b(cfg.L2ChainID, 22, l1[0]),
		nil,
	}
	// expected error of BatchQueue.NextBatch()
	expectedOutputErrors := []error{nil, nil, nil, nil, nil, nil, io.EOF}
	// errors will be returned by fakeBatchQueueInput.NextBatch()
	inputErrors := []error{nil, nil, nil, nil, io.EOF}

	// batches will be returned by fakeBatchQueueInput
	var inputBatches []Batch
	batchSize := 3
	for i := 0; i < len(expectedOutputBatches)-batchSize; i++ {
874
		inputBatches = append(inputBatches, initializedSpanBatch(expectedOutputBatches[i:i+batchSize], uint64(0), chainId))
875 876
	}
	inputBatches = append(inputBatches, nil)
877 878 879 880 881 882 883
	// inputBatches:
	// [
	//    [12, 14, 16],  // No overlap
	//    [14, 16, 18],  // overlapped blocks: 14, 16
	//    [16, 18, 20],  // overlapped blocks: 16, 18
	//    [18, 20, 22],  // overlapped blocks: 18, 20
	// ]
884 885 886 887 888 889 890 891 892 893 894 895 896

	input := &fakeBatchQueueInput{
		batches: inputBatches,
		errors:  inputErrors,
		origin:  l1[0],
	}

	l2Client := testutils.MockL2Client{}
	var nilErr error
	for i, batch := range expectedOutputBatches {
		if batch != nil {
			blockRef := singularBatchToBlockRef(t, batch, uint64(i+1))
			payload := singularBatchToPayload(t, batch, uint64(i+1))
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
			if i < 3 {
				// In CheckBatch(), "L2BlockRefByNumber" is called when fetching the parent block of overlapped span batch
				// so blocks at 12, 14, 16 should be called.
				// CheckBatch() is called twice for a batch - before pushing to the queue, after popping from the queue
				l2Client.Mock.On("L2BlockRefByNumber", uint64(i+1)).Times(2).Return(blockRef, &nilErr)
			}
			if i == 1 || i == 4 {
				// In CheckBatch(), "PayloadByNumber" is called when fetching the overlapped blocks.
				// blocks at 14, 20 are included in overlapped blocks once.
				// CheckBatch() is called twice for a batch - before adding to the queue, after getting from the queue
				l2Client.Mock.On("PayloadByNumber", uint64(i+1)).Times(2).Return(&payload, &nilErr)
			} else if i == 2 || i == 3 {
				// blocks at 16, 18 are included in overlapped blocks twice.
				l2Client.Mock.On("PayloadByNumber", uint64(i+1)).Times(4).Return(&payload, &nilErr)
			}
912 913 914 915 916 917 918 919 920
		}
	}

	bq := NewBatchQueue(log, cfg, input, &l2Client)
	_ = bq.Reset(context.Background(), l1[0], eth.SystemConfig{})
	// Advance the origin
	input.origin = l1[1]

	for i := 0; i < len(expectedOutputBatches); i++ {
921
		b, _, e := bq.NextBatch(context.Background(), safeHead)
922 923 924 925 926 927 928 929 930 931 932
		require.ErrorIs(t, e, expectedOutputErrors[i])
		if b == nil {
			require.Nil(t, expectedOutputBatches[i])
		} else {
			require.Equal(t, expectedOutputBatches[i], b)
			safeHead.Number += 1
			safeHead.Time += cfg.BlockTime
			safeHead.Hash = mockHash(b.Timestamp, 2)
			safeHead.L1Origin = b.Epoch()
		}
	}
933 934

	l2Client.Mock.AssertExpectations(t)
935 936 937
}

func TestBatchQueueComplex(t *testing.T) {
938
	log := testlog.Logger(t, log.LevelCrit)
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
	l1 := L1Chain([]uint64{0, 6, 12, 18, 24}) // L1 block time: 6s
	chainId := big.NewInt(1234)
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(4, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           4,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     30,
956
		DeltaTime:         getDeltaTime(SpanBatchType),
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
		L2ChainID:         chainId,
	}

	// expected output of BatchQueue.NextBatch()
	expectedOutputBatches := []*SingularBatch{
		// 3 L2 blocks per L1 block
		b(cfg.L2ChainID, 6, l1[1]),
		b(cfg.L2ChainID, 8, l1[1]),
		b(cfg.L2ChainID, 10, l1[1]),
		b(cfg.L2ChainID, 12, l1[2]),
		b(cfg.L2ChainID, 14, l1[2]),
		b(cfg.L2ChainID, 16, l1[2]),
		b(cfg.L2ChainID, 18, l1[3]),
		b(cfg.L2ChainID, 20, l1[3]),
		b(cfg.L2ChainID, 22, l1[3]),
	}
	// expected error of BatchQueue.NextBatch()
	expectedOutputErrors := []error{nil, nil, nil, nil, nil, nil, nil, nil, nil, io.EOF}
	// errors will be returned by fakeBatchQueueInput.NextBatch()
	inputErrors := []error{nil, nil, nil, nil, nil, nil, io.EOF}
	// batches will be returned by fakeBatchQueueInput
	inputBatches := []Batch{
979 980 981 982 983 984
		initializedSpanBatch(expectedOutputBatches[0:2], uint64(0), chainId), // [6, 8] - no overlap
		expectedOutputBatches[2], // [10] - no overlap
		initializedSpanBatch(expectedOutputBatches[1:4], uint64(0), chainId), // [8, 10, 12] - overlapped blocks: 8 or 8, 10
		expectedOutputBatches[4], // [14] - no overlap
		initializedSpanBatch(expectedOutputBatches[4:6], uint64(0), chainId), // [14, 16] - overlapped blocks: nothing or 14
		initializedSpanBatch(expectedOutputBatches[6:9], uint64(0), chainId), // [18, 20, 22] - no overlap
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	}

	// Shuffle the order of input batches
	rand.Shuffle(len(inputBatches), func(i, j int) {
		inputBatches[i], inputBatches[j] = inputBatches[j], inputBatches[i]
	})

	inputBatches = append(inputBatches, nil)

	// ChannelInReader origin number
	inputOriginNumber := 2
	input := &fakeBatchQueueInput{
		batches: inputBatches,
		errors:  inputErrors,
		origin:  l1[inputOriginNumber],
	}

	l2Client := testutils.MockL2Client{}
	var nilErr error
	for i, batch := range expectedOutputBatches {
		if batch != nil {
			blockRef := singularBatchToBlockRef(t, batch, uint64(i+1))
			payload := singularBatchToPayload(t, batch, uint64(i+1))
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
			if i == 0 || i == 3 {
				// In CheckBatch(), "L2BlockRefByNumber" is called when fetching the parent block of overlapped span batch
				// so blocks at 6, 8 could be called, depends on the order of batches
				l2Client.Mock.On("L2BlockRefByNumber", uint64(i+1)).Return(blockRef, &nilErr).Maybe()
			}
			if i == 1 || i == 2 || i == 4 {
				// In CheckBatch(), "PayloadByNumber" is called when fetching the overlapped blocks.
				// so blocks at 14, 20 could be called, depends on the order of batches
				l2Client.Mock.On("PayloadByNumber", uint64(i+1)).Return(&payload, &nilErr).Maybe()
			}
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		}
	}

	bq := NewBatchQueue(log, cfg, input, &l2Client)
	_ = bq.Reset(context.Background(), l1[1], eth.SystemConfig{})

	for i := 0; i < len(expectedOutputBatches); i++ {
		expectedOutput := expectedOutputBatches[i]
		if expectedOutput != nil && uint64(expectedOutput.EpochNum) == l1[inputOriginNumber].Number {
			// Advance ChannelInReader origin if needed
			inputOriginNumber += 1
			input.origin = l1[inputOriginNumber]
		}
		var b *SingularBatch
		var e error
		for j := 0; j < len(expectedOutputBatches); j++ {
			// Multiple NextBatch() executions may be required because the order of input is shuffled
1035
			b, _, e = bq.NextBatch(context.Background(), safeHead)
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
			if !errors.Is(e, NotEnoughData) {
				break
			}
		}
		require.ErrorIs(t, e, expectedOutputErrors[i])
		if b == nil {
			require.Nil(t, expectedOutput)
		} else {
			require.Equal(t, expectedOutput, b)
			safeHead.Number += 1
			safeHead.Time += cfg.BlockTime
			safeHead.Hash = mockHash(b.Timestamp, 2)
			safeHead.L1Origin = b.Epoch()
		}
	}
1051 1052

	l2Client.Mock.AssertExpectations(t)
1053
}
1054 1055

func TestBatchQueueResetSpan(t *testing.T) {
1056
	log := testlog.Logger(t, log.LevelCrit)
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
	chainId := big.NewInt(1234)
	l1 := L1Chain([]uint64{0, 4, 8})
	safeHead := eth.L2BlockRef{
		Hash:           mockHash(0, 2),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           0,
		L1Origin:       l1[0].ID(),
		SequenceNumber: 0,
	}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L2Time: 10,
		},
		BlockTime:         2,
		MaxSequencerDrift: 600,
		SeqWindowSize:     30,
1074
		DeltaTime:         getDeltaTime(SpanBatchType),
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
		L2ChainID:         chainId,
	}

	singularBatches := []*SingularBatch{
		b(cfg.L2ChainID, 2, l1[0]),
		b(cfg.L2ChainID, 4, l1[1]),
		b(cfg.L2ChainID, 6, l1[1]),
		b(cfg.L2ChainID, 8, l1[2]),
	}

	input := &fakeBatchQueueInput{
1086
		batches: []Batch{initializedSpanBatch(singularBatches, uint64(0), chainId)},
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
		errors:  []error{nil},
		origin:  l1[2],
	}
	l2Client := testutils.MockL2Client{}
	bq := NewBatchQueue(log, cfg, input, &l2Client)
	bq.l1Blocks = l1 // Set enough l1 blocks to derive span batch

	// This NextBatch() will derive the span batch, return the first singular batch and save rest of batches in span.
	nextBatch, _, err := bq.NextBatch(context.Background(), safeHead)
	require.NoError(t, err)
	require.Equal(t, nextBatch, singularBatches[0])
	require.Equal(t, len(bq.nextSpan), len(singularBatches)-1)
	// batch queue's epoch should not be advanced until the entire span batch is returned
	require.Equal(t, bq.l1Blocks[0], l1[0])

	// This NextBatch() will return the second singular batch.
	safeHead.Number += 1
	safeHead.Time += cfg.BlockTime
	safeHead.Hash = mockHash(nextBatch.Timestamp, 2)
	safeHead.L1Origin = nextBatch.Epoch()
	nextBatch, _, err = bq.NextBatch(context.Background(), safeHead)
	require.NoError(t, err)
	require.Equal(t, nextBatch, singularBatches[1])
	require.Equal(t, len(bq.nextSpan), len(singularBatches)-2)
	// batch queue's epoch should not be advanced until the entire span batch is returned
	require.Equal(t, bq.l1Blocks[0], l1[0])

	// Call NextBatch() with stale safeHead. It means the second batch failed to be processed.
	// Batch queue should drop the entire span batch.
	nextBatch, _, err = bq.NextBatch(context.Background(), safeHead)
	require.Nil(t, nextBatch)
	require.ErrorIs(t, err, io.EOF)
	require.Equal(t, len(bq.nextSpan), 0)
}