ethereum.forks.shanghai.forkethereum.forks.cancun.fork

Ethereum Specification.

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

Introduction

Entry point for the Ethereum specification.

BASE_FEE_MAX_CHANGE_DENOMINATOR

78
BASE_FEE_MAX_CHANGE_DENOMINATOR = Uint(8)

ELASTICITY_MULTIPLIER

79
ELASTICITY_MULTIPLIER = Uint(2)

GAS_LIMIT_ADJUSTMENT_FACTOR

80
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

81
GAS_LIMIT_MINIMUM = Uint(5000)

EMPTY_OMMER_HASH

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

SYSTEM_ADDRESS

83
SYSTEM_ADDRESS = hex_to_address("0xfffffffffffffffffffffffffffffffffffffffe")

BEACON_ROOTS_ADDRESS

84
BEACON_ROOTS_ADDRESS = hex_to_address(
85
    "0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02"
86
)

SYSTEM_TRANSACTION_GAS

87
SYSTEM_TRANSACTION_GAS = Uint(30000000)

MAX_BLOB_GAS_PER_BLOCK

88
MAX_BLOB_GAS_PER_BLOCK = U64(786432)

VERSIONED_HASH_VERSION_KZG

89
VERSIONED_HASH_VERSION_KZG = b"\x01"

BlockChain

History and current state of the block chain.

92
@dataclass
class BlockChain:

blocks

98
    blocks: List[Block]

state

99
    state: State

chain_id

100
    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:
104
    """
105
    Transforms the state from the previous hard fork (`old`) into the block
106
    chain object for this hard fork and returns it.
107
108
    When forks need to implement an irregular state transition, this function
109
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
110
    an example.
111
112
    Parameters
113
    ----------
114
    old :
115
        Previous block chain object.
116
117
    Returns
118
    -------
119
    new : `BlockChain`
120
        Upgraded block chain object for this hard fork.
121
122
    """
123
    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]:
127
    """
128
    Obtain the list of hashes of the previous 256 blocks in order of
129
    increasing block number.
130
131
    This function will return less hashes for the first 256 blocks.
132
133
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
134
    therefore this function retrieves them.
135
136
    Parameters
137
    ----------
138
    chain :
139
        History and current state.
140
141
    Returns
142
    -------
143
    recent_block_hashes : `List[Hash32]`
144
        Hashes of the recent 256 blocks in order of increasing block number.
145
146
    """
147
    recent_blocks = chain.blocks[-255:]
148
    # TODO: This function has not been tested rigorously
149
    if len(recent_blocks) == 0:
150
        return []
151
152
    recent_block_hashes = []
153
154
    for block in recent_blocks:
155
        prev_block_hash = block.header.parent_hash
156
        recent_block_hashes.append(prev_block_hash)
157
158
    # We are computing the hash only for the most recent block and not for
159
    # the rest of the blocks as they have successors which have the hash of
160
    # the current block as parent hash.
161
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
162
    recent_block_hashes.append(most_recent_block_hash)
163
164
    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:
168
    """
169
    Attempts to apply a block to an existing block chain.
170
171
    All parts of the block's contents need to be verified before being added
172
    to the chain. Blocks are verified by ensuring that the contents of the
173
    block make logical sense with the contents of the parent block. The
174
    information in the block's header must also match the corresponding
175
    information in the block.
176
177
    To implement Ethereum, in theory clients are only required to store the
178
    most recent 255 blocks of the chain since as far as execution is
179
    concerned, only those blocks are accessed. Practically, however, clients
180
    should store more blocks to handle reorgs.
181
182
    Parameters
183
    ----------
184
    chain :
185
        History and current state.
186
    block :
187
        Block to apply to `chain`.
188
189
    """
190
    validate_header(chain, block.header)
191
    if block.ommers != ():
192
        raise InvalidBlock
