ethereum.forks.bpo5.fork

Ethereum Specification.

.. contents:: Table of Contents :backlinks: none :local:

Introduction

Entry point for the Ethereum specification.

BASE_FEE_MAX_CHANGE_DENOMINATOR

98
BASE_FEE_MAX_CHANGE_DENOMINATOR = Uint(8)

ELASTICITY_MULTIPLIER

99
ELASTICITY_MULTIPLIER = Uint(2)

EMPTY_OMMER_HASH

100
EMPTY_OMMER_HASH = keccak256(rlp.encode([]))

SYSTEM_ADDRESS

101
SYSTEM_ADDRESS = hex_to_address("0xfffffffffffffffffffffffffffffffffffffffe")

BEACON_ROOTS_ADDRESS

102
BEACON_ROOTS_ADDRESS = hex_to_address(
103
    "0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02"
104
)

SYSTEM_TRANSACTION_GAS

105
SYSTEM_TRANSACTION_GAS = Uint(30000000)

MAX_BLOB_GAS_PER_BLOCK

106
MAX_BLOB_GAS_PER_BLOCK = GasCosts.BLOB_SCHEDULE_MAX * GasCosts.PER_BLOB

VERSIONED_HASH_VERSION_KZG

107
VERSIONED_HASH_VERSION_KZG = b"\x01"

WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS

109
WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS = hex_to_address(
110
    "0x00000961Ef480Eb55e80D19ad83579A64c007002"
111
)

CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS

112
CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS = hex_to_address(
113
    "0x0000BBdDc7CE488642fb579F8B00f3a590007251"
114
)

HISTORY_STORAGE_ADDRESS

115
HISTORY_STORAGE_ADDRESS = hex_to_address(
116
    "0x0000F90827F1C53a10cb7A02335B175320002935"
117
)

MAX_BLOCK_SIZE

118
MAX_BLOCK_SIZE = 10_485_760

SAFETY_MARGIN

119
SAFETY_MARGIN = 2_097_152

MAX_RLP_BLOCK_SIZE

120
MAX_RLP_BLOCK_SIZE = MAX_BLOCK_SIZE - SAFETY_MARGIN

BLOB_COUNT_LIMIT

121
BLOB_COUNT_LIMIT = 6

BlockChain

History and current state of the block chain.

124
@dataclass
class BlockChain:

blocks

130
    blocks: List[Block]

state

131
    state: State

chain_id

132
    chain_id: U64

apply_fork

Transforms the state from the previous hard fork (old) into the block chain object for this hard fork and returns it.

When forks need to implement an irregular state transition, this function is used to handle the irregularity. See the :ref:DAO Fork <dao-fork> for an example.

Parameters

old : Previous block chain object.

Returns

new : BlockChain Upgraded block chain object for this hard fork.

def apply_fork(old: BlockChain) -> BlockChain:
136
    """
137
    Transforms the state from the previous hard fork (`old`) into the block
138
    chain object for this hard fork and returns it.
139
140
    When forks need to implement an irregular state transition, this function
141
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
142
    an example.
143
144
    Parameters
145
    ----------
146
    old :
147
        Previous block chain object.
148
149
    Returns
150
    -------
151
    new : `BlockChain`
152
        Upgraded block chain object for this hard fork.
153
154
    """
155
    return old

get_last_256_block_hashes

Obtain the list of hashes of the previous 256 blocks in order of increasing block number.

This function will return less hashes for the first 256 blocks.

The BLOCKHASH opcode needs to access the latest hashes on the chain, therefore this function retrieves them.

Parameters

chain : History and current state.

Returns

recent_block_hashes : List[Hash32] Hashes of the recent 256 blocks in order of increasing block number.

def get_last_256_block_hashes(chain: BlockChain) -> List[Hash32]:
159
    """
160
    Obtain the list of hashes of the previous 256 blocks in order of
161
    increasing block number.
162
163
    This function will return less hashes for the first 256 blocks.
164
165
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
166
    therefore this function retrieves them.
167
168
    Parameters
169
    ----------
170
    chain :
171
        History and current state.
172
173
    Returns
174
    -------
175
    recent_block_hashes : `List[Hash32]`
176
        Hashes of the recent 256 blocks in order of increasing block number.
177
178
    """
179
    recent_blocks = chain.blocks[-255:]
180
    # TODO: This function has not been tested rigorously
181
    if len(recent_blocks) == 0:
182
        return []
183
184
    recent_block_hashes = []
185
186
    for block in recent_blocks:
187
        prev_block_hash = block.header.parent_hash
188
        recent_block_hashes.append(prev_block_hash)
189
190
    # We are computing the hash only for the most recent block and not for
191
    # the rest of the blocks as they have successors which have the hash of
192
    # the current block as parent hash.
193
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
194
    recent_block_hashes.append(most_recent_block_hash)
195
196
    return recent_block_hashes

state_transition

Attempts to apply a block to an existing block chain.

All parts of the block's contents need to be verified before being added to the chain. Blocks are verified by ensuring that the contents of the block make logical sense with the contents of the parent block. The information in the block's header must also match the corresponding information in the block.

