Skip to content

Test Initcode

Documentation for tests/shanghai/eip3860_initcode/test_initcode.py.

Generate fixtures for these test cases with:

fill -v tests/shanghai/eip3860_initcode/test_initcode.py
Test EIP-3860: Limit and meter initcode

Tests for EIP-3860: Limit and meter initcode.

Tests ported from:

test_contract_creating_tx(state_test, initcode)

Test cases using a contract creating transaction

Test creating a contract using a transaction using an initcode that is on/over the max allowed limit.

Generates a BlockchainTest based on the provided initcode and its length.

Source code in tests/shanghai/eip3860_initcode/test_initcode.py
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
@pytest.mark.parametrize(
    "initcode",
    [
        INITCODE_ZEROS_MAX_LIMIT,
        INITCODE_ONES_MAX_LIMIT,
        INITCODE_ZEROS_OVER_LIMIT,
        INITCODE_ONES_OVER_LIMIT,
    ],
    ids=get_initcode_name,
)
def test_contract_creating_tx(state_test: StateTestFiller, initcode: Initcode):
    """
    Test cases using a contract creating transaction

    Test creating a contract using a transaction using an initcode that is
    on/over the max allowed limit.

    Generates a BlockchainTest based on the provided `initcode` and its
    length.
    """
    eip_3860_active = True
    env = Environment()

    pre = {
        TestAddress: Account(balance=1000000000000000000000),
    }

    post: Dict[Any, Any] = {}

    created_contract_address = compute_create_address(
        address=TestAddress,
        nonce=0,
    )

    tx = Transaction(
        nonce=0,
        to=None,
        data=initcode,
        gas_limit=10000000,
        gas_price=10,
    )

    if len(initcode) > MAX_INITCODE_SIZE and eip_3860_active:
        # Initcode is above the max size, tx inclusion in the block makes
        # it invalid.
        post[created_contract_address] = Account.NONEXISTENT
        tx.error = TransactionException.INITCODE_SIZE_EXCEEDED
    else:
        # Initcode is at or below the max size, tx inclusion in the block
        # is ok and the contract is successfully created.
        post[created_contract_address] = Account(code=Op.STOP)

    state_test(
        pre=pre,
        post=post,
        tx=tx,
        env=env,
    )

TestContractCreationGasUsage

Test EIP-3860 Limit Initcode Gas Usage for a contract creating transaction, using different initcode lengths.

Generates 4 test cases that verify the gas cost behavior of a contract creating transaction:

  1. Test with exact intrinsic gas minus one, contract create fails and tx is invalid.
  2. Test with exact intrinsic gas, contract create fails, but tx is valid.
  3. Test with exact execution gas minus one, contract create fails, but tx is valid.
  4. Test with exact execution gas, contract create succeeds.

Initcode must be within valid EIP-3860 length.