193
194
    block_env = vm.BlockEnvironment(
195
        chain_id=chain.chain_id,
196
        state=chain.state,
197
        block_gas_limit=block.header.gas_limit,
198
        block_hashes=get_last_256_block_hashes(chain),
199
        coinbase=block.header.coinbase,
200
        number=block.header.number,
201
        base_fee_per_gas=block.header.base_fee_per_gas,
202
        time=block.header.timestamp,
203
        prev_randao=block.header.prev_randao,
204
        excess_blob_gas=block.header.excess_blob_gas,
205
        parent_beacon_block_root=block.header.parent_beacon_block_root,
206
    )
207
208
    block_output = apply_body(
209
        block_env=block_env,
210
        transactions=block.transactions,
211
        withdrawals=block.withdrawals,
212
    )
213
    block_state_root = state_root(block_env.state)
214
    transactions_root = root(block_output.transactions_trie)
215
    receipt_root = root(block_output.receipts_trie)
216
    block_logs_bloom = logs_bloom(block_output.block_logs)
217
    withdrawals_root = root(block_output.withdrawals_trie)
218
219
    if block_output.block_gas_used != block.header.gas_used:
220
        raise InvalidBlock(
221
            f"{block_output.block_gas_used} != {block.header.gas_used}"
222
        )
223
    if transactions_root != block.header.transactions_root:
224
        raise InvalidBlock
225
    if block_state_root != block.header.state_root:
226
        raise InvalidBlock
227
    if receipt_root != block.header.receipt_root:
228
        raise InvalidBlock
229
    if block_logs_bloom != block.header.bloom:
230
        raise InvalidBlock
231
    if withdrawals_root != block.header.withdrawals_root:
232
        raise InvalidBlock
233
    if block_output.blob_gas_used != block.header.blob_gas_used:
234
        raise InvalidBlock
235
236
    chain.blocks.append(block)
237
    if len(chain.blocks) > 255:
238
        # Real clients have to store more blocks to deal with reorgs, but the
239
        # protocol only requires the last 255
240
        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:
249
    """
250
    Calculates the base fee per gas for the block.
251
252
    Parameters
253
    ----------
254
    block_gas_limit :
255
        Gas limit of the block for which the base fee is being calculated.
256
    parent_gas_limit :
257
        Gas limit of the parent block.
258
    parent_gas_used :
259
        Gas used in the parent block.
260
    parent_base_fee_per_gas :
261
        Base fee per gas of the parent block.
262
263
    Returns
264
    -------
265
    base_fee_per_gas : `Uint`
266
        Base fee per gas for the block.
267
268
    """
269
    parent_gas_target = parent_gas_limit // ELASTICITY_MULTIPLIER
270
    if not check_gas_limit(block_gas_limit, parent_gas_limit):
271
        raise InvalidBlock
272
273
    if parent_gas_used == parent_gas_target:
274
        expected_base_fee_per_gas = parent_base_fee_per_gas
275
    elif parent_gas_used > parent_gas_target:
276
        gas_used_delta = parent_gas_used - parent_gas_target
277
278
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
279
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
280
281
        base_fee_per_gas_delta = max(
282
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR,
283
            Uint(1),
284
        )
285
286
        expected_base_fee_per_gas = (
287
            parent_base_fee_per_gas + base_fee_per_gas_delta
288
        )
289
    else:
290
        gas_used_delta = parent_gas_target - parent_gas_used
291
292
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
293
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
294
295
        base_fee_per_gas_delta = (
296
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR
297
        )
298
299
        expected_base_fee_per_gas = (
300
            parent_base_fee_per_gas - base_fee_per_gas_delta
301
        )
302
303
    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:
307
    """
308
    Verifies a block header.
309
310
    In order to consider a block's header valid, the logic for the
311
    quantities in the header should match the logic for the block itself.
312
    For example the header timestamp should be greater than the block's parent
313
    timestamp because the block was created *after* the parent block.
314
    Additionally, the block's number should be directly following the parent
315
    block's number since it is the next block in the sequence.
316
317
    Parameters
318
    ----------
319
    chain :
320
        History and current state.
321
    header :
322
        Header to check for correctness.
323
324
    """