To implement Ethereum, in theory clients are only required to store the most recent 255 blocks of the chain since as far as execution is concerned, only those blocks are accessed. Practically, however, clients should store more blocks to handle reorgs.

Parameters

chain : History and current state. block : Block to apply to chain.

def state_transition(chain: BlockChain, ​​block: Block) -> None:
200
    """
201
    Attempts to apply a block to an existing block chain.
202
203
    All parts of the block's contents need to be verified before being added
204
    to the chain. Blocks are verified by ensuring that the contents of the
205
    block make logical sense with the contents of the parent block. The
206
    information in the block's header must also match the corresponding
207
    information in the block.
208
209
    To implement Ethereum, in theory clients are only required to store the
210
    most recent 255 blocks of the chain since as far as execution is
211
    concerned, only those blocks are accessed. Practically, however, clients
212
    should store more blocks to handle reorgs.
213
214
    Parameters
215
    ----------
216
    chain :
217
        History and current state.
218
    block :
219
        Block to apply to `chain`.
220
221
    """
222
    if len(rlp.encode(block)) > MAX_RLP_BLOCK_SIZE:
223
        raise InvalidBlock("Block rlp size exceeds MAX_RLP_BLOCK_SIZE")
224
225
    validate_header(chain, block.header)
226
    if block.ommers != ():
227
        raise InvalidBlock
228
229
    block_state = BlockState(pre_state=chain.state)
230
231
    block_env = vm.BlockEnvironment(
232
        chain_id=chain.chain_id,
233
        state=block_state,
234
        block_gas_limit=block.header.gas_limit,
235
        block_hashes=get_last_256_block_hashes(chain),
236
        coinbase=block.header.coinbase,
237
        number=block.header.number,
238
        base_fee_per_gas=block.header.base_fee_per_gas,
239
        time=block.header.timestamp,
240
        prev_randao=block.header.prev_randao,
241
        excess_blob_gas=block.header.excess_blob_gas,
242
        parent_beacon_block_root=block.header.parent_beacon_block_root,
243
    )
244
245
    block_output = apply_body(
246
        block_env=block_env,
247
        transactions=block.transactions,
248
        withdrawals=block.withdrawals,
249
    )
250
    block_diff = extract_block_diff(block_state)
251
    block_state_root, _ = chain.state.compute_state_root_and_trie_changes(
252
        block_diff.account_changes, block_diff.storage_changes
253
    )
254
    transactions_root = root(block_output.transactions_trie)
255
    receipt_root = root(block_output.receipts_trie)
256
    block_logs_bloom = logs_bloom(block_output.block_logs)
257
    withdrawals_root = root(block_output.withdrawals_trie)
258
    requests_hash = compute_requests_hash(block_output.requests)
259
260
    if block_output.block_gas_used != block.header.gas_used:
261
        raise InvalidBlock(
262
            f"{block_output.block_gas_used} != {block.header.gas_used}"
263
        )
264
    if transactions_root != block.header.transactions_root:
265
        raise InvalidBlock
266
    if block_state_root != block.header.state_root:
267
        raise InvalidBlock
268
    if receipt_root != block.header.receipt_root:
269
        raise InvalidBlock
270
    if block_logs_bloom != block.header.bloom:
271
        raise InvalidBlock
272
    if withdrawals_root != block.header.withdrawals_root:
273
        raise InvalidBlock
274
    if block_output.blob_gas_used != block.header.blob_gas_used:
275
        raise InvalidBlock
276
    if requests_hash != block.header.requests_hash:
277
        raise InvalidBlock
278
279
    apply_changes_to_state(chain.state, block_diff)
280
    chain.blocks.append(block)
281
    if len(chain.blocks) > 255:
282
        # Real clients have to store more blocks to deal with reorgs, but the
283
        # protocol only requires the last 255
284
        chain.blocks = chain.blocks[-255:]

calculate_base_fee_per_gas

Calculates the base fee per gas for the block.

Parameters

block_gas_limit : Gas limit of the block for which the base fee is being calculated. parent_gas_limit : Gas limit of the parent block. parent_gas_used : Gas used in the parent block. parent_base_fee_per_gas : Base fee per gas of the parent block.

Returns

base_fee_per_gas : Uint Base fee per gas for the block.

def calculate_base_fee_per_gas(block_gas_limit: Uint, ​​parent_gas_limit: Uint, ​​parent_gas_used: Uint, ​​parent_base_fee_per_gas: Uint) -> Uint:
293
    """
294
    Calculates the base fee per gas for the block.
295
296
    Parameters
297
    ----------
298
    block_gas_limit :
299
        Gas limit of the block for which the base fee is being calculated.
300
    parent_gas_limit :
301
        Gas limit of the parent block.
302
    parent_gas_used :
303
        Gas used in the parent block.
304
    parent_base_fee_per_gas :
305
        Base fee per gas of the parent block.
306
307
    Returns
308
    -------
309
    base_fee_per_gas : `Uint`
310
        Base fee per gas for the block.
311
312
    """
