gamefactory_test.go 9.99 KB
Newer Older
1 2 3 4
package contracts

import (
	"context"
5
	"fmt"
6
	"math/big"
7
	"slices"
8 9
	"testing"

10
	"github.com/ethereum-optimism/optimism/op-challenger/game/fault/contracts/metrics"
11
	faultTypes "github.com/ethereum-optimism/optimism/op-challenger/game/fault/types"
12 13
	"github.com/ethereum-optimism/optimism/op-challenger/game/types"
	"github.com/ethereum-optimism/optimism/op-service/sources/batching"
14
	"github.com/ethereum-optimism/optimism/op-service/sources/batching/rpcblock"
15
	batchingTest "github.com/ethereum-optimism/optimism/op-service/sources/batching/test"
16
	"github.com/ethereum-optimism/optimism/packages/contracts-bedrock/snapshots"
17
	"github.com/ethereum/go-ethereum/common"
18
	ethTypes "github.com/ethereum/go-ethereum/core/types"
19 20 21
	"github.com/stretchr/testify/require"
)

22 23 24 25
var (
	factoryAddr = common.HexToAddress("0x24112842371dFC380576ebb09Ae16Cb6B6caD7CB")
	batchSize   = 5
)
26

27
func TestDisputeGameFactorySimpleGetters(t *testing.T) {
28
	blockHash := common.Hash{0xbb, 0xcd}
29 30 31 32 33 34 35 36 37 38 39 40
	tests := []struct {
		method   string
		args     []interface{}
		result   interface{}
		expected interface{} // Defaults to expecting the same as result
		call     func(game *DisputeGameFactoryContract) (any, error)
	}{
		{
			method:   methodGameCount,
			result:   big.NewInt(9876),
			expected: uint64(9876),
			call: func(game *DisputeGameFactoryContract) (any, error) {
41
				return game.GetGameCount(context.Background(), blockHash)
42 43 44 45 46 47 48
			},
		},
	}
	for _, test := range tests {
		test := test
		t.Run(test.method, func(t *testing.T) {
			stubRpc, factory := setupDisputeGameFactoryTest(t)
49
			stubRpc.SetResponse(factoryAddr, test.method, rpcblock.ByHash(blockHash), nil, []interface{}{test.result})
50 51 52 53 54 55 56 57 58 59 60 61
			status, err := test.call(factory)
			require.NoError(t, err)
			expected := test.expected
			if expected == nil {
				expected = test.result
			}
			require.Equal(t, expected, status)
		})
	}
}

func TestLoadGame(t *testing.T) {
62
	blockHash := common.Hash{0xbb, 0xce}
63 64
	stubRpc, factory := setupDisputeGameFactoryTest(t)
	game0 := types.GameMetadata{
65
		Index:     0,
66 67 68 69 70
		GameType:  0,
		Timestamp: 1234,
		Proxy:     common.Address{0xaa},
	}
	game1 := types.GameMetadata{
71
		Index:     1,
72 73 74 75 76
		GameType:  1,
		Timestamp: 5678,
		Proxy:     common.Address{0xbb},
	}
	game2 := types.GameMetadata{
77
		Index:     2,
78 79 80 81 82 83
		GameType:  99,
		Timestamp: 9988,
		Proxy:     common.Address{0xcc},
	}
	expectedGames := []types.GameMetadata{game0, game1, game2}
	for idx, expected := range expectedGames {
84 85
		expectGetGame(stubRpc, idx, blockHash, expected)
		actual, err := factory.GetGame(context.Background(), uint64(idx), blockHash)
86 87 88 89 90
		require.NoError(t, err)
		require.Equal(t, expected, actual)
	}
}