325
    if header.number < Uint(1):
326
        raise InvalidBlock
327
328
    parent_header = chain.blocks[-1].header
329
330
    excess_blob_gas = calculate_excess_blob_gas(parent_header)
331
    if header.excess_blob_gas != excess_blob_gas:
332
        raise InvalidBlock
333
334
    if header.gas_used > header.gas_limit:
335
        raise InvalidBlock
336
337
    expected_base_fee_per_gas = calculate_base_fee_per_gas(
338
        header.gas_limit,
339
        parent_header.gas_limit,
340
        parent_header.gas_used,
341
        parent_header.base_fee_per_gas,
342
    )
343
    if expected_base_fee_per_gas != header.base_fee_per_gas:
344
        raise InvalidBlock
345
    if header.timestamp <= parent_header.timestamp:
346
        raise InvalidBlock
347
    if header.number != parent_header.number + Uint(1):
348
        raise InvalidBlock
349
    if len(header.extra_data) > 32:
350
        raise InvalidBlock
351
    if header.difficulty != 0:
352
        raise InvalidBlock
353
    if header.nonce != b"\x00\x00\x00\x00\x00\x00\x00\x00":
354
        raise InvalidBlock
355
    if header.ommers_hash != EMPTY_OMMER_HASH:
356
        raise InvalidBlock
357
358
    block_parent_hash = keccak256(rlp.encode(parent_header))
359
    if header.parent_hash != block_parent_hash:
360
        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.

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. TransactionTypeContractCreationError: If the transaction type is not allowed to create contracts.

def check_transaction(block_env: ethereum.forks.shanghai.vm.BlockEnvironmentethereum.forks.cancun.vm.BlockEnvironment, ​​block_output: ethereum.forks.shanghai.vm.BlockOutputethereum.forks.cancun.vm.BlockOutput, ​​tx: Transaction) -> Tuple[Address, Uint, Tuple[VersionedHash, ...]U64]:
368
    """
369
    Check if the transaction is includable in the block.
370
371
    Parameters
372
    ----------
373
    block_env :
374
        The block scoped environment.
375
    block_output :
376
        The block output for the current block.
377
    tx :
378
        The transaction.
379
380
    Returns
381
    -------
382
    sender_address :
383
        The sender of the transaction.
384
    effective_gas_price :
385
        The price to charge for gas when the transaction is executed.
386
    blob_versioned_hashes :
387
        The blob versioned hashes of the transaction.
388
    tx_blob_gas_used:
389
        The blob gas used by the transaction.
390
391
    Raises
392
    ------
393
    InvalidBlock :
394
        If the transaction is not includable.
395
    GasUsedExceedsLimitError :
396
        If the gas used by the transaction exceeds the block's gas limit.
397
    NonceMismatchError :
398
        If the nonce of the transaction is not equal to the sender's nonce.
399
    InsufficientBalanceError :
400
        If the sender's balance is not enough to pay for the transaction.
401
    InvalidSenderError :
402
        If the transaction is from an address that does not exist anymore.
403
    PriorityFeeGreaterThanMaxFeeError :
404
        If the priority fee is greater than the maximum fee per gas.
405
    InsufficientMaxFeePerGasError :
406
        If the maximum fee per gas is insufficient for the transaction.
407
    InsufficientMaxFeePerBlobGasError :
408
        If the maximum fee per blob gas is insufficient for the transaction.
409
    BlobGasLimitExceededError :
410
        If the blob gas used by the transaction exceeds the block's blob gas
411
        limit.
412
    InvalidBlobVersionedHashError :
413
        If the transaction contains a blob versioned hash with an invalid
414
        version.
415
    NoBlobDataError :
416
        If the transaction is a type 3 but has no blobs.
417
    TransactionTypeContractCreationError:
418
        If the transaction type is not allowed to create contracts.
419
420
    """