313
    parent_gas_target = parent_gas_limit // ELASTICITY_MULTIPLIER
314
    if not check_gas_limit(block_gas_limit, parent_gas_limit):
315
        raise InvalidBlock
316
317
    if parent_gas_used == parent_gas_target:
318
        expected_base_fee_per_gas = parent_base_fee_per_gas
319
    elif parent_gas_used > parent_gas_target:
320
        gas_used_delta = parent_gas_used - parent_gas_target
321
322
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
323
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
324
325
        base_fee_per_gas_delta = max(
326
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR,
327
            Uint(1),
328
        )
329
330
        expected_base_fee_per_gas = (
331
            parent_base_fee_per_gas + base_fee_per_gas_delta
332
        )
333
    else:
334
        gas_used_delta = parent_gas_target - parent_gas_used
335
336
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
337
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
338
339
        base_fee_per_gas_delta = (
340
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR
341
        )
342
343
        expected_base_fee_per_gas = (
344
            parent_base_fee_per_gas - base_fee_per_gas_delta
345
        )
346
347
    return Uint(expected_base_fee_per_gas)

validate_header

Verifies a block header.

In order to consider a block's header valid, the logic for the quantities in the header should match the logic for the block itself. For example the header timestamp should be greater than the block's parent timestamp because the block was created after the parent block. Additionally, the block's number should be directly following the parent block's number since it is the next block in the sequence.

Parameters

chain : History and current state. header : Header to check for correctness.

def validate_header(chain: BlockChain, ​​header: Header) -> None:
351
    """
352
    Verifies a block header.
353
354
    In order to consider a block's header valid, the logic for the
355
    quantities in the header should match the logic for the block itself.
356
    For example the header timestamp should be greater than the block's parent
357
    timestamp because the block was created *after* the parent block.
358
    Additionally, the block's number should be directly following the parent
359
    block's number since it is the next block in the sequence.
360
361
    Parameters
362
    ----------
363
    chain :
364
        History and current state.
365
    header :
366
        Header to check for correctness.
367
368
    """
369
    if header.number < Uint(1):
370
        raise InvalidBlock
371
372
    parent_header = chain.blocks[-1].header
373
374
    excess_blob_gas = calculate_excess_blob_gas(parent_header)
375
    if header.excess_blob_gas != excess_blob_gas:
376
        raise InvalidBlock
377
378
    if header.gas_used > header.gas_limit:
379
        raise InvalidBlock
380
381
    expected_base_fee_per_gas = calculate_base_fee_per_gas(
382
        header.gas_limit,
383
        parent_header.gas_limit,
384
        parent_header.gas_used,
385
        parent_header.base_fee_per_gas,
386
    )
387
    if expected_base_fee_per_gas != header.base_fee_per_gas:
388
        raise InvalidBlock
389
    if header.timestamp <= parent_header.timestamp:
390
        raise InvalidBlock
391
    if header.number != parent_header.number + Uint(1):
392
        raise InvalidBlock
393
    if len(header.extra_data) > 32:
394
        raise InvalidBlock
395
    if header.difficulty != 0:
396
        raise InvalidBlock
397
    if header.nonce != b"\x00\x00\x00\x00\x00\x00\x00\x00":
398
        raise InvalidBlock
399
    if header.ommers_hash != EMPTY_OMMER_HASH:
400
        raise InvalidBlock
401
402
    block_parent_hash = keccak256(rlp.encode(parent_header))
403
    if header.parent_hash != block_parent_hash:
404
        raise InvalidBlock

check_transaction

Check if the transaction is includable in the block.

Parameters

block_env : The block scoped environment. block_output : The block output for the current block. tx : The transaction. tx_state : The transaction state tracker.

Returns

sender_address : The sender of the transaction. effective_gas_price : The price to charge for gas when the transaction is executed. blob_versioned_hashes : The blob versioned hashes of the transaction. tx_blob_gas_used: The blob gas used by the transaction.

Raises

InvalidBlock : If the transaction is not includable. GasUsedExceedsLimitError : If the gas used by the transaction exceeds the block's gas limit. NonceMismatchError : If the nonce of the transaction is not equal to the sender's nonce. InsufficientBalanceError : If the sender's balance is not enough to pay for the transaction. InvalidSenderError : If the transaction is from an address that does not exist anymore. PriorityFeeGreaterThanMaxFeeError : If the priority fee is greater than the maximum fee per gas. InsufficientMaxFeePerGasError : If the maximum fee per gas is insufficient for the transaction. InsufficientMaxFeePerBlobGasError : If the maximum fee per blob gas is insufficient for the transaction. BlobGasLimitExceededError : If the blob gas used by the transaction exceeds the block's blob gas limit. InvalidBlobVersionedHashError : If the transaction contains a blob versioned hash with an invalid version. NoBlobDataError : If the transaction is a type 3 but has no blobs. BlobCountExceededError : If the transaction is a type 3 and has more blobs than the limit. TransactionTypeContractCreationError: If the transaction type is not allowed to create contracts. EmptyAuthorizationListError : If the transaction is a SetCodeTransaction and the authorization list is empty.