91 92 93 94
func TestGetAllGames(t *testing.T) {
	blockHash := common.Hash{0xbb, 0xce}
	stubRpc, factory := setupDisputeGameFactoryTest(t)
	game0 := types.GameMetadata{
95
		Index:     0,
96 97 98 99 100
		GameType:  0,
		Timestamp: 1234,
		Proxy:     common.Address{0xaa},
	}
	game1 := types.GameMetadata{
101
		Index:     1,
102 103 104 105 106
		GameType:  1,
		Timestamp: 5678,
		Proxy:     common.Address{0xbb},
	}
	game2 := types.GameMetadata{
107
		Index:     2,
108 109 110 111 112 113
		GameType:  99,
		Timestamp: 9988,
		Proxy:     common.Address{0xcc},
	}

	expectedGames := []types.GameMetadata{game0, game1, game2}
114
	stubRpc.SetResponse(factoryAddr, methodGameCount, rpcblock.ByHash(blockHash), nil, []interface{}{big.NewInt(int64(len(expectedGames)))})
115 116 117 118 119 120 121 122
	for idx, expected := range expectedGames {
		expectGetGame(stubRpc, idx, blockHash, expected)
	}
	actualGames, err := factory.GetAllGames(context.Background(), blockHash)
	require.NoError(t, err)
	require.Equal(t, expectedGames, actualGames)
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
func TestGetAllGamesAtOrAfter(t *testing.T) {
	tests := []struct {
		gameCount       int
		earliestGameIdx int
	}{
		{gameCount: batchSize * 4, earliestGameIdx: batchSize + 3},
		{gameCount: 0, earliestGameIdx: 0},
		{gameCount: batchSize * 2, earliestGameIdx: batchSize},
		{gameCount: batchSize * 2, earliestGameIdx: batchSize + 1},
		{gameCount: batchSize * 2, earliestGameIdx: batchSize - 1},
		{gameCount: batchSize * 2, earliestGameIdx: batchSize * 2},
		{gameCount: batchSize * 2, earliestGameIdx: batchSize*2 + 1},
		{gameCount: batchSize - 2, earliestGameIdx: batchSize - 3},
	}
	for _, test := range tests {
		test := test
		t.Run(fmt.Sprintf("Count_%v_Start_%v", test.gameCount, test.earliestGameIdx), func(t *testing.T) {
			blockHash := common.Hash{0xbb, 0xce}
			stubRpc, factory := setupDisputeGameFactoryTest(t)
			var allGames []types.GameMetadata
			for i := 0; i < test.gameCount; i++ {
				allGames = append(allGames, types.GameMetadata{
145
					Index:     uint64(i),
146 147 148 149 150 151
					GameType:  uint32(i),
					Timestamp: uint64(i),
					Proxy:     common.Address{byte(i)},
				})
			}

152
			stubRpc.SetResponse(factoryAddr, methodGameCount, rpcblock.ByHash(blockHash), nil, []interface{}{big.NewInt(int64(len(allGames)))})
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
			for idx, expected := range allGames {
				expectGetGame(stubRpc, idx, blockHash, expected)
			}
			// Set an earliest timestamp that's in the middle of a batch
			earliestTimestamp := uint64(test.earliestGameIdx)
			actualGames, err := factory.GetGamesAtOrAfter(context.Background(), blockHash, earliestTimestamp)
			require.NoError(t, err)
			// Games come back in descending timestamp order
			var expectedGames []types.GameMetadata
			if test.earliestGameIdx < len(allGames) {
				expectedGames = slices.Clone(allGames[test.earliestGameIdx:])
			}
			slices.Reverse(expectedGames)
			require.Equal(t, len(expectedGames), len(actualGames))
			if len(expectedGames) != 0 {
				// Don't assert equal for empty arrays, we accept nil or empty array
				require.Equal(t, expectedGames, actualGames)
			}
		})
	}
}

175 176 177 178 179 180 181 182
func TestGetGameFromParameters(t *testing.T) {
	stubRpc, factory := setupDisputeGameFactoryTest(t)
	traceType := uint32(123)
	outputRoot := common.Hash{0x01}
	l2BlockNum := common.BigToHash(big.NewInt(456)).Bytes()
	stubRpc.SetResponse(
		factoryAddr,
		methodGames,
183
		rpcblock.Latest,
184 185 186 187 188 189 190 191
		[]interface{}{traceType, outputRoot, l2BlockNum},
		[]interface{}{common.Address{0xaa}, uint64(1)},
	)
	addr, err := factory.GetGameFromParameters(context.Background(), traceType, outputRoot, uint64(456))
	require.NoError(t, err)
	require.Equal(t, common.Address{0xaa}, addr)
}

192 193
func TestGetGameImpl(t *testing.T) {
	stubRpc, factory := setupDisputeGameFactoryTest(t)
194
	gameType := faultTypes.CannonGameType
195 196 197
	gameImplAddr := common.Address{0xaa}
	stubRpc.SetResponse(
		factoryAddr,
198
		methodGameImpls,
199
		rpcblock.Latest,
200 201
		[]interface{}{gameType},
		[]interface{}{gameImplAddr})
202
	actual, err := factory.GetGameImpl(context.Background(), faultTypes.CannonGameType)
203 204 205 206
	require.NoError(t, err)
	require.Equal(t, gameImplAddr, actual)
}

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
func TestDecodeDisputeGameCreatedLog(t *testing.T) {
	_, factory := setupDisputeGameFactoryTest(t)
	fdgAbi := snapshots.LoadDisputeGameFactoryABI()
	eventAbi := fdgAbi.Events[eventDisputeGameCreated]
	gameAddr := common.Address{0x11}
	gameType := uint32(4)
	rootClaim := common.Hash{0xaa, 0xbb, 0xcc}

	createValidReceipt := func() *ethTypes.Receipt {
		return &ethTypes.Receipt{
			Status:          ethTypes.ReceiptStatusSuccessful,
			ContractAddress: fdgAddr,
			Logs: []*ethTypes.Log{
				{
					Address: fdgAddr,
					Topics: []common.Hash{
						eventAbi.ID,
						common.BytesToHash(gameAddr.Bytes()),
						common.BytesToHash(big.NewInt(int64(gameType)).Bytes()),
						rootClaim,
					},
				},
			},
		}
	}

	t.Run("IgnoreIncorrectContract", func(t *testing.T) {
		rcpt := createValidReceipt()
		rcpt.Logs[0].Address = common.Address{0xff}
		_, _, _, err := factory.DecodeDisputeGameCreatedLog(rcpt)
		require.ErrorIs(t, err, ErrEventNotFound)
	})

	t.Run("IgnoreInvalidEvent", func(t *testing.T) {
		rcpt := createValidReceipt()
		rcpt.Logs[0].Topics = rcpt.Logs[0].Topics[0:2]
		_, _, _, err := factory.DecodeDisputeGameCreatedLog(rcpt)
		require.ErrorIs(t, err, ErrEventNotFound)
	})

	t.Run("IgnoreWrongEvent", func(t *testing.T) {
		rcpt := createValidReceipt()
		rcpt.Logs[0].Topics = []common.Hash{
			fdgAbi.Events["ImplementationSet"].ID,
			common.BytesToHash(common.Address{0x11}.Bytes()), // Implementation addr
			common.BytesToHash(big.NewInt(4).Bytes()),        // Game type

		}
		// Check the log is a valid ImplementationSet
		name, _, err := factory.contract.DecodeEvent(rcpt.Logs[0])
		require.NoError(t, err)
		require.Equal(t, "ImplementationSet", name)

		_, _, _, err = factory.DecodeDisputeGameCreatedLog(rcpt)
		require.ErrorIs(t, err, ErrEventNotFound)
	})

	t.Run("ValidEvent", func(t *testing.T) {
		rcpt := createValidReceipt()
		actualGameAddr, actualGameType, actualRootClaim, err := factory.DecodeDisputeGameCreatedLog(rcpt)
		require.NoError(t, err)
		require.Equal(t, gameAddr, actualGameAddr)
		require.Equal(t, gameType, actualGameType)
		require.Equal(t, rootClaim, actualRootClaim)
	})
}

274
func expectGetGame(stubRpc *batchingTest.AbiBasedRpc, idx int, blockHash common.Hash, game types.GameMetadata) {
275
	stubRpc.SetResponse(
276
		factoryAddr,
277
		methodGameAtIndex,
278
		rpcblock.ByHash(blockHash),
279 280 281 282 283 284 285 286
		[]interface{}{big.NewInt(int64(idx))},
		[]interface{}{
			game.GameType,
			game.Timestamp,
			game.Proxy,
		})
}

287 288 289 290 291
func TestCreateTx(t *testing.T) {
	stubRpc, factory := setupDisputeGameFactoryTest(t)
	traceType := uint32(123)
	outputRoot := common.Hash{0x01}
	l2BlockNum := common.BigToHash(big.NewInt(456)).Bytes()
292 293
	bond := big.NewInt(49284294829)
	stubRpc.SetResponse(factoryAddr, methodInitBonds, rpcblock.Latest, []interface{}{traceType}, []interface{}{bond})
294
	stubRpc.SetResponse(factoryAddr, methodCreateGame, rpcblock.Latest, []interface{}{traceType, outputRoot, l2BlockNum}, nil)
295
	tx, err := factory.CreateTx(context.Background(), traceType, outputRoot, uint64(456))
296 297
	require.NoError(t, err)
	stubRpc.VerifyTxCandidate(tx)
298 299
	require.NotNil(t, tx.Value)
	require.Truef(t, bond.Cmp(tx.Value) == 0, "Expected bond %v but was %v", bond, tx.Value)
300 301
}

302
func setupDisputeGameFactoryTest(t *testing.T) (*batchingTest.AbiBasedRpc, *DisputeGameFactoryContract) {
303
	fdgAbi := snapshots.LoadDisputeGameFactoryABI()
304

305
	stubRpc := batchingTest.NewAbiBasedRpc(t, factoryAddr, fdgAbi)
306
	caller := batching.NewMultiCaller(stubRpc, batchSize)
307
	factory := NewDisputeGameFactoryContract(metrics.NoopContractMetrics, factoryAddr, caller)
308 309
	return stubRpc, factory
}