421
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
422
    blob_gas_available = MAX_BLOB_GAS_PER_BLOCK - block_output.blob_gas_used
423
424
    if tx.gas > gas_available:
425
        raise GasUsedExceedsLimitError("gas used exceeds limit")
426
427
    tx_blob_gas_used = calculate_total_blob_gas(tx)
428
    if tx_blob_gas_used > blob_gas_available:
429
        raise BlobGasLimitExceededError("blob gas limit exceeded")
430
431
    sender_address = recover_sender(block_env.chain_id, tx)
432
    sender_account = get_account(block_env.state, sender_address)
433
381
    if isinstance(tx, FeeMarketTransaction):
434
    if isinstance(tx, (FeeMarketTransaction, BlobTransaction)):
435
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
436
            raise PriorityFeeGreaterThanMaxFeeError(
437
                "priority fee greater than max fee"
438
            )
439
        if tx.max_fee_per_gas < block_env.base_fee_per_gas:
440
            raise InsufficientMaxFeePerGasError(
441
                tx.max_fee_per_gas, block_env.base_fee_per_gas
442
            )
443
444
        priority_fee_per_gas = min(
445
            tx.max_priority_fee_per_gas,
446
            tx.max_fee_per_gas - block_env.base_fee_per_gas,
447
        )
448
        effective_gas_price = priority_fee_per_gas + block_env.base_fee_per_gas
449
        max_gas_fee = tx.gas * tx.max_fee_per_gas
450
    else:
451
        if tx.gas_price < block_env.base_fee_per_gas:
452
            raise InvalidBlock
453
        effective_gas_price = tx.gas_price
454
        max_gas_fee = tx.gas * tx.gas_price
455
456
    if isinstance(tx, BlobTransaction):
457
        if not isinstance(tx.to, Address):
458
            raise TransactionTypeContractCreationError(tx)
459
        if len(tx.blob_versioned_hashes) == 0:
460
            raise NoBlobDataError("no blob data in transaction")
461
        for blob_versioned_hash in tx.blob_versioned_hashes:
462
            if blob_versioned_hash[0:1] != VERSIONED_HASH_VERSION_KZG:
463
                raise InvalidBlobVersionedHashError(
464
                    "invalid blob versioned hash"
465
                )
466
467
        blob_gas_price = calculate_blob_gas_price(block_env.excess_blob_gas)
468
        if Uint(tx.max_fee_per_blob_gas) < blob_gas_price:
469
            raise InsufficientMaxFeePerBlobGasError(
470
                "insufficient max fee per blob gas"
471
            )
472
473
        max_gas_fee += Uint(calculate_total_blob_gas(tx)) * Uint(
474
            tx.max_fee_per_blob_gas
475
        )
476
        blob_versioned_hashes = tx.blob_versioned_hashes
477
    else:
478
        blob_versioned_hashes = ()
479
    if sender_account.nonce > Uint(tx.nonce):
480
        raise NonceMismatchError("nonce too low")
481
    elif sender_account.nonce < Uint(tx.nonce):
482
        raise NonceMismatchError("nonce too high")
483
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
484
        raise InsufficientBalanceError("insufficient sender balance")
485
    if sender_account.code:
486
        raise InvalidSenderError("not EOA")
487
412
    return sender_address, effective_gas_price
488
    return (
489
        sender_address,
490
        effective_gas_price,
491
        blob_versioned_hashes,
492
        tx_blob_gas_used,
493
    )

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:
502
    """
503
    Make the receipt for a transaction that was executed.
504
505
    Parameters
506
    ----------
507
    tx :
508
        The executed transaction.
509
    error :
510
        Error in the top level frame of the transaction, if any.
511
    cumulative_gas_used :
512
        The total gas used so far in the block after the transaction was
513
        executed.
514
    logs :
515
        The logs produced by the transaction.
516
517
    Returns
518
    -------
519
    receipt :
520
        The receipt for the transaction.
521
522
    """
