db_test.go 14.7 KB
Newer Older
1 2
package db

3
/*
4
import (
5
	"errors"
6
	"fmt"
7
	"io"
8
	"math/rand" // nosemgrep
9 10
	"testing"

11 12 13 14 15
	"github.com/stretchr/testify/require"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/log"

16
	"github.com/ethereum-optimism/optimism/op-service/eth"
17
	"github.com/ethereum-optimism/optimism/op-service/testlog"
18 19 20
	"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/entrydb"
	"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/heads"
	"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/logs"
21
	"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
22 23
)

24 25
func TestChainsDB_AddLog(t *testing.T) {
	t.Run("UnknownChain", func(t *testing.T) {
26
		db := NewChainsDB(nil, &stubHeadStorage{}, testlog.Logger(t, log.LevelDebug))
27
		err := db.AddLog(types.ChainIDFromUInt64(2), common.Hash{}, eth.BlockID{}, 33, nil)
28
		require.ErrorIs(t, err, ErrUnknownChain)
29 30
	})

31 32 33 34 35
	t.Run("KnownChain", func(t *testing.T) {
		chainID := types.ChainIDFromUInt64(1)
		logDB := &stubLogDB{}
		db := NewChainsDB(map[types.ChainID]LogStorage{
			chainID: logDB,
36 37 38 39
		}, &stubHeadStorage{}, testlog.Logger(t, log.LevelDebug))
		bl10 := eth.BlockID{Hash: common.Hash{0x10}, Number: 10}
		err := db.SealBlock(chainID, common.Hash{0x9}, bl10, 1234)
		require.NoError(t, err, err)
40
		err = db.AddLog(chainID, common.Hash{}, bl10, 0, nil)
41 42
		require.NoError(t, err, err)
		require.Equal(t, 1, logDB.addLogCalls)
43
		require.Equal(t, 1, logDB.sealBlockCalls)
44 45 46
	})
}

47 48
func TestChainsDB_Rewind(t *testing.T) {
	t.Run("UnknownChain", func(t *testing.T) {
49
		db := NewChainsDB(nil, &stubHeadStorage{}, testlog.Logger(t, log.LevelDebug))
50 51
		err := db.Rewind(types.ChainIDFromUInt64(2), 42)
		require.ErrorIs(t, err, ErrUnknownChain)
52 53
	})

54 55 56 57 58
	t.Run("KnownChain", func(t *testing.T) {
		chainID := types.ChainIDFromUInt64(1)
		logDB := &stubLogDB{}
		db := NewChainsDB(map[types.ChainID]LogStorage{
			chainID: logDB,
59 60
		}, &stubHeadStorage{},
			testlog.Logger(t, log.LevelDebug))
61 62 63
		err := db.Rewind(chainID, 23)
		require.NoError(t, err, err)
		require.EqualValues(t, 23, logDB.headBlockNum)
64 65 66
	})
}

67 68 69 70 71 72
func TestChainsDB_UpdateCrossHeads(t *testing.T) {
	// using a chainID of 1 for simplicity
	chainID := types.ChainIDFromUInt64(1)
	// get default stubbed components
	logDB, checker, h := setupStubbedForUpdateHeads(chainID)

73 74 75
	checker.numSafe = 1
	xSafe := checker.crossHeadForChain

76 77 78 79
	// The ChainsDB is real, but uses only stubbed components
	db := NewChainsDB(
		map[types.ChainID]LogStorage{
			chainID: logDB},
80 81
		&stubHeadStorage{h},
		testlog.Logger(t, log.LevelDebug))
82 83 84

	err := db.UpdateCrossHeads(checker)
	require.NoError(t, err)
85 86
	// found a safe executing message, and no new initiating messages
	require.Equal(t, xSafe+1, checker.updated)
87 88 89 90 91 92 93
}

func TestChainsDB_UpdateCrossHeadsBeyondLocal(t *testing.T) {
	// using a chainID of 1 for simplicity
	chainID := types.ChainIDFromUInt64(1)
	// get default stubbed components
	logDB, checker, h := setupStubbedForUpdateHeads(chainID)
94
	// set the safety checker to pass 99 times, effectively allowing all messages to be safe
95 96
	checker.numSafe = 99

97 98
	startLocalSafe := checker.localHeadForChain

99 100 101 102
	// The ChainsDB is real, but uses only stubbed components
	db := NewChainsDB(
		map[types.ChainID]LogStorage{
			chainID: logDB},
103 104
		&stubHeadStorage{h},
		testlog.Logger(t, log.LevelDebug))
105 106 107 108 109 110 111

	// Update cross-heads is expected to:
	// 1. get a last checkpoint iterator from the logDB (stubbed to be at 15)
	// 2. progress the iterator to repeatedly, as the safety check will pass 99 times.
	// 3. exceed the local head, and update the cross-head to the local head (40)
	err := db.UpdateCrossHeads(checker)
	require.NoError(t, err)
112
	require.Equal(t, startLocalSafe, checker.updated)
113 114 115 116 117 118 119 120
}

func TestChainsDB_UpdateCrossHeadsEOF(t *testing.T) {
	// using a chainID of 1 for simplicity
	chainID := types.ChainIDFromUInt64(1)
	// get default stubbed components
	logDB, checker, h := setupStubbedForUpdateHeads(chainID)
	// set the log DB to return an EOF error when trying to get the next executing message
121 122 123 124
	// after processing 10 message (with more messages available to be safe)
	logDB.nextLogs = logDB.nextLogs[:checker.crossHeadForChain+11]
	// This is a legacy test, the local head is further than the DB content...

125 126 127 128 129 130
	checker.numSafe = 99

	// The ChainsDB is real, but uses only stubbed components
	db := NewChainsDB(
		map[types.ChainID]LogStorage{
			chainID: logDB},
131 132
		&stubHeadStorage{h},
		testlog.Logger(t, log.LevelDebug))
133 134

	// Update cross-heads is expected to:
135 136
	// - process 10 logs as safe, 5 of which execute something
	// - update cross-safe to what was there
137 138
	err := db.UpdateCrossHeads(checker)
	require.NoError(t, err)
139
	require.Equal(t, checker.crossHeadForChain+11, checker.updated)
140 141 142 143 144 145 146 147 148
}

func TestChainsDB_UpdateCrossHeadsError(t *testing.T) {
	// using a chainID of 1 for simplicity
	chainID := types.ChainIDFromUInt64(1)
	// get default stubbed components
	logDB, checker, h := setupStubbedForUpdateHeads(chainID)
	// set the log DB to return an error when trying to get the next executing message
	// after processing 3 messages as safe (with more messages available to be safe)
149 150 151 152 153 154 155 156 157 158 159 160

	executed := 0
	for i, e := range logDB.nextLogs {
		if executed == 3 {
			logDB.nextLogs[i].err = errors.New("some error")
		}
		if entrydb.EntryIdx(i) > checker.crossHeadForChain && e.execIdx >= 0 {
			executed++
		}
	}

	// everything is safe until error
161 162 163 164 165 166
	checker.numSafe = 99

	// The ChainsDB is real, but uses only stubbed components
	db := NewChainsDB(
		map[types.ChainID]LogStorage{
			chainID: logDB},
167 168
		&stubHeadStorage{h},
		testlog.Logger(t, log.LevelDebug))
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

	// Update cross-heads is expected to:
	// 1. get a last checkpoint iterator from the logDB (stubbed to be at 10)
	// 2. fail during execution, even after processing 3 messages as safe
	// 3. exit without updating, returning the error
	err := db.UpdateCrossHeads(checker)
	require.Error(t, err)
	// the update was never set (aka 0-value)
	require.Equal(t, entrydb.EntryIdx(0), checker.updated)
}

// setupStubbedForUpdateHeads sets up stubbed components for testing the UpdateCrossHeads method
// it returns stubbed structs which are suitable for their interfaces, and can be modified before testing
// TODO: the variables at the top of this function should be configurable by the caller.
// this isn't an issue for now, as all tests can modify the stubbed components directly after calling this function.
// but readability and maintainability would be improved by making this function more configurable.
func setupStubbedForUpdateHeads(chainID types.ChainID) (*stubLogDB, *stubChecker, *heads.Heads) {
	// the last known cross-safe head is at 20
187
	cross := heads.HeadPointer{LastSealedBlockNum: 20}
188
	// the local head (the limit of the update) is at 40
189
	local := heads.HeadPointer{LastSealedBlockNum: 40}
190 191 192 193 194 195 196
	// the number of executing messages to make available (this should be more than the number of safety checks performed)
	numExecutingMessages := 30
	// number of safety checks that will pass before returning false
	numSafe := 1

	// set up stubbed logDB
	logDB := &stubLogDB{}
197

198
	// set up stubbed executing messages that the ChainsDB can pass to the checker
199
	logDB.executingMessages = []*types.ExecutingMessage{}
200 201
	for i := 0; i < numExecutingMessages; i++ {
		// executing messages are packed in groups of 3, with block numbers increasing by 1
202
		logDB.executingMessages = append(logDB.executingMessages, &types.ExecutingMessage{
203 204
			BlockNum: uint64(100 + int(i/3)),
			LogIdx:   uint32(i),
205
			Hash:     common.Hash{},
206 207 208
		})
	}

209 210 211 212 213
	rng := rand.New(rand.NewSource(123))
	blockNum := uint64(100)
	logIndex := uint32(0)
	executedCount := 0
	for i := entrydb.EntryIdx(0); i <= local; i++ {
214
		var logHash common.Hash
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
		rng.Read(logHash[:])

		execIndex := -1
		// All the even messages have an executing message
		if i%2 == 0 {
			execIndex = rng.Intn(len(logDB.executingMessages))
			executedCount += 1
		}
		var msgErr error

		logDB.nextLogs = append(logDB.nextLogs, nextLogResponse{
			blockNum: blockNum,
			logIdx:   logIndex,
			evtHash:  logHash,
			err:      msgErr,
			execIdx:  execIndex,
		})
	}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	// set up stubbed checker
	checker := &stubChecker{
		localHeadForChain: local,
		crossHeadForChain: cross,
		// the first safety check will return true, the second false
		numSafe: numSafe,
	}

	// set up stubbed heads with sample values
	h := heads.NewHeads()
	h.Chains[chainID] = heads.ChainHeads{}

	return logDB, checker, h
}

type stubChecker struct {
250 251
	localHeadForChain heads.HeadPointer
	crossHeadForChain heads.HeadPointer
252 253
	numSafe           int
	checkCalls        int
254
	updated           heads.HeadPointer
255 256
}

257 258
func (s *stubChecker) String() string {
	return "stubChecker"
259 260
}

261 262
func (s *stubChecker) LocalSafetyLevel() types.SafetyLevel {
	return types.Safe
263 264
}

265 266 267 268 269 270 271 272 273
func (s *stubChecker) CrossSafetyLevel() types.SafetyLevel {
	return types.Safe
}

func (s *stubChecker) LocalHead(chainID types.ChainID) heads.HeadPointer {
	return s.localHeadForChain
}

func (s *stubChecker) CrossHead(chainID types.ChainID) heads.HeadPointer {
274 275 276 277
	return s.crossHeadForChain
}

// stubbed Check returns true for the first numSafe calls, and false thereafter
278
func (s *stubChecker) Check(chain types.ChainID, blockNum uint64, logIdx uint32, logHash common.Hash) bool {
279
	if s.checkCalls >= s.numSafe {
280
		return fmt.Errorf("safety check failed")
281 282
	}
	s.checkCalls++
283 284 285 286 287 288 289
	return nil
}
func (s *stubChecker) CheckCross(chain types.ChainID, blockNum uint64, logIdx uint32, logHash backendTypes.TruncatedHash) error {
	return s.check(chain, blockNum, logIdx, logHash)
}
func (s *stubChecker) CheckLocal(chain types.ChainID, blockNum uint64, logIdx uint32, logHash backendTypes.TruncatedHash) error {
	return s.check(chain, blockNum, logIdx, logHash)
290 291
}

292 293 294 295 296 297 298 299 300
func (s *stubChecker) Update(chain types.ChainID, h heads.HeadPointer) error {
	s.updated = h
	return nil
}
func (s *stubChecker) UpdateCross(chain types.ChainID, h heads.HeadPointer) error {
	return s.Update(chain, h)
}
func (s *stubChecker) UpdateLocal(chain types.ChainID, h heads.HeadPointer) error {
	return s.Update(chain, h)
301 302
}

303 304 305 306
func (s *stubChecker) SafetyLevel() types.SafetyLevel {
	return types.CrossSafe
}

307 308 309 310
type stubHeadStorage struct {
	heads *heads.Heads
}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
func (s *stubHeadStorage) UpdateLocalUnsafe(chainID types.ChainID, h heads.HeadPointer) error {
	panic("not implemented")
}

func (s *stubHeadStorage) UpdateLocalSafe(chainID types.ChainID, h heads.HeadPointer) error {
	panic("not implemented")
}

func (s *stubHeadStorage) UpdateLocalFinalized(chainID types.ChainID, h heads.HeadPointer) error {
	panic("not implemented")
}

func (s *stubHeadStorage) UpdateCrossUnsafe(chainID types.ChainID, h heads.HeadPointer) error {
	panic("not implemented")
}

func (s *stubHeadStorage) UpdateCrossSafe(chainID types.ChainID, h heads.HeadPointer) error {
	panic("not implemented")
}

func (s *stubHeadStorage) UpdateCrossFinalized(chainID types.ChainID, h heads.HeadPointer) error {
	panic("not implemented")
}

func (s *stubHeadStorage) LocalUnsafe(chainID types.ChainID) heads.HeadPointer {
	panic("not implemented")
}

func (s *stubHeadStorage) LocalSafe(chainID types.ChainID) heads.HeadPointer {
	panic("not implemented")
}

func (s *stubHeadStorage) LocalFinalized(chainID types.ChainID) heads.HeadPointer {
	panic("not implemented")
}

func (s *stubHeadStorage) CrossUnsafe(chainID types.ChainID) heads.HeadPointer {
	panic("not implemented")
}

func (s *stubHeadStorage) CrossSafe(chainID types.ChainID) heads.HeadPointer {
	panic("not implemented")
}

func (s *stubHeadStorage) CrossFinalized(chainID types.ChainID) heads.HeadPointer {
	panic("not implemented")
}

359 360 361 362 363 364 365 366 367 368 369
func (s *stubHeadStorage) Apply(heads.Operation) error {
	return nil
}

func (s *stubHeadStorage) Current() *heads.Heads {
	if s.heads == nil {
		s.heads = heads.NewHeads()
	}
	return s.heads.Copy()
}

370 371
type nextLogResponse struct {
	blockNum uint64
372 373 374

	logIdx uint32

375
	evtHash common.Hash
376 377 378 379 380

	err error

	// -1 if not executing
	execIdx int
381
}
382

383
type stubIterator struct {
384 385 386
	index entrydb.EntryIdx

	db *stubLogDB
387 388
}

389 390
func (s *stubIterator) End() error {
	return nil // only used for DB-loading. The stub is already loaded
391
}
392

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
func (s *stubIterator) NextInitMsg() error {
	s.index += 1
	if s.index >= entrydb.EntryIdx(len(s.db.nextLogs)) {
		return io.EOF
	}
	e := s.db.nextLogs[s.index]
	return e.err
}

func (s *stubIterator) NextExecMsg() error {
	for {
		s.index += 1
		if s.index >= entrydb.EntryIdx(len(s.db.nextLogs)) {
			return io.EOF
		}
		e := s.db.nextLogs[s.index]
		if e.err != nil {
			return e.err
		}
		if e.execIdx >= 0 {
			return nil
		}
	}
416
}
417 418 419

func (s *stubIterator) NextBlock() error {
	panic("not yet supported")
420
}
421

422 423
func (s *stubIterator) NextIndex() entrydb.EntryIdx {
	return s.index + 1
424 425
}

426
func (s *stubIterator) SealedBlock() (hash common.Hash, num uint64, ok bool) {
427
	panic("not yet supported")
428 429
}

430
func (s *stubIterator) InitMessage() (hash common.Hash, logIndex uint32, ok bool) {
431
	if s.index < 0 {
432
		return common.Hash{}, 0, false
433 434
	}
	if s.index >= entrydb.EntryIdx(len(s.db.nextLogs)) {
435
		return common.Hash{}, 0, false
436 437 438
	}
	e := s.db.nextLogs[s.index]
	return e.evtHash, e.logIdx, true
439 440
}

441
func (s *stubIterator) ExecMessage() *types.ExecutingMessage {
442 443
	if s.index < 0 {
		return nil
444
	}
445 446 447 448 449 450 451 452
	if s.index >= entrydb.EntryIdx(len(s.db.nextLogs)) {
		return nil
	}
	e := s.db.nextLogs[s.index]
	if e.execIdx < 0 {
		return nil
	}
	return s.db.executingMessages[e.execIdx]
453 454
}

455 456 457 458 459 460 461
var _ logs.Iterator = (*stubIterator)(nil)

type stubLogDB struct {
	addLogCalls    int
	sealBlockCalls int
	headBlockNum   uint64

462
	executingMessages []*types.ExecutingMessage
463 464 465
	nextLogs          []nextLogResponse

	containsResponse containsResponse
466 467
}

468
func (s *stubLogDB) AddLog(logHash common.Hash, parentBlock eth.BlockID, logIdx uint32, execMsg *types.ExecutingMessage) error {
469 470
	s.addLogCalls++
	return nil
471 472
}

473 474 475 476 477 478 479 480 481 482 483 484 485
func (s *stubLogDB) SealBlock(parentHash common.Hash, block eth.BlockID, timestamp uint64) error {
	s.sealBlockCalls++
	return nil
}

func (s *stubLogDB) LatestSealedBlockNum() (n uint64, ok bool) {
	return s.headBlockNum, true
}

func (s *stubLogDB) FindSealedBlock(block eth.BlockID) (nextEntry entrydb.EntryIdx, err error) {
	panic("not implemented")
}

486
func (s *stubLogDB) IteratorStartingAt(sealedNum uint64, logIndex uint32) (logs.Iterator, error) {
487
	return &stubIterator{
488 489
		//index: i - 1, // TODO broken
		db: s,
490 491 492 493 494
	}, nil
}

var _ LogStorage = (*stubLogDB)(nil)

495
type containsResponse struct {
496 497
	index entrydb.EntryIdx
	err   error
498 499 500 501
}

// stubbed Contains records the arguments passed to it
// it returns the response set in the struct, or an empty response
502
func (s *stubLogDB) Contains(blockNum uint64, logIdx uint32, logHash common.Hash) (nextIndex entrydb.EntryIdx, err error) {
503
	return s.containsResponse.index, s.containsResponse.err
504 505
}

506 507
func (s *stubLogDB) Rewind(newHeadBlockNum uint64) error {
	s.headBlockNum = newHeadBlockNum
508 509 510
	return nil
}

511 512
func (s *stubLogDB) LatestBlockNum() uint64 {
	return s.headBlockNum
513 514
}

515
func (s *stubLogDB) Close() error {
516 517
	return nil
}
518
*/