def check_transaction(block_env: ethereum.forks.bpo5.vm.BlockEnvironment, ​​block_output: ethereum.forks.bpo5.vm.BlockOutput, ​​tx: Transaction, ​​tx_state: TransactionState) -> Tuple[Address, Uint, Tuple[VersionedHash, ...], U64]:
413
    """
414
    Check if the transaction is includable in the block.
415
416
    Parameters
417
    ----------
418
    block_env :
419
        The block scoped environment.
420
    block_output :
421
        The block output for the current block.
422
    tx :
423
        The transaction.
424
    tx_state :
425
        The transaction state tracker.
426
427
    Returns
428
    -------
429
    sender_address :
430
        The sender of the transaction.
431
    effective_gas_price :
432
        The price to charge for gas when the transaction is executed.
433
    blob_versioned_hashes :
434
        The blob versioned hashes of the transaction.
435
    tx_blob_gas_used:
436
        The blob gas used by the transaction.
437
438
    Raises
439
    ------
440
    InvalidBlock :
441
        If the transaction is not includable.
442
    GasUsedExceedsLimitError :
443
        If the gas used by the transaction exceeds the block's gas limit.
444
    NonceMismatchError :
445
        If the nonce of the transaction is not equal to the sender's nonce.
446
    InsufficientBalanceError :
447
        If the sender's balance is not enough to pay for the transaction.
448
    InvalidSenderError :
449
        If the transaction is from an address that does not exist anymore.
450
    PriorityFeeGreaterThanMaxFeeError :
451
        If the priority fee is greater than the maximum fee per gas.
452
    InsufficientMaxFeePerGasError :
453
        If the maximum fee per gas is insufficient for the transaction.
454
    InsufficientMaxFeePerBlobGasError :
455
        If the maximum fee per blob gas is insufficient for the transaction.
456
    BlobGasLimitExceededError :
457
        If the blob gas used by the transaction exceeds the block's blob gas
458
        limit.
459
    InvalidBlobVersionedHashError :
460
        If the transaction contains a blob versioned hash with an invalid
461
        version.
462
    NoBlobDataError :
463
        If the transaction is a type 3 but has no blobs.
464
    BlobCountExceededError :
465
        If the transaction is a type 3 and has more blobs than the limit.
466
    TransactionTypeContractCreationError:
467
        If the transaction type is not allowed to create contracts.
468
    EmptyAuthorizationListError :
469
        If the transaction is a SetCodeTransaction and the authorization list
470
        is empty.
471
472
    """
473
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
474
    blob_gas_available = MAX_BLOB_GAS_PER_BLOCK - block_output.blob_gas_used
475
476
    if tx.gas > gas_available:
477
        raise GasUsedExceedsLimitError("gas used exceeds limit")
478
479
    tx_blob_gas_used = calculate_total_blob_gas(tx)
480
    if tx_blob_gas_used > blob_gas_available:
481
        raise BlobGasLimitExceededError("blob gas limit exceeded")
482
483
    sender_address = recover_sender(block_env.chain_id, tx)
484
    sender_account = get_account(tx_state, sender_address)
485
486
    if isinstance(
487
        tx, (FeeMarketTransaction, BlobTransaction, SetCodeTransaction)
488
    ):
489
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
490
            raise PriorityFeeGreaterThanMaxFeeError(
491
                "priority fee greater than max fee"
492
            )
493
        if tx.max_fee_per_gas < block_env.base_fee_per_gas:
494
            raise InsufficientMaxFeePerGasError(
495
                tx.max_fee_per_gas, block_env.base_fee_per_gas
496
            )
497
498
        priority_fee_per_gas = min(
499
            tx.max_priority_fee_per_gas,
500
            tx.max_fee_per_gas - block_env.base_fee_per_gas,
501
        )
502
        effective_gas_price = priority_fee_per_gas + block_env.base_fee_per_gas
503
        max_gas_fee = tx.gas * tx.max_fee_per_gas
504
    else:
505
        if tx.gas_price < block_env.base_fee_per_gas:
506
            raise InvalidBlock
507
        effective_gas_price = tx.gas_price
508
        max_gas_fee = tx.gas * tx.gas_price
509
510
    if isinstance(tx, BlobTransaction):
511
        blob_count = len(tx.blob_versioned_hashes)
512
        if blob_count == 0:
513
            raise NoBlobDataError("no blob data in transaction")
514
        if blob_count > BLOB_COUNT_LIMIT:
515
            raise BlobCountExceededError(
516
                f"Tx has {blob_count} blobs. Max allowed: {BLOB_COUNT_LIMIT}"
517
            )
518
        for blob_versioned_hash in tx.blob_versioned_hashes:
519
            if blob_versioned_hash[0:1] != VERSIONED_HASH_VERSION_KZG:
520
                raise InvalidBlobVersionedHashError(
521
                    "invalid blob versioned hash"
522
                )
523
524
        blob_gas_price = calculate_blob_gas_price(block_env.excess_blob_gas)
