plasma_data_source_test.go 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package derive

import (
	"context"
	"io"
	"math/big"
	"math/rand"
	"testing"

	"github.com/ethereum-optimism/optimism/op-node/rollup"
	plasma "github.com/ethereum-optimism/optimism/op-plasma"
	"github.com/ethereum-optimism/optimism/op-service/eth"
	"github.com/ethereum-optimism/optimism/op-service/testlog"
	"github.com/ethereum-optimism/optimism/op-service/testutils"
15
	"github.com/ethereum/go-ethereum"
16 17 18 19 20 21
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/params"
22
	"github.com/stretchr/testify/mock"
23 24 25
	"github.com/stretchr/testify/require"
)

26 27 28 29 30 31 32 33 34 35 36 37
type MockFinalitySignal struct {
	mock.Mock
}

func (m *MockFinalitySignal) OnFinalized(blockRef eth.L1BlockRef) {
	m.MethodCalled("OnFinalized", blockRef)
}

func (m *MockFinalitySignal) ExpectFinalized(blockRef eth.L1BlockRef) {
	m.On("OnFinalized", blockRef).Once()
}

38 39
// TestPlasmaDataSource verifies that commitments are correctly read from l1 and then
// forwarded to the Plasma DA to return the correct inputs in the iterator.
40 41 42 43
// First it generates some L1 refs containing a random number of commitments, challenges
// the first 4 commitments then generates enough blocks to expire the challenge.
// Then it simulates rederiving while verifying it does skip the expired input until the next
// challenge expires.
44 45 46 47 48 49 50 51 52 53
func TestPlasmaDataSource(t *testing.T) {
	logger := testlog.Logger(t, log.LevelDebug)
	ctx := context.Background()

	rng := rand.New(rand.NewSource(1234))

	l1F := &testutils.MockL1Source{}

	storage := plasma.NewMockDAClient(logger)

54 55 56 57 58
	pcfg := plasma.Config{
		ChallengeWindow: 90, ResolveWindow: 90,
	}
	metrics := &plasma.NoopMetrics{}

59
	daState := plasma.NewState(logger, metrics, pcfg)
60 61 62 63 64

	da := plasma.NewPlasmaDAWithState(logger, pcfg, storage, metrics, daState)

	finalitySignal := &MockFinalitySignal{}
	da.OnFinalizedHeadSignal(finalitySignal.OnFinalized)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

	// Create rollup genesis and config
	l1Time := uint64(2)
	refA := testutils.RandomBlockRef(rng)
	refA.Number = 1
	l1Refs := []eth.L1BlockRef{refA}
	refA0 := eth.L2BlockRef{
		Hash:           testutils.RandomHash(rng),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           refA.Time,
		L1Origin:       refA.ID(),
		SequenceNumber: 0,
	}
	batcherPriv := testutils.RandomKey()
	batcherAddr := crypto.PubkeyToAddress(batcherPriv.PublicKey)
	batcherInbox := common.Address{42}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L1:     refA.ID(),
			L2:     refA0.ID(),
			L2Time: refA0.Time,
		},
88 89 90
		BlockTime:         1,
		SeqWindowSize:     20,
		BatchInboxAddress: batcherInbox,
91 92 93
		PlasmaConfig: &rollup.PlasmaConfig{
			DAChallengeWindow: pcfg.ChallengeWindow,
			DAResolveWindow:   pcfg.ResolveWindow,
94
			CommitmentType:    plasma.KeccakCommitmentString,
95
		},
96 97 98
	}
	// keep track of random input data to validate against
	var inputs [][]byte
99
	var comms []plasma.CommitmentData
100
	var inclusionBlocks []eth.L1BlockRef
101 102 103 104 105

	signer := cfg.L1Signer()

	factory := NewDataSourceFactory(logger, cfg, l1F, nil, da)