Source code in tests/shanghai/eip3860_initcode/test_initcode.py
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
@pytest.mark.parametrize(
    "initcode",
    [
        INITCODE_ZEROS_MAX_LIMIT,
        INITCODE_ONES_MAX_LIMIT,
        EMPTY_INITCODE,
        SINGLE_BYTE_INITCODE,
        INITCODE_ZEROS_32_BYTES,
        INITCODE_ZEROS_33_BYTES,
        INITCODE_ZEROS_49120_BYTES,
        INITCODE_ZEROS_49121_BYTES,
    ],
    ids=get_initcode_name,
)
@pytest.mark.parametrize(
    "gas_test_case",
    [
        "too_little_intrinsic_gas",
        "exact_intrinsic_gas",
        "too_little_execution_gas",
        "exact_execution_gas",
    ],
    ids=lambda x: x,
)
class TestContractCreationGasUsage:
    """
    Test EIP-3860 Limit Initcode Gas Usage for a contract
    creating transaction, using different initcode lengths.

    Generates 4 test cases that verify the gas cost behavior of a
    contract creating transaction:

    1. Test with exact intrinsic gas minus one, contract create fails
        and tx is invalid.
    2. Test with exact intrinsic gas, contract create fails,
        but tx is valid.
    3. Test with exact execution gas minus one, contract create fails,
        but tx is valid.
    4. Test with exact execution gas, contract create succeeds.

    Initcode must be within valid EIP-3860 length.
    """

    @pytest.fixture
    def eip_3860_active(self):  # noqa: D102
        return True

    @pytest.fixture
    def exact_intrinsic_gas(self, initcode, eip_3860_active):
        """
        Calculates the intrinsic tx gas cost.
        """
        return calculate_create_tx_intrinsic_cost(initcode, eip_3860_active)

    @pytest.fixture
    def exact_execution_gas(self, initcode, eip_3860_active):
        """
        Calculates the total execution gas cost.
        """
        return calculate_create_tx_execution_cost(
            initcode,
            eip_3860_active,
        )

    @pytest.fixture
    def created_contract_address(self):
        """
        Calculates the address of the contract deployed via CREATE.
        """
        return compute_create_address(
            address=TestAddress,
            nonce=0,
        )

    @pytest.fixture
    def env(self) -> Environment:  # noqa: D102
        return Environment()

    @pytest.fixture
    def pre(self) -> Dict[Any, Any]:  # noqa: D102
        return {
            TestAddress: Account(balance=1000000000000000000000),
        }

    @pytest.fixture
    def tx_error(self, gas_test_case) -> TransactionException | None:
        """
        Test that the transaction is invalid if too little intrinsic gas is
        specified, otherwise the tx succeeds.
        """
        if gas_test_case == "too_little_intrinsic_gas":
            return TransactionException.INTRINSIC_GAS_TOO_LOW
        return None

    @pytest.fixture
    def tx(
        self,
        gas_test_case,
        initcode,
        tx_error,
        exact_intrinsic_gas,
        exact_execution_gas,
    ) -> Transaction:
        """
        Implement the gas_test_case by setting the gas_limit of the tx
        appropriately and test whether the tx succeeds or fails with
        appropriate error.
        """
        if gas_test_case == "too_little_intrinsic_gas":
            gas_limit = exact_intrinsic_gas - 1
        elif gas_test_case == "exact_intrinsic_gas":
            gas_limit = exact_intrinsic_gas
        elif gas_test_case == "too_little_execution_gas":
            gas_limit = exact_execution_gas - 1
        elif gas_test_case == "exact_execution_gas":
            gas_limit = exact_execution_gas
        else:
            pytest.fail("Invalid gas test case provided.")

        return Transaction(
            nonce=0,
            to=None,
            data=initcode,
            gas_limit=gas_limit,
            gas_price=10,
            error=tx_error,
        )

    @pytest.fixture
    def post(
        self,
        gas_test_case,
        initcode,
        created_contract_address,
        exact_intrinsic_gas,
        exact_execution_gas,
    ) -> Dict[Any, Any]:
        """
        Test that contract creation fails unless enough execution gas is
        provided.
        """
        if gas_test_case == "exact_intrinsic_gas" and exact_intrinsic_gas == exact_execution_gas:
            # Special scenario where the execution of the initcode and
            # gas cost to deploy are zero
            return {created_contract_address: Account(code=initcode.deploy_code)}
        elif gas_test_case == "exact_execution_gas":
            return {created_contract_address: Account(code=initcode.deploy_code)}
        return {created_contract_address: Account.NONEXISTENT}

    def test_gas_usage(
        self,
        state_test: StateTestFiller,
        gas_test_case: str,
        initcode: Initcode,
        exact_intrinsic_gas,
        exact_execution_gas,
        env,
        pre,
        tx,
        post,
    ):
        """
        Test transaction and contract creation behavior for different gas
        limits.
        """
        if (gas_test_case == "too_little_execution_gas") and (
            exact_execution_gas == exact_intrinsic_gas
        ):
            pytest.skip(
                "Special case, the execution of the initcode and gas "
                "cost to deploy are zero: Then this test case is "
                "equivalent to that of 'test_exact_intrinsic_gas'."
            )

        state_test(
            pre=pre,
            post=post,
            tx=tx,
            env=env,
        )

test_gas_usage(state_test, gas_test_case, initcode, exact_intrinsic_gas, exact_execution_gas, env, pre, tx, post)

Test transaction and contract creation behavior for different gas limits.

Source code in tests/shanghai/eip3860_initcode/test_initcode.py
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
def test_gas_usage(
    self,
    state_test: StateTestFiller,
    gas_test_case: str,
    initcode: Initcode,
    exact_intrinsic_gas,
    exact_execution_gas,
    env,
    pre,
    tx,
    post,
):
    """
    Test transaction and contract creation behavior for different gas
    limits.
    """
    if (gas_test_case == "too_little_execution_gas") and (
        exact_execution_gas == exact_intrinsic_gas
    ):
        pytest.skip(
            "Special case, the execution of the initcode and gas "
            "cost to deploy are zero: Then this test case is "
            "equivalent to that of 'test_exact_intrinsic_gas'."
        )

    state_test(
        pre=pre,
        post=post,
        tx=tx,
        env=env,
    )