525
        if Uint(tx.max_fee_per_blob_gas) < blob_gas_price:
526
            raise InsufficientMaxFeePerBlobGasError(
527
                "insufficient max fee per blob gas"
528
            )
529
530
        max_gas_fee += Uint(calculate_total_blob_gas(tx)) * Uint(
531
            tx.max_fee_per_blob_gas
532
        )
533
        blob_versioned_hashes = tx.blob_versioned_hashes
534
    else:
535
        blob_versioned_hashes = ()
536
537
    if isinstance(tx, (BlobTransaction, SetCodeTransaction)):
538
        if not isinstance(tx.to, Address):
539
            raise TransactionTypeContractCreationError(tx)
540
541
    if isinstance(tx, SetCodeTransaction):
542
        if not any(tx.authorizations):
543
            raise EmptyAuthorizationListError("empty authorization list")
544
545
    if sender_account.nonce > Uint(tx.nonce):
546
        raise NonceMismatchError("nonce too low")
547
    elif sender_account.nonce < Uint(tx.nonce):
548
        raise NonceMismatchError("nonce too high")
549
550
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
551
        raise InsufficientBalanceError("insufficient sender balance")
552
    sender_code = get_code(tx_state, sender_account.code_hash)
553
    if sender_account.code_hash != EMPTY_CODE_HASH and not is_valid_delegation(
554
        sender_code
555
    ):
556
        raise InvalidSenderError("not EOA")
557
558
    return (
559
        sender_address,
560
        effective_gas_price,
561
        blob_versioned_hashes,
562
        tx_blob_gas_used,
563
    )

make_receipt

Make the receipt for a transaction that was executed.

Parameters

tx : The executed transaction. error : Error in the top level frame of the transaction, if any. cumulative_gas_used : The total gas used so far in the block after the transaction was executed. logs : The logs produced by the transaction.

Returns

receipt : The receipt for the transaction.

def make_receipt(tx: Transaction, ​​error: Optional[EthereumException], ​​cumulative_gas_used: Uint, ​​logs: Tuple[Log, ...]) -> Bytes | Receipt:
572
    """
573
    Make the receipt for a transaction that was executed.
574
575
    Parameters
576
    ----------
577
    tx :
578
        The executed transaction.
579
    error :
580
        Error in the top level frame of the transaction, if any.
581
    cumulative_gas_used :
582
        The total gas used so far in the block after the transaction was
583
        executed.
584
    logs :
585
        The logs produced by the transaction.
586
587
    Returns
588
    -------
589
    receipt :
590
        The receipt for the transaction.
591
592
    """
593
    receipt = Receipt(
594
        succeeded=error is None,
595
        cumulative_gas_used=cumulative_gas_used,
596
        bloom=logs_bloom(logs),
597
        logs=logs,
598
    )
599
600
    return encode_receipt(tx, receipt)

process_checked_system_transaction

Process a system transaction and raise an error if the contract does not contain code or if the transaction fails.

Parameters

block_env : The block scoped environment. target_address : Address of the contract to call. data : Data to pass to the contract.

Returns

system_tx_output : MessageCallOutput Output of processing the system transaction.

def process_checked_system_transaction(block_env: ethereum.forks.bpo5.vm.BlockEnvironment, ​​target_address: Address, ​​data: Bytes) -> MessageCallOutput:
608
    """
609
    Process a system transaction and raise an error if the contract does not
610
    contain code or if the transaction fails.
611
612
    Parameters
613
    ----------
614
    block_env :
615
        The block scoped environment.
616
    target_address :
617
        Address of the contract to call.
618
    data :
619
        Data to pass to the contract.
620
621
    Returns
622
    -------
623
    system_tx_output : `MessageCallOutput`
624
        Output of processing the system transaction.
625
626
    """
627
    # Pre-check that the system contract has code. We use a throwaway
628
    # TransactionState here that is *never* propagated back to BlockState
629
    # (no incorporate_tx_into_block call); the same get_account / get_code
630
    # lookups are performed and properly tracked by
631
    # process_unchecked_system_transaction below, which this function
632
    # always calls. Reading via a TransactionState (rather than directly
633
    # against pre_state) lets us see system contracts deployed earlier in
634
    # the same block — see EIP-7002 and EIP-7251 for this edge case.
635
    untracked_state = TransactionState(parent=block_env.state)
636
    system_contract_code = get_code(
637
        untracked_state,
638
        get_account(untracked_state, target_address).code_hash,
639
    )
640
641
    if len(system_contract_code) == 0:
642
        raise InvalidBlock(
643
            f"System contract address {target_address.hex()} does not "
644
            "contain code"
645
        )
646
647
    system_tx_output = process_unchecked_system_transaction(
648
        block_env,
649
        target_address,
650
        data,
651
    )
652
653
    if system_tx_output.error:
654
        raise InvalidBlock(
655
            f"System contract ({target_address.hex()}) call failed: "
656
            f"{system_tx_output.error}"
657
        )
658
659
    return system_tx_output

process_unchecked_system_transaction

Process a system transaction without checking if the contract contains code or if the transaction fails.