106 107 108 109
	nc := 0
	firstChallengeExpirationBlock := uint64(95)

	for i := uint64(0); i <= pcfg.ChallengeWindow+pcfg.ResolveWindow; i++ {
110 111 112 113 114 115 116 117 118 119
		parent := l1Refs[len(l1Refs)-1]
		// create a new mock l1 ref
		ref := eth.L1BlockRef{
			Hash:       testutils.RandomHash(rng),
			Number:     parent.Number + 1,
			ParentHash: parent.Hash,
			Time:       parent.Time + l1Time,
		}
		l1Refs = append(l1Refs, ref)
		logger.Info("new l1 block", "ref", ref)
120 121
		// called for each l1 block to sync challenges
		l1F.ExpectFetchReceipts(ref.Hash, nil, types.Receipts{}, nil)
122 123 124 125 126 127 128 129 130

		// pick a random number of commitments to include in the l1 block
		c := rng.Intn(4)
		var txs []*types.Transaction

		for j := 0; j < c; j++ {
			// mock input commitments in l1 transactions
			input := testutils.RandomData(rng, 2000)
			comm, _ := storage.SetInput(ctx, input)
131 132
			// plasma da tests are designed for keccak256 commitments, so we type assert here
			kComm := comm.(plasma.Keccak256Commitment)
133
			inputs = append(inputs, input)
134
			comms = append(comms, kComm)
135
			inclusionBlocks = append(inclusionBlocks, ref)
136 137 138 139 140 141 142 143 144

			tx, err := types.SignNewTx(batcherPriv, signer, &types.DynamicFeeTx{
				ChainID:   signer.ChainID(),
				Nonce:     0,
				GasTipCap: big.NewInt(2 * params.GWei),
				GasFeeCap: big.NewInt(30 * params.GWei),
				Gas:       100_000,
				To:        &batcherInbox,
				Value:     big.NewInt(int64(0)),
145
				Data:      comm.TxData(),
146 147 148 149
			})
			require.NoError(t, err)

			txs = append(txs, tx)
150

151 152 153
		}
		logger.Info("included commitments", "count", c)
		l1F.ExpectInfoAndTxsByHash(ref.Hash, testutils.RandomBlockInfo(rng), txs, nil)
154 155 156 157 158 159 160 161 162 163 164 165
		// called once per derivation
		l1F.ExpectInfoAndTxsByHash(ref.Hash, testutils.RandomBlockInfo(rng), txs, nil)

		if ref.Number == 2 {
			l1F.ExpectL1BlockRefByNumber(ref.Number, ref, nil)
			finalitySignal.ExpectFinalized(ref)
		}

		// challenge the first 4 commitments as soon as we have collected them all
		if len(comms) >= 4 && nc < 7 {
			// skip a block between each challenge transaction
			if nc%2 == 0 {
166
				daState.CreateChallenge(comms[nc/2], ref.ID(), inclusionBlocks[nc/2].Number)
167 168 169 170
				logger.Info("setting active challenge", "comm", comms[nc/2])
			}
			nc++
		}
171 172 173 174

		// create a new data source for each block
		src, err := factory.OpenData(ctx, ref, batcherAddr)
		require.NoError(t, err)
175 176 177 178 179 180 181 182

		// first challenge expires
		if i == firstChallengeExpirationBlock {
			_, err := src.Next(ctx)
			require.ErrorIs(t, err, ErrReset)
			break
		}

183 184 185 186 187 188 189 190 191 192
		for j := 0; j < c; j++ {
			data, err := src.Next(ctx)
			// check that each commitment is resolved
			require.NoError(t, err)
			require.Equal(t, hexutil.Bytes(inputs[len(inputs)-(c-j)]), data)
		}
		// returns EOF once done
		_, err = src.Next(ctx)
		require.ErrorIs(t, err, io.EOF)
	}
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

	logger.Info("pipeline reset ..................................")

	// start at 1 since first input should be skipped
	nc = 1
	secondChallengeExpirationBlock := 98

	for i := 1; i <= len(l1Refs)+2; i++ {

		var ref eth.L1BlockRef
		// first we run through all the existing l1 blocks
		if i < len(l1Refs) {
			ref = l1Refs[i]
			logger.Info("re deriving block", "ref", ref, "i", i)

			if i == len(l1Refs)-1 {
				l1F.ExpectFetchReceipts(ref.Hash, nil, types.Receipts{}, nil)
			}
			// once past the l1 head, continue generating new l1 refs
		} else {
			parent := l1Refs[len(l1Refs)-1]
			// create a new mock l1 ref
			ref = eth.L1BlockRef{
				Hash:       testutils.RandomHash(rng),
				Number:     parent.Number + 1,
				ParentHash: parent.Hash,
				Time:       parent.Time + l1Time,
			}
			l1Refs = append(l1Refs, ref)
			logger.Info("new l1 block", "ref", ref)
			// called for each l1 block to sync challenges
			l1F.ExpectFetchReceipts(ref.Hash, nil, types.Receipts{}, nil)

			// pick a random number of commitments to include in the l1 block
			c := rng.Intn(4)
			var txs []*types.Transaction

			for j := 0; j < c; j++ {
				// mock input commitments in l1 transactions
				input := testutils.RandomData(rng, 2000)
				comm, _ := storage.SetInput(ctx, input)
234 235
				// plasma da tests are designed for keccak256 commitments, so we type assert here
				kComm := comm.(plasma.Keccak256Commitment)
236
				inputs = append(inputs, input)
237
				comms = append(comms, kComm)
238 239 240 241 242 243 244 245 246

				tx, err := types.SignNewTx(batcherPriv, signer, &types.DynamicFeeTx{
					ChainID:   signer.ChainID(),
					Nonce:     0,
					GasTipCap: big.NewInt(2 * params.GWei),
					GasFeeCap: big.NewInt(30 * params.GWei),
					Gas:       100_000,
					To:        &batcherInbox,
					Value:     big.NewInt(int64(0)),
247
					Data:      comm.TxData(),
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
				})
				require.NoError(t, err)

				txs = append(txs, tx)

			}
			logger.Info("included commitments", "count", c)
			l1F.ExpectInfoAndTxsByHash(ref.Hash, testutils.RandomBlockInfo(rng), txs, nil)
		}

		// create a new data source for each block
		src, err := factory.OpenData(ctx, ref, batcherAddr)
		require.NoError(t, err)

		// next challenge expires
		if i == secondChallengeExpirationBlock {
			_, err := src.Next(ctx)
			require.ErrorIs(t, err, ErrReset)
			break
		}

		for data, err := src.Next(ctx); err != io.EOF; data, err = src.Next(ctx) {
			logger.Info("yielding data")
			// check that each commitment is resolved
			require.NoError(t, err)
			require.Equal(t, hexutil.Bytes(inputs[nc]), data)

			nc++
		}

	}

