test-runner.ts 17.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import { expect } from '../../setup'

/* External Imports */
import { ethers } from 'hardhat'
import { Contract, BigNumber, ContractFactory } from 'ethers'
import { cloneDeep, merge } from 'lodash'
import { smoddit, smockit, ModifiableContract } from '@eth-optimism/smock'

/* Internal Imports */
import {
  TestDefinition,
  ParsedTestStep,
  TestParameter,
  TestStep,
15
  TestStep_CALLType,
16 17 18 19
  TestStep_Run,
  isRevertFlagError,
  isTestStep_SSTORE,
  isTestStep_SLOAD,
20
  isTestStep_CALLType,
21 22 23 24 25 26 27 28 29
  isTestStep_CREATE,
  isTestStep_CREATE2,
  isTestStep_CREATEEOA,
  isTestStep_Context,
  isTestStep_evm,
  isTestStep_Run,
  isTestStep_EXTCODESIZE,
  isTestStep_EXTCODEHASH,
  isTestStep_EXTCODECOPY,
30
  isTestStep_BALANCE,
31
  isTestStep_REVERT,
32
  isTestStep_CALL,
33 34 35 36 37 38 39 40 41
} from './test.types'
import { encodeRevertData, REVERT_FLAGS } from '../codec'
import {
  OVM_TX_GAS_LIMIT,
  RUN_OVM_TEST_GAS,
  NON_NULL_BYTES32,
} from '../constants'
import { getStorageXOR } from '../'
import { UNSAFE_BYTECODE } from '../dummy'
42
import { getContractFactory, predeploys } from '../../../src'
43 44 45 46 47 48 49 50 51 52

export class ExecutionManagerTestRunner {
  private snapshot: string
  private contracts: {
    OVM_SafetyChecker: Contract
    OVM_StateManager: ModifiableContract
    OVM_ExecutionManager: ModifiableContract
    Helper_TestRunner: Contract
    Factory__Helper_TestRunner_CREATE: ContractFactory
    OVM_DeployerWhitelist: Contract
53
    OVM_ProxyEOA: Contract
54
    OVM_ETH: Contract
55 56 57 58 59 60 61
  } = {
    OVM_SafetyChecker: undefined,
    OVM_StateManager: undefined,
    OVM_ExecutionManager: undefined,
    Helper_TestRunner: undefined,
    Factory__Helper_TestRunner_CREATE: undefined,
    OVM_DeployerWhitelist: undefined,
62
    OVM_ProxyEOA: undefined,
63
    OVM_ETH: undefined,
64 65 66 67 68 69 70
  }

  // Default pre-state with contract deployer whitelist NOT initialized.
  private defaultPreState = {
    StateManager: {
      owner: '$OVM_EXECUTION_MANAGER',
      accounts: {
71
        [predeploys.OVM_DeployerWhitelist]: {
72 73 74
          codeHash: NON_NULL_BYTES32,
          ethAddress: '$OVM_DEPLOYER_WHITELIST',
        },
75 76 77 78
        [predeploys.OVM_ETH]: {
          codeHash: NON_NULL_BYTES32,
          ethAddress: '$OVM_ETH',
        },
79
        [predeploys.OVM_ProxyEOA]: {
80 81 82
          codeHash: NON_NULL_BYTES32,
          ethAddress: '$OVM_PROXY_EOA',
        },
83 84
      },
      contractStorage: {
85
        [predeploys.OVM_DeployerWhitelist]: {
86 87 88 89 90
          '0x0000000000000000000000000000000000000000000000000000000000000000':
            {
              getStorageXOR: true,
              value: ethers.constants.HashZero,
            },
91 92 93
        },
      },
      verifiedContractStorage: {
94
        [predeploys.OVM_DeployerWhitelist]: {
95 96
          '0x0000000000000000000000000000000000000000000000000000000000000000':
            true,
97 98 99
        },
      },
    },
100 101 102 103 104
    ExecutionManager: {
      transactionRecord: {
        ovmGasRefund: 0,
      },
    },
105 106 107 108 109 110
  }

