cycle_test.go 14.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package cross

import (
	"errors"
	"fmt"
	"strconv"
	"testing"

	"github.com/stretchr/testify/require"

11
	"github.com/ethereum-optimism/optimism/op-service/eth"
12 13 14 15
	"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
)

type mockCycleCheckDeps struct {
16
	openBlockFn func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error)
17 18
}

19
func (m *mockCycleCheckDeps) OpenBlock(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
	return m.openBlockFn(chainID, blockNum)
}

type chainBlockDef struct {
	logCount uint32
	messages map[uint32]*types.ExecutingMessage
	error    error
}

type hazardCycleChecksTestCase struct {
	name        string
	chainBlocks map[string]chainBlockDef
	expectErr   error
	msg         string

	// Optional overrides
	hazards     map[types.ChainIndex]types.BlockSeal
37
	openBlockFn func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error)
38 39 40 41 42 43 44 45 46 47 48 49 50
}

func runHazardCycleChecksTestCaseGroup(t *testing.T, group string, tests []hazardCycleChecksTestCase) {
	for _, tc := range tests {
		t.Run(group+"/"+tc.name, func(t *testing.T) {
			runHazardCycleChecksTestCase(t, tc)
		})
	}
}

func runHazardCycleChecksTestCase(t *testing.T, tc hazardCycleChecksTestCase) {
	// Create mocked dependencies
	deps := &mockCycleCheckDeps{
51
		openBlockFn: func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
52 53 54 55 56 57 58 59 60
			// Use override if provided
			if tc.openBlockFn != nil {
				return tc.openBlockFn(chainID, blockNum)
			}

			// Default behavior
			chainStr := chainID.String()
			def, ok := tc.chainBlocks[chainStr]
			if !ok {
61
				return eth.BlockRef{}, 0, nil, errors.New("unexpected chain")
62 63
			}
			if def.error != nil {
64
				return eth.BlockRef{}, 0, nil, def.error
65
			}
66
			return eth.BlockRef{Number: blockNum}, def.logCount, def.messages, nil
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
		},
	}

	// Generate hazards map automatically if not explicitly provided
	var hazards map[types.ChainIndex]types.BlockSeal
	if tc.hazards != nil {
		hazards = tc.hazards
	} else {
		hazards = make(map[types.ChainIndex]types.BlockSeal)
		for chainStr := range tc.chainBlocks {
			hazards[chainIndex(chainStr)] = types.BlockSeal{Number: 1}
		}
	}

	// Run the test
	err := HazardCycleChecks(deps, 100, hazards)

	// No error expected
	if tc.expectErr == nil {
		require.NoError(t, err, tc.msg)
		return
	}

	// Error expected, make sure it's the right one
	require.Error(t, err, tc.msg)
	if errors.Is(err, tc.expectErr) {
		require.ErrorIs(t, err, tc.expectErr, tc.msg)
	} else {
		require.Contains(t, err.Error(), tc.expectErr.Error(), tc.msg)
	}
}

func chainIndex(s string) types.ChainIndex {
	id, err := strconv.ParseUint(s, 10, 32)
	if err != nil {
		panic(fmt.Sprintf("invalid chain index in test: %v", err))
	}
	return types.ChainIndex(id)
}

func execMsg(chain string, logIdx uint32) *types.ExecutingMessage {
	return execMsgWithTimestamp(chain, logIdx, 100)
}

func execMsgWithTimestamp(chain string, logIdx uint32, timestamp uint64) *types.ExecutingMessage {
	return &types.ExecutingMessage{
		Chain:     chainIndex(chain),
		LogIdx:    logIdx,
		Timestamp: timestamp,
	}
}

var emptyChainBlocks = map[string]chainBlockDef{
	"1": {
		logCount: 0,
		messages: map[uint32]*types.ExecutingMessage{},
	},
}