280 281
	// finalize based on the second to last block, which will prune the commitment on block 2, and make it finalized
	da.Finalize(l1Refs[len(l1Refs)-2])
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
	finalitySignal.AssertExpectations(t)
}

// This tests makes sure the pipeline returns a temporary error if data is not found.
func TestPlasmaDataSourceStall(t *testing.T) {
	logger := testlog.Logger(t, log.LevelDebug)
	ctx := context.Background()

	rng := rand.New(rand.NewSource(1234))

	l1F := &testutils.MockL1Source{}

	storage := plasma.NewMockDAClient(logger)

	pcfg := plasma.Config{
		ChallengeWindow: 90, ResolveWindow: 90,
	}

	metrics := &plasma.NoopMetrics{}

302
	daState := plasma.NewState(logger, metrics, pcfg)
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

	da := plasma.NewPlasmaDAWithState(logger, pcfg, storage, metrics, daState)

	finalitySignal := &MockFinalitySignal{}
	da.OnFinalizedHeadSignal(finalitySignal.OnFinalized)

	// Create rollup genesis and config
	l1Time := uint64(2)
	refA := testutils.RandomBlockRef(rng)
	refA.Number = 1
	l1Refs := []eth.L1BlockRef{refA}
	refA0 := eth.L2BlockRef{
		Hash:           testutils.RandomHash(rng),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           refA.Time,
		L1Origin:       refA.ID(),
		SequenceNumber: 0,
	}
	batcherPriv := testutils.RandomKey()
	batcherAddr := crypto.PubkeyToAddress(batcherPriv.PublicKey)
	batcherInbox := common.Address{42}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L1:     refA.ID(),
			L2:     refA0.ID(),
			L2Time: refA0.Time,
		},
		BlockTime:         1,
		SeqWindowSize:     20,
		BatchInboxAddress: batcherInbox,