  public run(test: TestDefinition) {
    ;(test.preState = merge(
      cloneDeep(this.defaultPreState),
      cloneDeep(test.preState)
111
      // eslint-disable-next-line no-sequences
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
    )),
      (test.postState = test.postState || {})

    describe(`OVM_ExecutionManager Test: ${test.name}`, () => {
      test.subTests?.map((subTest) => {
        this.run({
          ...subTest,
          preState: merge(
            cloneDeep(test.preState),
            cloneDeep(subTest.preState)
          ),
          postState: merge(
            cloneDeep(test.postState),
            cloneDeep(subTest.postState)
          ),
        })
      })

      test.parameters?.map((parameter) => {
        beforeEach(async () => {
          await this.initContracts()
        })

        let replacedTest: TestDefinition
        let replacedParameter: TestParameter
        beforeEach(async () => {
          replacedTest = this.setPlaceholderStrings(test)
          replacedParameter = this.setPlaceholderStrings(parameter)
        })

142 143
        beforeEach(async () => {
          await this.contracts.OVM_StateManager.smodify.put({
144 145 146 147 148 149 150 151 152 153
            accounts: {
              [this.contracts.Helper_TestRunner.address]: {
                nonce: 0,
                codeHash: NON_NULL_BYTES32,
                ethAddress: this.contracts.Helper_TestRunner.address,
              },
            },
          })
        })

154 155
        beforeEach(async () => {
          await this.contracts.OVM_ExecutionManager.smodify.put(
156 157
            replacedTest.preState.ExecutionManager
          )
158
          await this.contracts.OVM_StateManager.smodify.put(
159 160 161 162 163 164 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
            replacedTest.preState.StateManager
          )
        })

        afterEach(async () => {
          expect(
            await this.contracts.OVM_ExecutionManager.smodify.check(
              replacedTest.postState.ExecutionManager
            )
          ).to.equal(true)

          expect(
            await this.contracts.OVM_StateManager.smodify.check(
              replacedTest.postState.StateManager
            )
          ).to.equal(true)
        })

        let itfn: any = it
        if (parameter.focus) {
          itfn = it.only
        } else if (parameter.skip) {
          itfn = it.skip
        }

        itfn(`should execute: ${parameter.name}`, async () => {
          try {
            for (const step of replacedParameter.steps) {
              await this.runTestStep(step)
            }
          } catch (err) {
            if (parameter.expectInvalidStateAccess) {
              expect(err.toString()).to.contain(
                'VM Exception while processing transaction: revert'
              )
            } else {
              throw err
            }
          }
        })
      })
    })
  }

  private async initContracts() {
    if (this.snapshot) {
      await ethers.provider.send('evm_revert', [this.snapshot])
      this.snapshot = await ethers.provider.send('evm_snapshot', [])
      return
    }

    const AddressManager = await (
      await ethers.getContractFactory('Lib_AddressManager')
    ).deploy()

    const SafetyChecker = await (
      await ethers.getContractFactory('OVM_SafetyChecker')
    ).deploy()

    const MockSafetyChecker = await smockit(SafetyChecker)
    MockSafetyChecker.smocked.isBytecodeSafe.will.return.with(
      (bytecode: string) => {
        return bytecode !== UNSAFE_BYTECODE
      }
    )

    this.contracts.OVM_SafetyChecker = MockSafetyChecker

    await AddressManager.setAddress(
      'OVM_SafetyChecker',
      this.contracts.OVM_SafetyChecker.address
    )

232 233 234 235
    const DeployerWhitelist = await getContractFactory(
      'OVM_DeployerWhitelist',
      AddressManager.signer,
      true
236 237 238 239
    ).deploy()

    this.contracts.OVM_DeployerWhitelist = DeployerWhitelist

240 241 242 243
    const OvmEth = await getContractFactory(
      'OVM_ETH',
      AddressManager.signer,
      true
244
    ).deploy()
245 246 247

    this.contracts.OVM_ETH = OvmEth

248 249 250 251 252 253
    this.contracts.OVM_ProxyEOA = await getContractFactory(
      'OVM_ProxyEOA',
      AddressManager.signer,
      true
    ).deploy()

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
    this.contracts.OVM_ExecutionManager = await (
      await smoddit('OVM_ExecutionManager')
    ).deploy(
      AddressManager.address,
      {
        minTransactionGasLimit: 0,
        maxTransactionGasLimit: 1_000_000_000,
        maxGasPerQueuePerEpoch: 1_000_000_000_000,
        secondsPerEpoch: 600,
      },
      {
        ovmCHAINID: 420,
      }
    )

    this.contracts.OVM_StateManager = await (
      await smoddit('OVM_StateManager')
    ).deploy(await this.contracts.OVM_ExecutionManager.signer.getAddress())
    await this.contracts.OVM_StateManager.setExecutionManager(
      this.contracts.OVM_ExecutionManager.address
    )

    this.contracts.Helper_TestRunner = await (
      await ethers.getContractFactory('Helper_TestRunner')
    ).deploy()

280 281
    this.contracts.Factory__Helper_TestRunner_CREATE =
      await ethers.getContractFactory('Helper_TestRunner_CREATE')
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

    this.snapshot = await ethers.provider.send('evm_snapshot', [])
  }