523
    receipt = Receipt(
524
        succeeded=error is None,
525
        cumulative_gas_used=cumulative_gas_used,
526
        bloom=logs_bloom(logs),
527
        logs=logs,
528
    )
529
530
    return encode_receipt(tx, receipt)

process_system_transaction

Process a system transaction with the given code.

Prefer calling process_unchecked_system_transaction unless the contract code has already been read from the state.

Parameters

block_env : The block scoped environment. target_address : Address of the contract to call. system_contract_code : Code 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_system_transaction(block_env: ethereum.forks.cancun.vm.BlockEnvironment, ​​target_address: Address, ​​system_contract_code: Bytes, ​​data: Bytes) -> MessageCallOutput:
539
    """
540
    Process a system transaction with the given code.
541
542
    Prefer calling `process_unchecked_system_transaction` unless the contract
543
    code has already been read from the state.
544
545
    Parameters
546
    ----------
547
    block_env :
548
        The block scoped environment.
549
    target_address :
550
        Address of the contract to call.
551
    system_contract_code :
552
        Code of the contract to call.
553
    data :
554
        Data to pass to the contract.
555
556
    Returns
557
    -------
558
    system_tx_output : `MessageCallOutput`
559
        Output of processing the system transaction.
560
561
    """
562
    tx_env = vm.TransactionEnvironment(
563
        origin=SYSTEM_ADDRESS,
564
        gas_price=block_env.base_fee_per_gas,
565
        gas=SYSTEM_TRANSACTION_GAS,
566
        access_list_addresses=set(),
567
        access_list_storage_keys=set(),
568
        transient_storage=TransientStorage(),
569
        blob_versioned_hashes=(),
570
        index_in_block=None,
571
        tx_hash=None,
572
    )
573
574
    system_tx_message = Message(
575
        block_env=block_env,
576
        tx_env=tx_env,
577
        caller=SYSTEM_ADDRESS,
578
        target=target_address,
579
        gas=SYSTEM_TRANSACTION_GAS,
580
        value=U256(0),
581
        data=data,
582
        code=system_contract_code,
583
        depth=Uint(0),
584
        current_target=target_address,
585
        code_address=target_address,
586
        should_transfer_value=False,
587
        is_static=False,
588
        accessed_addresses=set(),
589
        accessed_storage_keys=set(),
590
        parent_evm=None,
591
    )
592
593
    system_tx_output = process_message_call(system_tx_message)
594
595
    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.cancun.vm.BlockEnvironment, ​​target_address: Address, ​​data: Bytes) -> MessageCallOutput:
603
    """
604
    Process a system transaction without checking if the contract contains code
605
    or if the transaction fails.
606
607
    Parameters
608
    ----------
609
    block_env :
610
        The block scoped environment.
611
    target_address :
612
        Address of the contract to call.
613
    data :
614
        Data to pass to the contract.
615
616
    Returns
617
    -------
618
    system_tx_output : `MessageCallOutput`
619
        Output of processing the system transaction.
620
621
    """
622
    system_contract_code = get_account(block_env.state, target_address).code
623
    return process_system_transaction(
624
        block_env,
625
        target_address,
626
        system_contract_code,
627
        data,
628
    )

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. block_output : The block output for the current block. 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.shanghai.vm.BlockEnvironmentethereum.forks.cancun.vm.BlockEnvironment, ​​transactions: Tuple[LegacyTransaction | Bytes, ...], ​​withdrawals: Tuple[Withdrawal, ...]) -> ethereum.forks.shanghai.vm.BlockOutputethereum.forks.cancun.vm.BlockOutput:
636
    """
637
    Executes a block.
638
639
    Many of the contents of a block are stored in data structures called
640
    tries. There is a transactions trie which is similar to a ledger of the
641
    transactions stored in the current block. There is also a receipts trie
642
    which stores the results of executing a transaction, like the post state
643
    and gas used. This function creates and executes the block that is to be
644
    added to the chain.
645
646
    Parameters
647
    ----------
648
    block_env :
649
        The block scoped environment.
471
    block_output :
472
        The block output for the current block.
650
    transactions :
651
        Transactions included in the block.
652
    withdrawals :
653
        Withdrawals to be processed in the current block.
654
655
    Returns
656
    -------
657
    block_output :
658
        The block output for the current block.
659
660
    """