334 335 336
		PlasmaConfig: &rollup.PlasmaConfig{
			DAChallengeWindow: pcfg.ChallengeWindow,
			DAResolveWindow:   pcfg.ResolveWindow,
337
			CommitmentType:    plasma.KeccakCommitmentString,
338
		},
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
	}

	signer := cfg.L1Signer()

	factory := NewDataSourceFactory(logger, cfg, l1F, nil, da)

	parent := l1Refs[0]
	// create a new mock l1 ref
	ref := eth.L1BlockRef{
		Hash:       testutils.RandomHash(rng),
		Number:     parent.Number + 1,
		ParentHash: parent.Hash,
		Time:       parent.Time + l1Time,
	}
	l1F.ExpectFetchReceipts(ref.Hash, nil, types.Receipts{}, nil)
	// mock input commitments in l1 transactions
	input := testutils.RandomData(rng, 2000)
	comm, _ := storage.SetInput(ctx, input)

	tx, err := types.SignNewTx(batcherPriv, signer, &types.DynamicFeeTx{
		ChainID:   signer.ChainID(),
		Nonce:     0,
		GasTipCap: big.NewInt(2 * params.GWei),
		GasFeeCap: big.NewInt(30 * params.GWei),
		Gas:       100_000,
		To:        &batcherInbox,
		Value:     big.NewInt(int64(0)),
366
		Data:      comm.TxData(),
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
	})
	require.NoError(t, err)

	txs := []*types.Transaction{tx}

	l1F.ExpectInfoAndTxsByHash(ref.Hash, testutils.RandomBlockInfo(rng), txs, nil)

	// delete the input from the DA provider so it returns not found
	require.NoError(t, storage.DeleteData(comm.Encode()))

	// next block is fetched to look ahead challenges but is not yet available
	l1F.ExpectL1BlockRefByNumber(ref.Number+1, eth.L1BlockRef{}, ethereum.NotFound)

	src, err := factory.OpenData(ctx, ref, batcherAddr)
	require.NoError(t, err)

	// data is not found so we return a temporary error
	_, err = src.Next(ctx)
	require.ErrorIs(t, err, ErrTemporary)

	// next block is available with no challenge events
	nextRef := eth.L1BlockRef{
		Number: ref.Number + 1,
		Hash:   testutils.RandomHash(rng),
	}
	l1F.ExpectL1BlockRefByNumber(nextRef.Number, nextRef, nil)
	l1F.ExpectFetchReceipts(nextRef.Hash, nil, types.Receipts{}, nil)

	// not enough data
	_, err = src.Next(ctx)
	require.ErrorIs(t, err, NotEnoughData)

399 400
	// create and resolve a challenge
	daState.CreateChallenge(comm, ref.ID(), ref.Number)
401
	// now challenge is resolved
402 403
	err = daState.ResolveChallenge(comm, eth.BlockID{Number: ref.Number + 2}, ref.Number, input)
	require.NoError(t, err)
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 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

	// derivation can resume
	data, err := src.Next(ctx)
	require.NoError(t, err)
	require.Equal(t, hexutil.Bytes(input), data)

	l1F.AssertExpectations(t)
}

// TestPlasmaDataSourceInvalidData tests that the pipeline skips invalid data and continues
// this includes invalid commitments and oversized inputs.
func TestPlasmaDataSourceInvalidData(t *testing.T) {
	logger := testlog.Logger(t, log.LevelDebug)
	ctx := context.Background()

	rng := rand.New(rand.NewSource(1234))

	l1F := &testutils.MockL1Source{}

	storage := plasma.NewMockDAClient(logger)

	pcfg := plasma.Config{
		ChallengeWindow: 90, ResolveWindow: 90,
	}

	da := plasma.NewPlasmaDAWithStorage(logger, pcfg, storage, &plasma.NoopMetrics{})

	// Create rollup genesis and config
	l1Time := uint64(2)
	refA := testutils.RandomBlockRef(rng)
	refA.Number = 1
	l1Refs := []eth.L1BlockRef{refA}
	refA0 := eth.L2BlockRef{
		Hash:           testutils.RandomHash(rng),
		Number:         0,
		ParentHash:     common.Hash{},
		Time:           refA.Time,
		L1Origin:       refA.ID(),
		SequenceNumber: 0,
	}
	batcherPriv := testutils.RandomKey()
	batcherAddr := crypto.PubkeyToAddress(batcherPriv.PublicKey)
	batcherInbox := common.Address{42}
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L1:     refA.ID(),
			L2:     refA0.ID(),
			L2Time: refA0.Time,
		},
		BlockTime:         1,
		SeqWindowSize:     20,
		BatchInboxAddress: batcherInbox,