  public static getDummyAddress(placeholder: string): string {
    return '0x' + (placeholder.split('$DUMMY_OVM_ADDRESS_')[1] + '0').repeat(20)
  }

  private setPlaceholderStrings(obj: any) {
    const getReplacementString = (kv: string): string => {
      if (kv === '$OVM_EXECUTION_MANAGER') {
        return this.contracts.OVM_ExecutionManager.address
      } else if (kv === '$OVM_STATE_MANAGER') {
        return this.contracts.OVM_StateManager.address
      } else if (kv === '$OVM_SAFETY_CHECKER') {
        return this.contracts.OVM_SafetyChecker.address
      } else if (kv === '$OVM_CALL_HELPER') {
        return this.contracts.Helper_TestRunner.address
      } else if (kv === '$OVM_DEPLOYER_WHITELIST') {
        return this.contracts.OVM_DeployerWhitelist.address
302 303
      } else if (kv === '$OVM_ETH') {
        return this.contracts.OVM_ETH.address
304 305
      } else if (kv === '$OVM_PROXY_EOA') {
        return this.contracts.OVM_ProxyEOA.address
306 307 308 309 310 311 312 313 314 315 316 317 318
      } else if (kv.startsWith('$DUMMY_OVM_ADDRESS_')) {
        return ExecutionManagerTestRunner.getDummyAddress(kv)
      } else {
        return kv
      }
    }

    let ret: any = cloneDeep(obj)
    if (Array.isArray(ret)) {
      ret = ret.map((element: any) => {
        return this.setPlaceholderStrings(element)
      })
    } else if (typeof ret === 'object' && ret !== null) {
319 320 321 322 323 324 325 326
      if (ret.getStorageXOR) {
        // Special case allowing us to set prestate with an object which will be
        // padded to 32 bytes and XORd with STORAGE_XOR_VALUE
        return getStorageXOR(
          ethers.utils.hexZeroPad(getReplacementString(ret.value), 32)
        )
      }

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
      for (const key of Object.keys(ret)) {
        const replacedKey = getReplacementString(key)

        if (replacedKey !== key) {
          ret[replacedKey] = ret[key]
          delete ret[key]
        }

        ret[replacedKey] = this.setPlaceholderStrings(ret[replacedKey])
      }
    } else if (typeof ret === 'string') {
      ret = getReplacementString(ret)
    }

    return ret
  }