661
    block_output = vm.BlockOutput()
662
663
    process_unchecked_system_transaction(
664
        block_env=block_env,
665
        target_address=BEACON_ROOTS_ADDRESS,
666
        data=block_env.parent_beacon_block_root,
667
    )
668
669
    for i, tx in enumerate(map(decode_transaction, transactions)):
670
        process_transaction(block_env, block_output, tx, Uint(i))
671
672
    process_withdrawals(block_env, block_output, withdrawals)
673
674
    return block_output

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.shanghai.vm.BlockEnvironmentethereum.forks.cancun.vm.BlockEnvironment, ​​block_output: ethereum.forks.shanghai.vm.BlockOutputethereum.forks.cancun.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
683
    """
684
    Execute a transaction against the provided environment.
685
686
    This function processes the actions needed to execute a transaction.
687
    It decrements the sender's account balance after calculating the gas fee
688
    and refunds them the proper amount after execution. Calling contracts,
689
    deploying code, and incrementing nonces are all examples of actions that
690
    happen within this function or from a call made within this function.
691
692
    Accounts that are marked for deletion are processed and destroyed after
693
    execution.
694
695
    Parameters
696
    ----------
697
    block_env :
698
        Environment for the Ethereum Virtual Machine.
699
    block_output :
700
        The block output for the current block.
701
    tx :
702
        Transaction to execute.
703
    index:
704
        Index of the transaction in the block.
705
706
    """
707
    trie_set(
708
        block_output.transactions_trie,
709
        rlp.encode(index),
710
        encode_transaction(tx),
711
    )
712
713
    intrinsic_gas = validate_transaction(tx)
714
715
    (
716
        sender,
534
        effective_gas_price,
717
        effective_gas_price,
718
        blob_versioned_hashes,
719
        tx_blob_gas_used,
720
    ) = check_transaction(
721
        block_env=block_env,
722
        block_output=block_output,
723
        tx=tx,
724
    )
725
726
    sender_account = get_account(block_env.state, sender)
727
728
    if isinstance(tx, BlobTransaction):
729
        blob_gas_fee = calculate_data_fee(block_env.excess_blob_gas, tx)
730
    else:
731
        blob_gas_fee = Uint(0)
732
733
    effective_gas_fee = tx.gas * effective_gas_price
734
735
    gas = tx.gas - intrinsic_gas
736
    increment_nonce(block_env.state, sender)
737
738
    sender_balance_after_gas_fee = (
549
        Uint(sender_account.balance) - effective_gas_fee
739
        Uint(sender_account.balance) - effective_gas_fee - blob_gas_fee
740
    )
741
    set_account_balance(
742
        block_env.state, sender, U256(sender_balance_after_gas_fee)
743
    )
744
745
    access_list_addresses = set()
746
    access_list_storage_keys = set()
747
    access_list_addresses.add(block_env.coinbase)
558
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
748
    if isinstance(
749
        tx, (AccessListTransaction, FeeMarketTransaction, BlobTransaction)
750
    ):
751
        for access in tx.access_list:
752
            access_list_addresses.add(access.account)
753
            for slot in access.slots:
754
                access_list_storage_keys.add((access.account, slot))
755
756
    tx_env = vm.TransactionEnvironment(
757
        origin=sender,
758
        gas_price=effective_gas_price,
759
        gas=gas,
760
        access_list_addresses=access_list_addresses,
761
        access_list_storage_keys=access_list_storage_keys,
762
        transient_storage=TransientStorage(),
763
        blob_versioned_hashes=blob_versioned_hashes,
764
        index_in_block=index,
765
        tx_hash=get_transaction_hash(encode_transaction(tx)),
766
    )