func TestHazardCycleChecksFailures(t *testing.T) {
	testOpenBlockErr := errors.New("test OpenBlock error")
	tests := []hazardCycleChecksTestCase{
		{
			name:        "empty hazards",
			chainBlocks: emptyChainBlocks,
			hazards:     make(map[types.ChainIndex]types.BlockSeal),
			expectErr:   nil,
			msg:         "expected no error when there are no hazards",
		},
		{
			name:        "nil hazards",
			chainBlocks: emptyChainBlocks,
			hazards:     nil,
			expectErr:   nil,
			msg:         "expected no error when there are nil hazards",
		},
		{
			name:        "nil blocks",
			chainBlocks: nil,
			hazards:     nil,
			expectErr:   nil,
			msg:         "expected no error when there are nil blocks and hazards",
		},
		{
			name:        "failed to open block error",
			chainBlocks: emptyChainBlocks,
153 154
			openBlockFn: func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
				return eth.BlockRef{}, 0, nil, testOpenBlockErr
155 156 157 158 159 160 161 162
			},
			expectErr: errors.New("failed to open block"),
			msg:       "expected error when OpenBlock fails",
		},
		{
			name:        "block mismatch error",
			chainBlocks: emptyChainBlocks,
			// openBlockFn returns a block number that doesn't match the expected block number.
163 164
			openBlockFn: func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
				return eth.BlockRef{Number: blockNum + 1}, 0, make(map[uint32]*types.ExecutingMessage), nil
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 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 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 359 360 361 362 363 364 365 366 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 399 400 401 402 403 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 456 457 458 459 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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
			},
			expectErr: errors.New("tried to open block"),
			msg:       "expected error due to block mismatch",
		},
		{
			name: "invalid log index error",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 3,
					messages: map[uint32]*types.ExecutingMessage{
						5: execMsg("1", 0), // Invalid index >= logCount.
					},
				},
			},
			expectErr: ErrExecMsgHasInvalidIndex,
			msg:       "expected invalid log index error",
		},
		{
			name: "self reference detected error",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 1,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("1", 0), // Points at itself.
					},
				},
			},
			expectErr: types.ErrConflict,
			msg:       "expected self reference detection error",
		},
		{
			name: "unknown chain",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("2", 0), // References chain 2 which isn't in hazards.
					},
				},
			},
			hazards: map[types.ChainIndex]types.BlockSeal{
				1: {Number: 1}, // Only include chain 1.
			},
			expectErr: ErrExecMsgUnknownChain,
			msg:       "expected unknown chain error",
		},
	}
	runHazardCycleChecksTestCaseGroup(t, "Failure", tests)
}

func TestHazardCycleChecksNoCycle(t *testing.T) {
	tests := []hazardCycleChecksTestCase{
		{
			name:        "no logs",
			chainBlocks: emptyChainBlocks,
			expectErr:   nil,
			msg:         "expected no cycle found for block with no logs",
		},
		{
			name: "one basic log",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 1,
					messages: map[uint32]*types.ExecutingMessage{},
				},
			},
			msg: "expected no cycle found for single basic log",
		},
		{
			name: "one exec log",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 0),
					},
				},
			},
			msg: "expected no cycle found for single exec log",
		},
		{
			name: "two basic logs",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{},
				},
			},
			msg: "expected no cycle found for two basic logs",
		},
		{
			name: "two exec logs to same target",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 3,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 0),
						2: execMsg("1", 0),
					},
				},
			},
			msg: "expected no cycle found for two exec logs pointing at the same log",
		},
		{
			name: "two exec logs to different targets",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 3,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 0),
						2: execMsg("1", 1),
					},
				},
			},
			msg: "expected no cycle found for two exec logs pointing at the different logs",
		},
		{
			name: "one basic log one exec log",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 0),
					},
				},
			},
			msg: "expected no cycle found for one basic and one exec log",
		},
		{
			name: "first log is exec",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 1,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("2", 0),
					},
				},
				"2": {
					logCount: 1,
					messages: nil,
				},
			},
			msg: "expected no cycle found first log is exec",
		},
		{
			name: "cycle through older timestamp",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("2", 0),
						1: execMsgWithTimestamp("2", 1, 101),
					},
				},
				"2": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("1", 1),
					},
				},
			},
			msg: "expected no cycle detection error for cycle through messages with different timestamps",
		},
		// This should be caught by earlier validations, but included for completeness.
		{
			name: "cycle through younger timestamp",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("2", 0),
						1: execMsgWithTimestamp("2", 1, 99),
					},
				},
				"2": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("1", 1),
					},
				},
			},
			msg: "expected no cycle detection error for cycle through messages with different timestamps",
		},
	}
	runHazardCycleChecksTestCaseGroup(t, "NoCycle", tests)
}