Parameters

block_env : The block scoped environment. target_address : Address of the contract to call. data : Data to pass to the contract.

Returns

system_tx_output : MessageCallOutput Output of processing the system transaction.

def process_unchecked_system_transaction(block_env: ethereum.forks.bpo5.vm.BlockEnvironment, ​​target_address: Address, ​​data: Bytes) -> MessageCallOutput:
667
    """
668
    Process a system transaction without checking if the contract contains
669
    code or if the transaction fails.
670
671
    Parameters
672
    ----------
673
    block_env :
674
        The block scoped environment.
675
    target_address :
676
        Address of the contract to call.
677
    data :
678
        Data to pass to the contract.
679
680
    Returns
681
    -------
682
    system_tx_output : `MessageCallOutput`
683
        Output of processing the system transaction.
684
685
    """
686
    system_tx_state = TransactionState(parent=block_env.state)
687
    system_contract_code = get_code(
688
        system_tx_state,
689
        get_account(system_tx_state, target_address).code_hash,
690
    )
691
692
    tx_env = vm.TransactionEnvironment(
693
        origin=SYSTEM_ADDRESS,
694
        gas_price=block_env.base_fee_per_gas,
695
        gas=SYSTEM_TRANSACTION_GAS,
696
        access_list_addresses=set(),
697
        access_list_storage_keys=set(),
698
        state=system_tx_state,
699
        blob_versioned_hashes=(),
700
        authorizations=(),
701
        index_in_block=None,
702
        tx_hash=None,
703
    )
704
705
    system_tx_message = Message(
706
        block_env=block_env,
707
        tx_env=tx_env,
708
        caller=SYSTEM_ADDRESS,
709
        target=target_address,
710
        gas=SYSTEM_TRANSACTION_GAS,
711
        value=U256(0),
712
        data=data,
713
        code=system_contract_code,
714
        depth=Uint(0),
715
        current_target=target_address,
716
        code_address=target_address,
717
        should_transfer_value=False,
718
        is_static=False,
719
        accessed_addresses=set(),
720
        accessed_storage_keys=set(),
721
        disable_precompiles=False,
722
        parent_evm=None,
723
    )
724
725
    system_tx_output = process_message_call(system_tx_message)
726
727
    incorporate_tx_into_block(system_tx_state)
728
729
    return system_tx_output

apply_body

Executes a block.

Many of the contents of a block are stored in data structures called tries. There is a transactions trie which is similar to a ledger of the transactions stored in the current block. There is also a receipts trie which stores the results of executing a transaction, like the post state and gas used. This function creates and executes the block that is to be added to the chain.

Parameters

block_env : The block scoped environment. transactions : Transactions included in the block. withdrawals : Withdrawals to be processed in the current block.

Returns

block_output : The block output for the current block.

def apply_body(block_env: ethereum.forks.bpo5.vm.BlockEnvironment, ​​transactions: Tuple[LegacyTransaction | Bytes, ...], ​​withdrawals: Tuple[Withdrawal, ...]) -> ethereum.forks.bpo5.vm.BlockOutput:
737
    """
738
    Executes a block.
739
740
    Many of the contents of a block are stored in data structures called
741
    tries. There is a transactions trie which is similar to a ledger of the
742
    transactions stored in the current block. There is also a receipts trie
743
    which stores the results of executing a transaction, like the post state
744
    and gas used. This function creates and executes the block that is to be
745
    added to the chain.
746
747
    Parameters
748
    ----------
749
    block_env :
750
        The block scoped environment.
751
    transactions :
752
        Transactions included in the block.
753
    withdrawals :
754
        Withdrawals to be processed in the current block.
755
756
    Returns
757
    -------
758
    block_output :
759
        The block output for the current block.
760
761
    """
762
    block_output = vm.BlockOutput()
763
764
    process_unchecked_system_transaction(
765
        block_env=block_env,
766
        target_address=BEACON_ROOTS_ADDRESS,
767
        data=block_env.parent_beacon_block_root,
768
    )
769
770
    process_unchecked_system_transaction(
771
        block_env=block_env,
772
        target_address=HISTORY_STORAGE_ADDRESS,
773
        data=block_env.block_hashes[-1],  # The parent hash
774
    )
775
776
    for i, tx in enumerate(map(decode_transaction, transactions)):
777
        process_transaction(block_env, block_output, tx, Uint(i))
778
779
    process_withdrawals(block_env, block_output, withdrawals)
780
781
    process_general_purpose_requests(
782
        block_env=block_env,
783
        block_output=block_output,
784
    )
785
786
    return block_output

process_general_purpose_requests

Process all the requests in the block.

Parameters

block_env : The execution environment for the Block. block_output : The block output for the current block.

def process_general_purpose_requests(block_env: ethereum.forks.bpo5.vm.BlockEnvironment, ​​block_output: ethereum.forks.bpo5.vm.BlockOutput) -> None:
793
    """
794
    Process all the requests in the block.
795
796
    Parameters
797
    ----------
798
    block_env :
799
        The execution environment for the Block.
800
    block_output :
801
        The block output for the current block.
802
803
    """