767
768
    message = prepare_message(block_env, tx_env, tx)
769
770
    tx_output = process_message_call(message)
771
772
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
773
    tx_gas_refund = min(
774
        tx_gas_used_before_refund // Uint(5), Uint(tx_output.refund_counter)
775
    )
776
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
777
    tx_gas_left = tx.gas - tx_gas_used_after_refund
778
    gas_refund_amount = tx_gas_left * effective_gas_price
779
780
    # For non-1559 transactions effective_gas_price == tx.gas_price
781
    priority_fee_per_gas = effective_gas_price - block_env.base_fee_per_gas
782
    transaction_fee = tx_gas_used_after_refund * priority_fee_per_gas
783
784
    # refund gas
785
    sender_balance_after_refund = get_account(
786
        block_env.state, sender
787
    ).balance + U256(gas_refund_amount)
788
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
789
790
    # transfer miner fees
791
    coinbase_balance_after_mining_fee = get_account(
792
        block_env.state, block_env.coinbase
793
    ).balance + U256(transaction_fee)
794
    set_account_balance(
795
        block_env.state,
796
        block_env.coinbase,
797
        coinbase_balance_after_mining_fee,
798
    )
799
800
    for address in tx_output.accounts_to_delete:
801
        destroy_account(block_env.state, address)
802
803
    block_output.block_gas_used += tx_gas_used_after_refund
804
    block_output.blob_gas_used += tx_blob_gas_used
805
806
    receipt = make_receipt(
807
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
808
    )
809
810
    receipt_key = rlp.encode(Uint(index))
811
    block_output.receipt_keys += (receipt_key,)
812
813
    trie_set(
814
        block_output.receipts_trie,
815
        receipt_key,
816
        receipt,
817
    )
818
819
    block_output.block_logs += tx_output.logs

process_withdrawals

Increase the balance of the withdrawing account.

def process_withdrawals(block_env: ethereum.forks.shanghai.vm.BlockEnvironmentethereum.forks.cancun.vm.BlockEnvironment, ​​block_output: ethereum.forks.shanghai.vm.BlockOutputethereum.forks.cancun.vm.BlockOutput, ​​withdrawals: Tuple[Withdrawal, ...]) -> None:
827
    """
828
    Increase the balance of the withdrawing account.
829
    """
830
831
    def increase_recipient_balance(recipient: Account) -> None:
832
        recipient.balance += wd.amount * U256(10**9)
833
834
    for i, wd in enumerate(withdrawals):
835
        trie_set(
836
            block_output.withdrawals_trie,
837
            rlp.encode(Uint(i)),
838
            rlp.encode(wd),
839
        )
840
841
        modify_state(block_env.state, wd.address, increase_recipient_balance)

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 GAS_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 GAS_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:
845
    """
846
    Validates the gas limit for a block.
847
848
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
849
    quotient of the parent block's gas limit and the
850
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
851
    passed through as a parameter is greater than or equal to the *sum* of
852
    the parent's gas and the adjustment delta then the limit for gas is too
853
    high and fails this function's check. Similarly, if the limit is less
854
    than or equal to the *difference* of the parent's gas and the adjustment
855
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
856
    check fails because the gas limit doesn't allow for a sufficient or
857
    reasonable amount of gas to be used on a block.
858
859
    Parameters
860
    ----------
861
    gas_limit :
862
        Gas limit to validate.
863
864
    parent_gas_limit :
865
        Gas limit of the parent block.
866
867
    Returns
868
    -------
869
    check : `bool`
870
        True if gas limit constraints are satisfied, False otherwise.
871
872
    """
873
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
874
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
875
        return False
876
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
877
        return False
878
    if gas_limit < GAS_LIMIT_MINIMUM:
879
        return False
880
881
    return True