  private async runTestStep(step: TestStep | TestStep_Run) {
    if (isTestStep_Run(step)) {
      let calldata: string
      if (step.functionParams.data) {
        calldata = step.functionParams.data
      } else {
350
        const runStep: TestStep_CALLType = {
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
          functionName: 'ovmCALL',
          functionParams: {
            gasLimit: OVM_TX_GAS_LIMIT,
            target: ExecutionManagerTestRunner.getDummyAddress(
              '$DUMMY_OVM_ADDRESS_1'
            ),
            subSteps: step.functionParams.subSteps,
          },
          expectedReturnStatus: true,
        }

        calldata = this.encodeFunctionData(runStep)
      }

      const toRun = this.contracts.OVM_ExecutionManager.run(
        {
          timestamp: step.functionParams.timestamp,
          blockNumber: 0,
          l1QueueOrigin: step.functionParams.queueOrigin,
          l1TxOrigin: step.functionParams.origin,
          entrypoint: step.functionParams.entrypoint,
          gasLimit: step.functionParams.gasLimit,
          data: calldata,
        },
        this.contracts.OVM_StateManager.address,
        { gasLimit: step.suppliedGas || RUN_OVM_TEST_GAS }
      )
      if (!!step.expectedRevertValue) {
        await expect(toRun).to.be.revertedWith(step.expectedRevertValue)
      } else {
        await toRun
      }
    } else {
384 385 386
      await this.contracts.OVM_ExecutionManager[
        'ovmCALL(uint256,address,uint256,bytes)'
      ](
387 388
        OVM_TX_GAS_LIMIT,
        ExecutionManagerTestRunner.getDummyAddress('$DUMMY_OVM_ADDRESS_1'),
389
        0,
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
        this.contracts.Helper_TestRunner.interface.encodeFunctionData(
          'runSingleTestStep',
          [this.parseTestStep(step)]
        ),
        { gasLimit: RUN_OVM_TEST_GAS }
      )
    }
  }

  private parseTestStep(step: TestStep): ParsedTestStep {
    return {
      functionName: step.functionName,
      functionData: this.encodeFunctionData(step),
      expectedReturnStatus: this.getReturnStatus(step),
      expectedReturnData: this.encodeExpectedReturnData(step),
      onlyValidateFlag: this.shouldStepOnlyValidateFlag(step),
    }
  }

  private shouldStepOnlyValidateFlag(step: TestStep): boolean {
    if (!!(step as any).expectedReturnValue) {
      if (!!((step as any).expectedReturnValue as any).onlyValidateFlag) {
        return true
      }
    }
    return false
  }

  private getReturnStatus(step: TestStep): boolean {
    if (isTestStep_evm(step)) {
      return false
    } else if (isTestStep_Context(step)) {
      return true
423
    } else if (isTestStep_CALLType(step)) {
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
      if (
        isRevertFlagError(step.expectedReturnValue) &&
        (step.expectedReturnValue.flag === REVERT_FLAGS.INVALID_STATE_ACCESS ||
          step.expectedReturnValue.flag === REVERT_FLAGS.STATIC_VIOLATION ||
          step.expectedReturnValue.flag === REVERT_FLAGS.CREATOR_NOT_ALLOWED)
      ) {
        return step.expectedReturnStatus
      } else {
        return true
      }
    } else {
      return step.expectedReturnStatus
    }
  }