456 457 458
		PlasmaConfig: &rollup.PlasmaConfig{
			DAChallengeWindow: pcfg.ChallengeWindow,
			DAResolveWindow:   pcfg.ResolveWindow,
459
			CommitmentType:    plasma.KeccakCommitmentString,
460
		},
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	}

	signer := cfg.L1Signer()

	factory := NewDataSourceFactory(logger, cfg, l1F, nil, da)

	parent := l1Refs[0]
	// create a new mock l1 ref
	ref := eth.L1BlockRef{
		Hash:       testutils.RandomHash(rng),
		Number:     parent.Number + 1,
		ParentHash: parent.Hash,
		Time:       parent.Time + l1Time,
	}
	l1F.ExpectFetchReceipts(ref.Hash, nil, types.Receipts{}, nil)
	// mock input commitments in l1 transactions with an oversized input
	input := testutils.RandomData(rng, plasma.MaxInputSize+1)
	comm, _ := storage.SetInput(ctx, input)

	tx1, err := types.SignNewTx(batcherPriv, signer, &types.DynamicFeeTx{
		ChainID:   signer.ChainID(),
		Nonce:     0,
		GasTipCap: big.NewInt(2 * params.GWei),
		GasFeeCap: big.NewInt(30 * params.GWei),
		Gas:       100_000,
		To:        &batcherInbox,
		Value:     big.NewInt(int64(0)),
488
		Data:      comm.TxData(),
489 490 491 492 493 494 495 496 497 498 499 500 501 502
	})
	require.NoError(t, err)

	// valid data
	input2 := testutils.RandomData(rng, 2000)
	comm2, _ := storage.SetInput(ctx, input2)
	tx2, err := types.SignNewTx(batcherPriv, signer, &types.DynamicFeeTx{
		ChainID:   signer.ChainID(),
		Nonce:     0,
		GasTipCap: big.NewInt(2 * params.GWei),
		GasFeeCap: big.NewInt(30 * params.GWei),
		Gas:       100_000,
		To:        &batcherInbox,
		Value:     big.NewInt(int64(0)),
503
		Data:      comm2.TxData(),
504 505 506
	})
	require.NoError(t, err)

507
	// regular input instead of commitment
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
	input3 := testutils.RandomData(rng, 32)
	tx3, err := types.SignNewTx(batcherPriv, signer, &types.DynamicFeeTx{
		ChainID:   signer.ChainID(),
		Nonce:     0,
		GasTipCap: big.NewInt(2 * params.GWei),
		GasFeeCap: big.NewInt(30 * params.GWei),
		Gas:       100_000,
		To:        &batcherInbox,
		Value:     big.NewInt(int64(0)),
		Data:      input3,
	})
	require.NoError(t, err)

	txs := []*types.Transaction{tx1, tx2, tx3}

	l1F.ExpectInfoAndTxsByHash(ref.Hash, testutils.RandomBlockInfo(rng), txs, nil)

	src, err := factory.OpenData(ctx, ref, batcherAddr)
	require.NoError(t, err)

528
	// oversized input is skipped and returns input2 directly
529 530 531 532
	data, err := src.Next(ctx)
	require.NoError(t, err)
	require.Equal(t, hexutil.Bytes(input2), data)

533 534 535 536 537
	// regular input is passed through
	data, err = src.Next(ctx)
	require.NoError(t, err)
	require.Equal(t, hexutil.Bytes(input3), data)

538 539 540 541
	_, err = src.Next(ctx)
	require.ErrorIs(t, err, io.EOF)

	l1F.AssertExpectations(t)
542
}