differential-testing.go 17.2 KB
Newer Older
1 2 3
package main

import (
4
	"bytes"
5 6 7
	"fmt"
	"math/big"
	"os"
8
	"strconv"
9 10 11 12

	"github.com/ethereum/go-ethereum/accounts/abi"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
13
	"github.com/ethereum/go-ethereum/core/rawdb"
14 15
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
16
	"github.com/ethereum/go-ethereum/trie"
17 18
	"github.com/ethereum/go-ethereum/triedb"
	"github.com/ethereum/go-ethereum/triedb/hashdb"
19

20
	"github.com/ethereum-optimism/optimism/cannon/mipsevm/arch"
21 22 23 24
	"github.com/ethereum-optimism/optimism/cannon/mipsevm/memory"
	"github.com/ethereum-optimism/optimism/op-chain-ops/crossdomain"
	"github.com/ethereum-optimism/optimism/op-service/eth"
	"github.com/ethereum-optimism/optimism/op-service/predeploys"
25 26 27 28
)

// ABI types
var (
29 30 31 32
	// Plain dynamic dynBytes type
	dynBytes, _ = abi.NewType("bytes", "", nil)
	bytesArgs   = abi.Arguments{
		{Type: dynBytes},
33 34 35
	}

	// Plain fixed bytes32 type
36
	fixedBytes, _  = abi.NewType("bytes32", "", nil)
37 38 39 40
	fixedBytesArgs = abi.Arguments{
		{Type: fixedBytes},
	}

41 42
	uint32Type, _ = abi.NewType("uint32", "", nil)

43 44 45 46 47 48 49 50 51
	// Plain address type
	addressType, _ = abi.NewType("address", "", nil)

	// Plain uint8 type
	uint8Type, _ = abi.NewType("uint8", "", nil)

	// Plain uint256 type
	uint256Type, _ = abi.NewType("uint256", "", nil)

52 53 54 55 56 57
	// Decoded nonce tuple (nonce, version)
	decodedNonce, _ = abi.NewType("tuple", "DecodedNonce", []abi.ArgumentMarshaling{
		{Name: "nonce", Type: "uint256"},
		{Name: "version", Type: "uint256"},
	})
	decodedNonceArgs = abi.Arguments{
58
		{Name: "encodedNonce", Type: decodedNonce},
59 60
	}

61 62 63 64 65 66
	// Decoded ecotone scalars (uint32, uint32)
	decodedScalars = abi.Arguments{
		{Name: "basefeeScalar", Type: uint32Type},
		{Name: "blobbasefeeScalar", Type: uint32Type},
	}

67
	// WithdrawalHash slot tuple (bytes32, bytes32)
68
	withdrawalSlot, _ = abi.NewType("tuple", "SlotHash", []abi.ArgumentMarshaling{
69 70 71 72 73 74 75 76 77 78
		{Name: "withdrawalHash", Type: "bytes32"},
		{Name: "zeroPadding", Type: "bytes32"},
	})
	withdrawalSlotArgs = abi.Arguments{
		{Name: "slotHash", Type: withdrawalSlot},
	}

	// Prove withdrawal inputs tuple (bytes32, bytes32, bytes32, bytes32, bytes[])
	proveWithdrawalInputs, _ = abi.NewType("tuple", "ProveWithdrawalInputs", []abi.ArgumentMarshaling{
		{Name: "worldRoot", Type: "bytes32"},
79
		{Name: "stateRoot", Type: "bytes32"},
80 81 82 83 84 85 86
		{Name: "outputRoot", Type: "bytes32"},
		{Name: "withdrawalHash", Type: "bytes32"},
		{Name: "proof", Type: "bytes[]"},
	})
	proveWithdrawalInputsArgs = abi.Arguments{
		{Name: "inputs", Type: proveWithdrawalInputs},
	}
87 88 89 90 91 92 93 94 95

	// cannonMemoryProof inputs tuple (bytes32, bytes)
	cannonMemoryProof, _ = abi.NewType("tuple", "CannonMemoryProof", []abi.ArgumentMarshaling{
		{Name: "memRoot", Type: "bytes32"},
		{Name: "proof", Type: "bytes"},
	})
	cannonMemoryProofArgs = abi.Arguments{
		{Name: "encodedCannonMemoryProof", Type: cannonMemoryProof},
	}
96 97 98 99 100 101 102 103 104 105 106

	// Gas paying token tuple (address, uint8, bytes32, bytes32)
	gasPayingTokenArgs = abi.Arguments{
		{Name: "token", Type: addressType},
		{Name: "decimals", Type: uint8Type},
		{Name: "name", Type: fixedBytes},
		{Name: "symbol", Type: fixedBytes},
	}

	// Dependency tuple (uint256)
	dependencyArgs = abi.Arguments{{Name: "chainId", Type: uint256Type}}
107 108
)