TestCreateInitcode

Test contract creation via the CREATE/CREATE2 opcodes that have an initcode that is on/over the max allowed limit.

Source code in tests/shanghai/eip3860_initcode/test_initcode.py
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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
@pytest.mark.parametrize(
    "initcode",
    [
        INITCODE_ZEROS_MAX_LIMIT,
        INITCODE_ONES_MAX_LIMIT,
        INITCODE_ZEROS_OVER_LIMIT,
        INITCODE_ONES_OVER_LIMIT,
        EMPTY_INITCODE,
        SINGLE_BYTE_INITCODE,
        INITCODE_ZEROS_32_BYTES,
        INITCODE_ZEROS_33_BYTES,
        INITCODE_ZEROS_49120_BYTES,
        INITCODE_ZEROS_49121_BYTES,
    ],
    ids=get_initcode_name,
)
@pytest.mark.parametrize("opcode", [Op.CREATE, Op.CREATE2], ids=get_create_id)
class TestCreateInitcode:
    """
    Test contract creation via the CREATE/CREATE2 opcodes that have an initcode
    that is on/over the max allowed limit.
    """

    @pytest.fixture
    def create_code(self, opcode: Op, initcode: Initcode):  # noqa: D102
        if opcode == Op.CREATE:
            create_call = Op.CREATE(0, 0, Op.CALLDATASIZE)
        elif opcode == Op.CREATE2:
            create_call = Op.CREATE2(0, 0, Op.CALLDATASIZE, 0xDEADBEEF)
        else:
            raise Exception("Invalid opcode specified for test.")
        return (
            Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
            + Op.GAS
            + create_call
            + Op.GAS
            # stack: [Gas 2, Call Result, Gas 1]
            + Op.SWAP1
            # stack: [Call Result, Gas 2, Gas 1]
            + Op.SSTORE(0, unchecked=True)
            # stack: [Gas 2, Gas 1]
            + Op.SWAP1
            # stack: [Gas 1, Gas 2]
            + Op.SUB
            # stack: [Gas 1 - Gas 2]
            + Op.SSTORE(1, unchecked=True)
        )

    @pytest.fixture
    def created_contract_address(self, initcode: Initcode, opcode: Op):  # noqa: D102
        if opcode == Op.CREATE:
            return compute_create_address(
                address=0x100,
                nonce=1,
            )
        if opcode == Op.CREATE2:
            return compute_create2_address(
                address=0x100,
                salt=0xDEADBEEF,
                initcode=initcode,
            )
        raise Exception("invalid opcode for generator")

    def test_create_opcode_initcode(
        self,
        state_test: StateTestFiller,
        opcode: Op,
        initcode: Initcode,
        create_code: Yul,
        created_contract_address: str,
    ):
        """
        Test contract creation via the CREATE/CREATE2 opcodes that have an
        initcode that is on/over the max allowed limit.
        """
        eip_3860_active = True
        env = Environment()

        call_code = Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
        call_code += Op.SSTORE(
            Op.CALL(5000000, 0x100, 0, 0, Op.CALLDATASIZE, 0, 0),
            1,
        )

        pre = {
            TestAddress: Account(balance=1000000000000000000000),
            Address(0x100): Account(
                code=create_code,
                nonce=1,
            ),
            Address(0x200): Account(
                code=call_code,
                nonce=1,
            ),
        }

        post: Dict[Any, Any] = {}

        tx = Transaction(
            nonce=0,
            to=Address(0x200),
            data=initcode,
            gas_limit=10000000,
            gas_price=10,
        )

        # Calculate the expected gas of the contract creation operation
        expected_gas_usage = (
            CREATE_CONTRACT_BASE_GAS
            + GAS_OPCODE_GAS
            + (2 * PUSH_DUP_OPCODE_GAS)
            + CALLDATASIZE_OPCODE_GAS
        )
        if opcode == Op.CREATE2:
            # Extra PUSH operation
            expected_gas_usage += PUSH_DUP_OPCODE_GAS

        if len(initcode) > MAX_INITCODE_SIZE and eip_3860_active:
            # Call returns 0 as out of gas s[0]==1
            post[Address(0x200)] = Account(
                nonce=1,
                storage={
                    0: 1,
                    1: 0,
                },
            )

            post[created_contract_address] = Account.NONEXISTENT
            post[Address(0x100)] = Account(
                nonce=1,
                storage={
                    0: 0,
                    1: 0,
                },
            )

        else:
            # The initcode is only executed if the length check succeeds
            expected_gas_usage += initcode.execution_gas
            # The code is only deployed if the length check succeeds
            expected_gas_usage += initcode.deployment_gas

            if opcode == Op.CREATE2:
                # CREATE2 hashing cost should only be deducted if the initcode
                # does not exceed the max length
                expected_gas_usage += calculate_create2_word_cost(len(initcode))

            if eip_3860_active:
                # Initcode word cost is only deducted if the length check
                # succeeds
                expected_gas_usage += calculate_initcode_word_cost(len(initcode))

            # Call returns 1 as valid initcode length s[0]==1 && s[1]==1
            post[Address(0x200)] = Account(
                nonce=1,
                storage={
                    0: 0,
                    1: 1,
                },
            )

            post[created_contract_address] = Account(code=initcode.deploy_code)
            post[Address(0x100)] = Account(
                nonce=2,
                storage={
                    0: created_contract_address,
                    1: expected_gas_usage,
                },
            )

        state_test(
            env=env,
            pre=pre,
            post=post,
            tx=tx,
        )