804
    # Requests are to be in ascending order of request type
805
    deposit_requests = parse_deposit_requests(block_output)
806
    requests_from_execution = block_output.requests
807
    if len(deposit_requests) > 0:
808
        requests_from_execution.append(DEPOSIT_REQUEST_TYPE + deposit_requests)
809
810
    system_withdrawal_tx_output = process_checked_system_transaction(
811
        block_env=block_env,
812
        target_address=WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS,
813
        data=b"",
814
    )
815
816
    if len(system_withdrawal_tx_output.return_data) > 0:
817
        requests_from_execution.append(
818
            WITHDRAWAL_REQUEST_TYPE + system_withdrawal_tx_output.return_data
819
        )
820
821
    system_consolidation_tx_output = process_checked_system_transaction(
822
        block_env=block_env,
823
        target_address=CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS,
824
        data=b"",
825
    )
826
827
    if len(system_consolidation_tx_output.return_data) > 0:
828
        requests_from_execution.append(
829
            CONSOLIDATION_REQUEST_TYPE
830
            + system_consolidation_tx_output.return_data
831
        )

process_transaction

Execute a transaction against the provided environment.

This function processes the actions needed to execute a transaction. It decrements the sender's account balance after calculating the gas fee and refunds them the proper amount after execution. Calling contracts, deploying code, and incrementing nonces are all examples of actions that happen within this function or from a call made within this function.

Accounts that are marked for deletion are processed and destroyed after execution.

Parameters

block_env : Environment for the Ethereum Virtual Machine. block_output : The block output for the current block. tx : Transaction to execute. index: Index of the transaction in the block.