clabby's avatar
clabby committed
109 110
func DiffTestUtils() {
	args := os.Args[2:]
clabby's avatar
clabby committed
111
	variant := args[0]
112 113 114 115 116 117

	// This command requires arguments
	if len(args) == 0 {
		panic("Error: No arguments provided")
	}

clabby's avatar
clabby committed
118
	switch variant {
119
	case "decodeVersionedNonce":
120
		// Parse input arguments
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
		input, ok := new(big.Int).SetString(args[1], 10)
		checkOk(ok)

		// Decode versioned nonce
		nonce, version := crossdomain.DecodeVersionedNonce(input)

		// ABI encode output
		packArgs := struct {
			Nonce   *big.Int
			Version *big.Int
		}{
			nonce,
			version,
		}
		packed, err := decodedNonceArgs.Pack(&packArgs)
136
		checkErr(err, "Error encoding output")
137 138 139

		fmt.Print(hexutil.Encode(packed))
	case "encodeCrossDomainMessage":
140
		// Parse input arguments
141 142 143 144 145 146 147 148
		nonce, ok := new(big.Int).SetString(args[1], 10)
		checkOk(ok)
		sender := common.HexToAddress(args[2])
		target := common.HexToAddress(args[3])
		value, ok := new(big.Int).SetString(args[4], 10)
		checkOk(ok)
		gasLimit, ok := new(big.Int).SetString(args[5], 10)
		checkOk(ok)
clabby's avatar
clabby committed
149
		data := common.FromHex(args[6])
150 151 152

		// Encode cross domain message
		encoded, err := encodeCrossDomainMessage(nonce, sender, target, value, gasLimit, data)
153
		checkErr(err, "Error encoding cross domain message")
154 155 156

		// Pack encoded cross domain message
		packed, err := bytesArgs.Pack(&encoded)
157
		checkErr(err, "Error encoding output")
158 159 160 161 162 163 164 165 166 167 168 169

		fmt.Print(hexutil.Encode(packed))
	case "hashCrossDomainMessage":
		// Parse input arguments
		nonce, ok := new(big.Int).SetString(args[1], 10)
		checkOk(ok)
		sender := common.HexToAddress(args[2])
		target := common.HexToAddress(args[3])
		value, ok := new(big.Int).SetString(args[4], 10)
		checkOk(ok)
		gasLimit, ok := new(big.Int).SetString(args[5], 10)
		checkOk(ok)
clabby's avatar
clabby committed
170
		data := common.FromHex(args[6])
171 172 173

		// Encode cross domain message
		encoded, err := encodeCrossDomainMessage(nonce, sender, target, value, gasLimit, data)
174
		checkErr(err, "Error encoding cross domain message")
175 176 177 178 179 180

		// Hash encoded cross domain message
		hash := crypto.Keccak256Hash(encoded)

		// Pack hash
		packed, err := fixedBytesArgs.Pack(&hash)
181
		checkErr(err, "Error encoding output")
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

		fmt.Print(hexutil.Encode(packed))
	case "hashDepositTransaction":
		// Parse input arguments
		l1BlockHash := common.HexToHash(args[1])
		logIndex, ok := new(big.Int).SetString(args[2], 10)
		checkOk(ok)
		from := common.HexToAddress(args[3])
		to := common.HexToAddress(args[4])
		mint, ok := new(big.Int).SetString(args[5], 10)
		checkOk(ok)
		value, ok := new(big.Int).SetString(args[6], 10)
		checkOk(ok)
		gasLimit, ok := new(big.Int).SetString(args[7], 10)
		checkOk(ok)
		data := common.FromHex(args[8])

		// Create deposit transaction
		depositTx := makeDepositTx(from, to, value, mint, gasLimit, false, data, l1BlockHash, logIndex)

		// RLP encode deposit transaction
		encoded, err := types.NewTx(&depositTx).MarshalBinary()
204
		checkErr(err, "Error encoding deposit transaction")
205 206 207 208 209 210

		// Hash encoded deposit transaction
		hash := crypto.Keccak256Hash(encoded)

		// Pack hash
		packed, err := fixedBytesArgs.Pack(&hash)
211
		checkErr(err, "Error encoding output")
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

		fmt.Print(hexutil.Encode(packed))
	case "encodeDepositTransaction":
		// Parse input arguments
		from := common.HexToAddress(args[1])
		to := common.HexToAddress(args[2])
		value, ok := new(big.Int).SetString(args[3], 10)
		checkOk(ok)
		mint, ok := new(big.Int).SetString(args[4], 10)
		checkOk(ok)
		gasLimit, ok := new(big.Int).SetString(args[5], 10)
		checkOk(ok)
		isCreate := args[6] == "true"
		data := common.FromHex(args[7])
		l1BlockHash := common.HexToHash(args[8])
		logIndex, ok := new(big.Int).SetString(args[9], 10)
		checkOk(ok)

		depositTx := makeDepositTx(from, to, value, mint, gasLimit, isCreate, data, l1BlockHash, logIndex)

		// RLP encode deposit transaction
		encoded, err := types.NewTx(&depositTx).MarshalBinary()
234
		checkErr(err, "Failed to RLP encode deposit transaction")
235 236
		// Pack rlp encoded deposit transaction
		packed, err := bytesArgs.Pack(&encoded)
237
		checkErr(err, "Error encoding output")
238 239 240 241 242 243 244 245 246 247 248 249 250 251

		fmt.Print(hexutil.Encode(packed))
	case "hashWithdrawal":
		// Parse input arguments
		nonce, ok := new(big.Int).SetString(args[1], 10)
		checkOk(ok)
		sender := common.HexToAddress(args[2])
		target := common.HexToAddress(args[3])
		value, ok := new(big.Int).SetString(args[4], 10)
		checkOk(ok)
		gasLimit, ok := new(big.Int).SetString(args[5], 10)
		checkOk(ok)
		data := common.FromHex(args[6])

252 253
		// Hash withdrawal
		hash, err := hashWithdrawal(nonce, sender, target, value, gasLimit, data)
254
		checkErr(err, "Error hashing withdrawal")
255 256

		// Pack hash
257
		packed, err := fixedBytesArgs.Pack(&hash)
258
		checkErr(err, "Error encoding output")
259 260 261 262 263 264 265 266 267

		fmt.Print(hexutil.Encode(packed))
	case "hashOutputRootProof":
		// Parse input arguments
		version := common.HexToHash(args[1])
		stateRoot := common.HexToHash(args[2])
		messagePasserStorageRoot := common.HexToHash(args[3])
		latestBlockHash := common.HexToHash(args[4])

268
		// Hash the output root proof
269 270
		hash, err := hashOutputRootProof(version, stateRoot, messagePasserStorageRoot, latestBlockHash)
		checkErr(err, "Error hashing output root proof")
271 272

		// Pack hash
273
		packed, err := fixedBytesArgs.Pack(&hash)
274
		checkErr(err, "Error encoding output")
275 276 277

		fmt.Print(hexutil.Encode(packed))
	case "getProveWithdrawalTransactionInputs":
278 279 280 281 282 283 284 285 286 287 288 289
		// Parse input arguments
		nonce, ok := new(big.Int).SetString(args[1], 10)
		checkOk(ok)
		sender := common.HexToAddress(args[2])
		target := common.HexToAddress(args[3])
		value, ok := new(big.Int).SetString(args[4], 10)
		checkOk(ok)
		gasLimit, ok := new(big.Int).SetString(args[5], 10)
		checkOk(ok)
		data := common.FromHex(args[6])

		wdHash, err := hashWithdrawal(nonce, sender, target, value, gasLimit, data)
290
		checkErr(err, "Error hashing withdrawal")
291 292 293 294 295 296 297 298 299 300

		// Compute the storage slot the withdrawalHash will be stored in
		slot := struct {
			WithdrawalHash common.Hash
			ZeroPadding    common.Hash
		}{
			WithdrawalHash: wdHash,
			ZeroPadding:    common.Hash{},
		}
		packed, err := withdrawalSlotArgs.Pack(&slot)
301
		checkErr(err, "Error packing withdrawal slot")
302 303 304 305

		// Compute the storage slot the withdrawalHash will be stored in
		hash := crypto.Keccak256Hash(packed)

306 307 308
		// Create a secure trie for state
		state, err := trie.NewStateTrie(
			trie.TrieID(types.EmptyRootHash),
309
			triedb.NewDatabase(rawdb.NewMemoryDatabase(), &triedb.Config{HashDB: hashdb.Defaults}),
310
		)
311
		checkErr(err, "Error creating secure trie")
312 313

		// Put a "true" bool in the storage slot
314 315
		err = state.UpdateStorage(common.Address{}, hash.Bytes(), []byte{0x01})
		checkErr(err, "Error updating storage")
316 317 318

		// Create a secure trie for the world state
		world, err := trie.NewStateTrie(
319
			trie.TrieID(types.EmptyRootHash),
320
			triedb.NewDatabase(rawdb.NewMemoryDatabase(), &triedb.Config{HashDB: hashdb.Defaults}),
321
		)
322
		checkErr(err, "Error creating secure trie")
323

324
		// Put the put the rlp encoded account in the world trie
325 326
		account := types.StateAccount{
			Nonce:   0,
327
			Balance: common.U2560,
328
			Root:    state.Hash(),
329 330
		}
		writer := new(bytes.Buffer)
331
		checkErr(account.EncodeRLP(writer), "Error encoding account")
332 333
		err = world.UpdateStorage(common.Address{}, predeploys.L2ToL1MessagePasserAddr.Bytes(), writer.Bytes())
		checkErr(err, "Error updating storage")
334 335 336

		// Get the proof
		var proof proofList
337
		checkErr(state.Prove(predeploys.L2ToL1MessagePasserAddr.Bytes(), &proof), "Error getting proof")
338 339

		// Get the output root
340 341
		outputRoot, err := hashOutputRootProof(common.Hash{}, world.Hash(), state.Hash(), common.Hash{})
		checkErr(err, "Error hashing output root proof")
342 343 344 345

		// Pack the output
		output := struct {
			WorldRoot      common.Hash
346
			StateRoot      common.Hash
347 348
			OutputRoot     common.Hash
			WithdrawalHash common.Hash
349
			Proof          proofList
350 351
		}{
			WorldRoot:      world.Hash(),
352
			StateRoot:      state.Hash(),
353 354 355 356 357
			OutputRoot:     outputRoot,
			WithdrawalHash: wdHash,
			Proof:          proof,
		}
		packed, err = proveWithdrawalInputsArgs.Pack(&output)
358
		checkErr(err, "Error encoding output")
359 360 361

		// Print the output
		fmt.Print(hexutil.Encode(packed[32:]))
362
	case "cannonMemoryProof":
363 364 365
		// <memAddr0, memValue0, [memAddr1, memValue1], [memAddr2, memValue2]>
		// Generates memory proofs of `memAddr0` for a trie containing memValue0 and `memAddr1` for a trie containing memValue1 and memValue2
		// For the cannon stf, this is equivalent to the prestate proofs of the program counter and memory access for instruction execution
366
		mem := memory.NewMemory()
367 368
		if len(args) != 3 && len(args) != 5 && len(args) != 7 {
			panic("Error: cannonMemoryProofWithProof requires 2, 4, or 6 arguments")
369
		}
370
		memAddr0, err := strconv.ParseUint(args[1], 10, arch.WordSize)
371
		checkErr(err, "Error decoding addr")
372 373 374
		memValue0, err := strconv.ParseUint(args[2], 10, arch.WordSize)
		checkErr(err, "Error decoding memValue0")
		mem.SetWord(arch.Word(memAddr0), arch.Word(memValue0))
375

376
		var proof1 []byte
377
		if len(args) >= 5 {
378
			memAddr, err := strconv.ParseUint(args[3], 10, arch.WordSize)
379
			checkErr(err, "Error decoding memAddr")
380
			memValue, err := strconv.ParseUint(args[4], 10, arch.WordSize)
381
			checkErr(err, "Error decoding memValue")
382
			mem.SetWord(arch.Word(memAddr), arch.Word(memValue))
383 384
			proof := mem.MerkleProof(arch.Word(memAddr))
			proof1 = proof[:]
385
		}
386
		if len(args) == 7 {
387
			memAddr, err := strconv.ParseUint(args[5], 10, arch.WordSize)
388
			checkErr(err, "Error decoding memAddr")
389
			memValue, err := strconv.ParseUint(args[6], 10, arch.WordSize)
390
			checkErr(err, "Error decoding memValue")
391
			mem.SetWord(arch.Word(memAddr), arch.Word(memValue))
392 393
			proof := mem.MerkleProof(arch.Word(memAddr))
			proof1 = proof[:]
394
		}
395
		proof0 := mem.MerkleProof(arch.Word(memAddr0))
396

397 398 399 400 401
		output := struct {
			MemRoot common.Hash
			Proof   []byte
		}{
			MemRoot: mem.MerkleRoot(),
402
			Proof:   append(proof0[:], proof1...),
403 404
		}
		packed, err := cannonMemoryProofArgs.Pack(&output)
405 406 407
		checkErr(err, "Error encoding output")
		fmt.Print(hexutil.Encode(packed[32:]))
	case "cannonMemoryProof2":
408 409
		// <memAddr0, memValue0, [memAddr1, memValue1], memAddr2>
		// Generates memory proof of `memAddr2` for a trie containing `memValue0` and `memValue1`
410 411 412 413
		mem := memory.NewMemory()
		if len(args) != 6 {
			panic("Error: cannonMemoryProofWithProof2 requires 5 arguments")
		}
414
		memAddr0, err := strconv.ParseUint(args[1], 10, arch.WordSize)
415
		checkErr(err, "Error decoding addr")
416 417 418
		memValue0, err := strconv.ParseUint(args[2], 10, arch.WordSize)
		checkErr(err, "Error decoding memValue0")
		mem.SetWord(arch.Word(memAddr0), arch.Word(memValue0))
419

420 421
		var memProof [memory.MemProofSize]byte
		memAddr, err := strconv.ParseUint(args[3], 10, arch.WordSize)
422
		checkErr(err, "Error decoding memAddr")
423 424 425
		memValue1, err := strconv.ParseUint(args[4], 10, arch.WordSize)
		checkErr(err, "Error decoding memValue1")
		mem.SetWord(arch.Word(memAddr), arch.Word(memValue1))
426

427
		memAddr2, err := strconv.ParseUint(args[5], 10, arch.WordSize)
428
		checkErr(err, "Error decoding memAddr")
429
		memProof = mem.MerkleProof(arch.Word(memAddr2))
430 431 432 433 434 435 436 437 438

		output := struct {
			MemRoot common.Hash
			Proof   []byte
		}{
			MemRoot: mem.MerkleRoot(),
			Proof:   memProof[:],
		}
		packed, err := cannonMemoryProofArgs.Pack(&output)
439 440 441
		checkErr(err, "Error encoding output")
		fmt.Print(hexutil.Encode(packed[32:]))
	case "cannonMemoryProofWrongLeaf":
442
		// <memAddr0, memValue0, memAddr1, memValue1>
443
		mem := memory.NewMemory()
444 445 446
		if len(args) != 5 {
			panic("Error: cannonMemoryProofWrongLeaf requires 4 arguments")
		}
447 448 449 450 451 452 453 454 455 456 457 458
		memAddr0, err := strconv.ParseUint(args[1], 10, arch.WordSize)
		checkErr(err, "Error decoding memAddr0")
		memValue0, err := strconv.ParseUint(args[2], 10, arch.WordSize)
		checkErr(err, "Error decoding memValue0")
		mem.SetWord(arch.Word(memAddr0), arch.Word(memValue0))

		var insnProof, memProof [memory.MemProofSize]byte
		memAddr1, err := strconv.ParseUint(args[3], 10, arch.WordSize)
		checkErr(err, "Error decoding memAddr1")
		memValue1, err := strconv.ParseUint(args[4], 10, arch.WordSize)
		checkErr(err, "Error decoding memValue1")
		mem.SetWord(arch.Word(memAddr1), arch.Word(memValue1))
459 460

		// Compute a valid proof for the root, but for the wrong leaves.
461 462
		memProof = mem.MerkleProof(arch.Word(memAddr1 + arch.WordSize))
		insnProof = mem.MerkleProof(arch.Word(memAddr0 + arch.WordSize))
463

464 465 466 467 468 469 470 471 472 473
		output := struct {
			MemRoot common.Hash
			Proof   []byte
		}{
			MemRoot: mem.MerkleRoot(),
			Proof:   append(insnProof[:], memProof[:]...),
		}
		packed, err := cannonMemoryProofArgs.Pack(&output)
		checkErr(err, "Error encoding output")
		fmt.Print(hexutil.Encode(packed[32:]))
474 475
	case "encodeScalarEcotone":
		basefeeScalar, err := strconv.ParseUint(args[1], 10, 32)
476
		checkErr(err, "Error decoding basefeeScalar")
477
		blobbasefeeScalar, err := strconv.ParseUint(args[2], 10, 32)
478
		checkErr(err, "Error decoding blobbasefeeScalar")
479 480 481 482 483 484 485 486 487 488 489 490 491

		encoded := eth.EncodeScalar(eth.EcotoneScalars{
			BaseFeeScalar:     uint32(basefeeScalar),
			BlobBaseFeeScalar: uint32(blobbasefeeScalar),
		})
		fmt.Print(hexutil.Encode(encoded[:]))
	case "decodeScalarEcotone":
		scalar := common.HexToHash(args[1])
		scalars, err := eth.DecodeScalar([32]byte(scalar[:]))
		checkErr(err, "Error decoding scalar")

		packed, err := decodedScalars.Pack(scalars.BaseFeeScalar, scalars.BlobBaseFeeScalar)
		checkErr(err, "Error encoding output")
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
		fmt.Print(hexutil.Encode(packed))
	case "encodeGasPayingToken":
		// Parse input arguments
		token := common.HexToAddress(args[1])
		decimals, err := strconv.ParseUint(args[2], 10, 8)
		checkErr(err, "Error decoding decimals")
		name := common.HexToHash(args[3])
		symbol := common.HexToHash(args[4])

		// Encode gas paying token
		encoded, err := gasPayingTokenArgs.Pack(token, uint8(decimals), name, symbol)
		checkErr(err, "Error encoding gas paying token")

		// Pack encoded gas paying token
		packed, err := bytesArgs.Pack(&encoded)
		checkErr(err, "Error encoding output")

		fmt.Print(hexutil.Encode(packed))
	case "encodeDependency":
		// Parse input arguments
		chainId, ok := new(big.Int).SetString(args[1], 10)
		checkOk(ok)

		// Encode dependency
		encoded, err := dependencyArgs.Pack(chainId)
		checkErr(err, "Error encoding dependency")

		// Pack encoded dependency
		packed, err := bytesArgs.Pack(&encoded)
		checkErr(err, "Error encoding output")

523
		fmt.Print(hexutil.Encode(packed))
524 525 526 527
	default:
		panic(fmt.Errorf("Unknown command: %s", args[0]))
	}
}