test_create_opcode_initcode(state_test, opcode, initcode, create_code, created_contract_address)

Test contract creation via the CREATE/CREATE2 opcodes that have an initcode that is on/over the max allowed limit.

Source code in tests/shanghai/eip3860_initcode/test_initcode.py
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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def test_create_opcode_initcode(
    self,
    state_test: StateTestFiller,
    opcode: Op,
    initcode: Initcode,
    create_code: Yul,
    created_contract_address: str,
):
    """
    Test contract creation via the CREATE/CREATE2 opcodes that have an
    initcode that is on/over the max allowed limit.
    """
    eip_3860_active = True
    env = Environment()

    call_code = Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
    call_code += Op.SSTORE(
        Op.CALL(5000000, 0x100, 0, 0, Op.CALLDATASIZE, 0, 0),
        1,
    )

    pre = {
        TestAddress: Account(balance=1000000000000000000000),
        Address(0x100): Account(
            code=create_code,
            nonce=1,
        ),
        Address(0x200): Account(
            code=call_code,
            nonce=1,
        ),
    }

    post: Dict[Any, Any] = {}

    tx = Transaction(
        nonce=0,
        to=Address(0x200),
        data=initcode,
        gas_limit=10000000,
        gas_price=10,
    )

    # Calculate the expected gas of the contract creation operation
    expected_gas_usage = (
        CREATE_CONTRACT_BASE_GAS
        + GAS_OPCODE_GAS
        + (2 * PUSH_DUP_OPCODE_GAS)
        + CALLDATASIZE_OPCODE_GAS
    )
    if opcode == Op.CREATE2:
        # Extra PUSH operation
        expected_gas_usage += PUSH_DUP_OPCODE_GAS

    if len(initcode) > MAX_INITCODE_SIZE and eip_3860_active:
        # Call returns 0 as out of gas s[0]==1
        post[Address(0x200)] = Account(
            nonce=1,
            storage={
                0: 1,
                1: 0,
            },
        )

        post[created_contract_address] = Account.NONEXISTENT
        post[Address(0x100)] = Account(
            nonce=1,
            storage={
                0: 0,
                1: 0,
            },
        )

    else:
        # The initcode is only executed if the length check succeeds
        expected_gas_usage += initcode.execution_gas
        # The code is only deployed if the length check succeeds
        expected_gas_usage += initcode.deployment_gas

        if opcode == Op.CREATE2:
            # CREATE2 hashing cost should only be deducted if the initcode
            # does not exceed the max length
            expected_gas_usage += calculate_create2_word_cost(len(initcode))

        if eip_3860_active:
            # Initcode word cost is only deducted if the length check
            # succeeds
            expected_gas_usage += calculate_initcode_word_cost(len(initcode))

        # Call returns 1 as valid initcode length s[0]==1 && s[1]==1
        post[Address(0x200)] = Account(
            nonce=1,
            storage={
                0: 0,
                1: 1,
            },
        )

        post[created_contract_address] = Account(code=initcode.deploy_code)
        post[Address(0x100)] = Account(
            nonce=2,
            storage={
                0: created_contract_address,
                1: expected_gas_usage,
            },
        )

    state_test(
        env=env,
        pre=pre,
        post=post,
        tx=tx,
    )