def process_transaction(block_env: ethereum.forks.bpo5.vm.BlockEnvironment, ​​block_output: ethereum.forks.bpo5.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
840
    """
841
    Execute a transaction against the provided environment.
842
843
    This function processes the actions needed to execute a transaction.
844
    It decrements the sender's account balance after calculating the gas fee
845
    and refunds them the proper amount after execution. Calling contracts,
846
    deploying code, and incrementing nonces are all examples of actions that
847
    happen within this function or from a call made within this function.
848
849
    Accounts that are marked for deletion are processed and destroyed after
850
    execution.
851
852
    Parameters
853
    ----------
854
    block_env :
855
        Environment for the Ethereum Virtual Machine.
856
    block_output :
857
        The block output for the current block.
858
    tx :
859
        Transaction to execute.
860
    index:
861
        Index of the transaction in the block.
862
863
    """
864
    tx_state = TransactionState(parent=block_env.state)
865
866
    trie_set(
867
        block_output.transactions_trie,
868
        rlp.encode(index),
869
        encode_transaction(tx),
870
    )
871
872
    intrinsic_gas, calldata_floor_gas_cost = validate_transaction(tx)
873
874
    (
875
        sender,
876
        effective_gas_price,
877
        blob_versioned_hashes,
878
        tx_blob_gas_used,
879
    ) = check_transaction(
880
        block_env=block_env,
881
        block_output=block_output,
882
        tx=tx,
883
        tx_state=tx_state,
884
    )
885
886
    sender_account = get_account(tx_state, sender)
887
888
    if isinstance(tx, BlobTransaction):
889
        blob_gas_fee = calculate_data_fee(block_env.excess_blob_gas, tx)
890
    else:
891
        blob_gas_fee = Uint(0)
892
893
    effective_gas_fee = tx.gas * effective_gas_price
894
895
    gas = tx.gas - intrinsic_gas
896
    increment_nonce(tx_state, sender)
897
898
    sender_balance_after_gas_fee = (
899
        Uint(sender_account.balance) - effective_gas_fee - blob_gas_fee
900
    )
901
    set_account_balance(tx_state, sender, U256(sender_balance_after_gas_fee))
902
903
    access_list_addresses = set()
904
    access_list_storage_keys = set()
905
    access_list_addresses.add(block_env.coinbase)
906
    if has_access_list(tx):
907
        for access in tx.access_list:
908
            access_list_addresses.add(access.account)
909
            for slot in access.slots:
910
                access_list_storage_keys.add((access.account, slot))
911
912
    authorizations: Tuple[Authorization, ...] = ()
913
    if isinstance(tx, SetCodeTransaction):
914
        authorizations = tx.authorizations
915
916
    tx_env = vm.TransactionEnvironment(
917
        origin=sender,
918
        gas_price=effective_gas_price,
919
        gas=gas,
920
        access_list_addresses=access_list_addresses,
921
        access_list_storage_keys=access_list_storage_keys,
922
        state=tx_state,
923
        blob_versioned_hashes=blob_versioned_hashes,
924
        authorizations=authorizations,
925
        index_in_block=index,
926
        tx_hash=get_transaction_hash(encode_transaction(tx)),
927
    )
928
929
    message = prepare_message(block_env, tx_env, tx)
930
931
    tx_output = process_message_call(message)
932
933
    # For EIP-7623 we first calculate the execution_gas_used, which includes
934
    # the execution gas refund.
935
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
936
    tx_gas_refund = min(
937
        tx_gas_used_before_refund // Uint(5), Uint(tx_output.refund_counter)
938
    )
939
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
940
941
    # Transactions with less execution_gas_used than the floor pay at the
942
    # floor cost.
943
    tx_gas_used_after_refund = max(
944
        tx_gas_used_after_refund, calldata_floor_gas_cost
945
    )
946
947
    tx_gas_left = tx.gas - tx_gas_used_after_refund
948
    gas_refund_amount = tx_gas_left * effective_gas_price
949
950
    # For non-1559 transactions effective_gas_price == tx.gas_price
951
    priority_fee_per_gas = effective_gas_price - block_env.base_fee_per_gas
952
    transaction_fee = tx_gas_used_after_refund * priority_fee_per_gas
953
954
    # refund gas
955
    sender_balance_after_refund = get_account(tx_state, sender).balance + U256(
956
        gas_refund_amount
957
    )
958
    set_account_balance(tx_state, sender, sender_balance_after_refund)
959
960
    # transfer miner fees
961
    coinbase_balance_after_mining_fee = get_account(
962
        tx_state, block_env.coinbase
963
    ).balance + U256(transaction_fee)
964
    set_account_balance(
965
        tx_state, block_env.coinbase, coinbase_balance_after_mining_fee
966
    )
967
968
    for address in tx_output.accounts_to_delete:
969
        destroy_account(tx_state, address)
970
971
    block_output.block_gas_used += tx_gas_used_after_refund
972
    block_output.blob_gas_used += tx_blob_gas_used
973
974
    receipt = make_receipt(
975
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
976
    )
977
978
    receipt_key = rlp.encode(Uint(index))
979
    block_output.receipt_keys += (receipt_key,)
980
981
    trie_set(
982
        block_output.receipts_trie,
983
        receipt_key,
984
        receipt,
985
    )
986
987
    block_output.block_logs += tx_output.logs
988
989
    incorporate_tx_into_block(tx_state)

process_withdrawals

Increase the balance of the withdrawing account.

def process_withdrawals(block_env: ethereum.forks.bpo5.vm.BlockEnvironment, ​​block_output: ethereum.forks.bpo5.vm.BlockOutput, ​​withdrawals: Tuple[Withdrawal, ...]) -> None:
997
    """
998
    Increase the balance of the withdrawing account.
999
    """
1000
    wd_state = TransactionState(parent=block_env.state)
1001
1002
    for i, wd in enumerate(withdrawals):
1003
        trie_set(
1004
            block_output.withdrawals_trie,
1005
            rlp.encode(Uint(i)),
1006
            rlp.encode(wd),
1007
        )
1008
1009
        create_ether(wd_state, wd.address, wd.amount * U256(10**9))
1010
1011
    incorporate_tx_into_block(wd_state)

check_gas_limit

Validates the gas limit for a block.

The bounds of the gas limit, max_adjustment_delta, is set as the quotient of the parent block's gas limit and the LIMIT_ADJUSTMENT_FACTOR. Therefore, if the gas limit that is passed through as a parameter is greater than or equal to the sum of the parent's gas and the adjustment delta then the limit for gas is too high and fails this function's check. Similarly, if the limit is less than or equal to the difference of the parent's gas and the adjustment delta or the predefined LIMIT_MINIMUM then this function's check fails because the gas limit doesn't allow for a sufficient or reasonable amount of gas to be used on a block.

Parameters

gas_limit : Gas limit to validate.

parent_gas_limit : Gas limit of the parent block.

Returns

check : bool True if gas limit constraints are satisfied, False otherwise.

def check_gas_limit(gas_limit: Uint, ​​parent_gas_limit: Uint) -> bool:
1015
    """
1016
    Validates the gas limit for a block.
1017
1018
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
1019
    quotient of the parent block's gas limit and the
1020
    ``LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is passed
1021
    through as a parameter is greater than or equal to the *sum* of the
1022
    parent's gas and the adjustment delta then the limit for gas is too high
1023
    and fails this function's check. Similarly, if the limit is less than or
1024
    equal to the *difference* of the parent's gas and the adjustment delta *or*
1025
    the predefined ``LIMIT_MINIMUM`` then this function's check fails because
1026
    the gas limit doesn't allow for a sufficient or reasonable amount of gas to
1027
    be used on a block.
1028
1029
    Parameters
1030
    ----------
1031
    gas_limit :
1032
        Gas limit to validate.
1033
1034
    parent_gas_limit :
1035
        Gas limit of the parent block.
1036
1037
    Returns
1038
    -------
1039
    check : `bool`
1040
        True if gas limit constraints are satisfied, False otherwise.
1041
1042
    """
1043
    max_adjustment_delta = parent_gas_limit // GasCosts.LIMIT_ADJUSTMENT_FACTOR
1044
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
1045
        return False
1046
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
1047
        return False
1048
    if gas_limit < GasCosts.LIMIT_MINIMUM:
1049
        return False
1050
1051
    return True