  private encodeFunctionData(step: TestStep): string {
    if (isTestStep_evm(step)) {
      if (isRevertFlagError(step.returnData)) {
        return encodeRevertData(
          step.returnData.flag,
          step.returnData.data,
          step.returnData.nuisanceGasLeft,
          step.returnData.ovmGasRefund
        )
      } else {
        return step.returnData || '0x'
      }
    }

    let functionParams: any[] = []
    if (
      isTestStep_SSTORE(step) ||
      isTestStep_SLOAD(step) ||
      isTestStep_EXTCODESIZE(step) ||
      isTestStep_EXTCODEHASH(step) ||
      isTestStep_EXTCODECOPY(step) ||
460
      isTestStep_BALANCE(step) ||
461 462 463
      isTestStep_CREATEEOA(step)
    ) {
      functionParams = Object.values(step.functionParams)
464 465
    } else if (isTestStep_CALLType(step)) {
      const innnerCalldata =
466
        step.functionParams.calldata ||
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
        this.contracts.Helper_TestRunner.interface.encodeFunctionData(
          'runMultipleTestSteps',
          [
            step.functionParams.subSteps.map((subStep) => {
              return this.parseTestStep(subStep)
            }),
          ]
        )
      // only ovmCALL accepts a value parameter.
      if (isTestStep_CALL(step)) {
        functionParams = [
          step.functionParams.gasLimit,
          step.functionParams.target,
          step.functionParams.value || 0,
          innnerCalldata,
        ]
      } else {
        functionParams = [
          step.functionParams.gasLimit,
          step.functionParams.target,
          innnerCalldata,
        ]
      }
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
    } else if (isTestStep_CREATE(step)) {
      functionParams = [
        this.contracts.Factory__Helper_TestRunner_CREATE.getDeployTransaction(
          step.functionParams.bytecode || '0x',
          step.functionParams.subSteps?.map((subStep) => {
            return this.parseTestStep(subStep)
          }) || []
        ).data,
      ]
    } else if (isTestStep_CREATE2(step)) {
      functionParams = [
        this.contracts.Factory__Helper_TestRunner_CREATE.getDeployTransaction(
          step.functionParams.bytecode || '0x',
          step.functionParams.subSteps?.map((subStep) => {
            return this.parseTestStep(subStep)
          }) || []
        ).data,
        step.functionParams.salt,
      ]
    } else if (isTestStep_REVERT(step)) {
      functionParams = [step.revertData || '0x']
    }

513 514 515 516 517 518 519 520
    // legacy ovmCALL causes multiple matching functions without the full signature
    let functionName
    if (step.functionName === 'ovmCALL') {
      functionName = 'ovmCALL(uint256,address,uint256,bytes)'
    } else {
      functionName = step.functionName
    }

521
    return this.contracts.OVM_ExecutionManager.interface.encodeFunctionData(
522
      functionName,
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
      functionParams
    )
  }

  private encodeExpectedReturnData(step: TestStep): string {
    if (isTestStep_evm(step)) {
      return '0x'
    }

    if (isRevertFlagError(step.expectedReturnValue)) {
      return encodeRevertData(
        step.expectedReturnValue.flag,
        step.expectedReturnValue.data,
        step.expectedReturnValue.nuisanceGasLeft,
        step.expectedReturnValue.ovmGasRefund
      )
    }

    if (isTestStep_REVERT(step)) {
      return step.expectedReturnValue || '0x'
    }

    let returnData: any[] = []
546
    if (isTestStep_CALLType(step)) {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
      if (step.expectedReturnValue === '0x00') {
        return step.expectedReturnValue
      } else if (
        typeof step.expectedReturnValue === 'string' ||
        step.expectedReturnValue === undefined
      ) {
        returnData = [
          step.expectedReturnStatus,
          step.expectedReturnValue || '0x',
        ]
      } else {
        returnData = [
          step.expectedReturnValue.ovmSuccess,
          step.expectedReturnValue.returnData,
        ]
      }
    } else if (BigNumber.isBigNumber(step.expectedReturnValue)) {
      returnData = [step.expectedReturnValue.toHexString()]
    } else if (step.expectedReturnValue !== undefined) {
      if (step.expectedReturnValue === '0x00') {
        return step.expectedReturnValue
      } else {
        returnData = [step.expectedReturnValue]
      }
    }

    if (isTestStep_CREATE(step) || isTestStep_CREATE2(step)) {
      if (!isRevertFlagError(step.expectedReturnValue)) {
        if (typeof step.expectedReturnValue === 'string') {
          returnData = [step.expectedReturnValue, '0x']
        } else {
          returnData = [
            step.expectedReturnValue.address,
            step.expectedReturnValue.revertData || '0x',
          ]
        }
      }
    }

586 587 588 589 590 591 592 593
    // legacy ovmCALL causes multiple matching functions without the full signature
    let functionName
    if (step.functionName === 'ovmCALL') {
      functionName = 'ovmCALL(uint256,address,uint256,bytes)'
    } else {
      functionName = step.functionName
    }

594
    return this.contracts.OVM_ExecutionManager.interface.encodeFunctionResult(
595
      functionName,
596 597 598 599
      returnData
    )
  }
}