func TestHazardCycleChecksCycle(t *testing.T) {
	tests := []hazardCycleChecksTestCase{
		{
			name: "2-cycle in single chain with first log",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 3,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("1", 2),
						2: execMsg("1", 0),
					},
				},
			},
			expectErr: ErrCycle,
			msg:       "expected cycle detection error",
		},
		{
			name: "2-cycle in single chain with first log, adjacent",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("1", 1),
						1: execMsg("1", 0),
					},
				},
			},
			expectErr: ErrCycle,
			msg:       "expected cycle detection error",
		},
		{
			name: "2-cycle in single chain, not first, adjacent",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 3,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 2),
						2: execMsg("1", 1),
					},
				},
			},
			expectErr: ErrCycle,
			msg:       "expected cycle detection error",
		},
		{
			name: "2-cycle in single chain, not first, not adjacent",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 4,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 3),
						3: execMsg("1", 1),
					},
				},
			},
			expectErr: ErrCycle,
			msg:       "expected cycle detection error",
		},
		{
			name: "2-cycle across chains",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("2", 0),
					},
				},
				"2": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						0: execMsg("1", 1),
					},
				},
			},
			expectErr: ErrCycle,
			msg:       "expected cycle detection error for cycle through executing messages",
		},
		{
			name: "3-cycle in single chain",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 4,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 2), // Points to log 2
						2: execMsg("1", 3), // Points to log 3
						3: execMsg("1", 1), // Points back to log 1
					},
				},
			},
			expectErr: ErrCycle,
			msg:       "expected cycle detection error for 3-node cycle",
		},
		{
			name: "cycle through adjacency dependency",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 10,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 5), // Points to log 5
						5: execMsg("1", 2), // Points back to log 2 which is adjacent to log 1
					},
				},
			},
			expectErr: ErrCycle,
			msg:       "expected cycle detection error for when cycle goes through adjacency dependency",
		},
		{
			name: "2-cycle across chains with 3 hazard chains",
			chainBlocks: map[string]chainBlockDef{
				"1": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("2", 1),
					},
				},
				"2": {
					logCount: 2,
					messages: map[uint32]*types.ExecutingMessage{
						1: execMsg("1", 1),
					},
				},
				"3": {},
			},
			expectErr: ErrCycle,
			hazards: map[types.ChainIndex]types.BlockSeal{
				1: {Number: 1},
				2: {Number: 1},
				3: {Number: 1},
			},
			msg: "expected cycle detection error for cycle through executing messages",
		},
	}
	runHazardCycleChecksTestCaseGroup(t, "Cycle", tests)
}

const (
	largeGraphChains       = 10
	largeGraphLogsPerChain = 10000
)

func TestHazardCycleChecksLargeGraphNoCycle(t *testing.T) {
	// Create a large but acyclic graph
	chainBlocks := make(map[string]chainBlockDef)
	for i := 1; i <= largeGraphChains; i++ {
		msgs := make(map[uint32]*types.ExecutingMessage)
		// Create a chain of dependencies across chains
		if i > 1 {
			for j := uint32(0); j < largeGraphLogsPerChain; j++ {
				// Point to previous chain, same log index
				msgs[j] = execMsg(strconv.Itoa(i-1), j)
			}
		}
		chainBlocks[strconv.Itoa(i)] = chainBlockDef{
			logCount: largeGraphLogsPerChain,
			messages: msgs,
		}
	}

	tc := hazardCycleChecksTestCase{
		name:        "Large graph without cycles",
		chainBlocks: chainBlocks,
		expectErr:   nil,
		msg:         "expected no cycle in large acyclic graph",
	}
	runHazardCycleChecksTestCase(t, tc)
}

func TestHazardCycleChecksLargeGraphCycle(t *testing.T) {
	// Create a large graph with a cycle hidden in it
	const cycleChain = 3
	const cycleLogIndex = 5678

	chainBlocks := make(map[string]chainBlockDef)
	for i := 1; i <= largeGraphChains; i++ {
		msgs := make(map[uint32]*types.ExecutingMessage)

		// Create a chain of dependencies across chains
		if i > 1 {
			for j := uint32(0); j < largeGraphLogsPerChain; j++ {
				if i == cycleChain && j == cycleLogIndex {
					// Create a cycle by pointing back to chain 1
					msgs[j] = execMsg("1", cycleLogIndex+1)
				} else {
					// Normal case: point to previous chain, same log index
					msgs[j] = execMsg(strconv.Itoa(i-1), j)
				}
			}
		} else {
			// In chain 1, create the other side of the cycle
			msgs[cycleLogIndex+1] = execMsg(strconv.Itoa(cycleChain), cycleLogIndex)
		}

		chainBlocks[strconv.Itoa(i)] = chainBlockDef{
			logCount: largeGraphLogsPerChain,
			messages: msgs,
		}
	}

	tc := hazardCycleChecksTestCase{
		name:        "Large graph with cycle",
		chainBlocks: chainBlocks,
		expectErr:   ErrCycle,
		msg:         "expected to detect cycle in large cyclic graph",
	}
	runHazardCycleChecksTestCase(t, tc)
}