ethereum.forks.berlin.fork

Ethereum Specification.

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

62
BLOCK_REWARD = U256(2 * 10**18)

MINIMUM_DIFFICULTY

63
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

64
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

65
BOMB_DELAY_BLOCKS = 9000000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

69
@dataclass
class BlockChain:

blocks

75
    blocks: List[Block]

state

76
    state: State

chain_id

77
    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:
81
    """
82
    Transforms the state from the previous hard fork (`old`) into the block
83
    chain object for this hard fork and returns it.
84
85
    When forks need to implement an irregular state transition, this function
86
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
87
    an example.
88
89
    Parameters
90
    ----------
91
    old :
92
        Previous block chain object.
93
94
    Returns
95
    -------
96
    new : `BlockChain`
97
        Upgraded block chain object for this hard fork.
98
99
    """
100
    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]:
104
    """
105
    Obtain the list of hashes of the previous 256 blocks in order of
106
    increasing block number.
107
108
    This function will return less hashes for the first 256 blocks.
109
110
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
111
    therefore this function retrieves them.
112
113
    Parameters
114
    ----------
115
    chain :
116
        History and current state.
117
118
    Returns
119
    -------
120
    recent_block_hashes : `List[Hash32]`
121
        Hashes of the recent 256 blocks in order of increasing block number.
122
123
    """
124
    recent_blocks = chain.blocks[-255:]
125
    # TODO: This function has not been tested rigorously
126
    if len(recent_blocks) == 0:
127
        return []
128
129
    recent_block_hashes = []
130
131
    for block in recent_blocks:
132
        prev_block_hash = block.header.parent_hash
133
        recent_block_hashes.append(prev_block_hash)
134
135
    # We are computing the hash only for the most recent block and not for
136
    # the rest of the blocks as they have successors which have the hash of
137
    # the current block as parent hash.
138
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
139
    recent_block_hashes.append(most_recent_block_hash)
140
141
    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:
145
    """
146
    Attempts to apply a block to an existing block chain.
147
148
    All parts of the block's contents need to be verified before being added
149
    to the chain. Blocks are verified by ensuring that the contents of the
150
    block make logical sense with the contents of the parent block. The
151
    information in the block's header must also match the corresponding
152
    information in the block.
153
154
    To implement Ethereum, in theory clients are only required to store the
155
    most recent 255 blocks of the chain since as far as execution is
156
    concerned, only those blocks are accessed. Practically, however, clients
157
    should store more blocks to handle reorgs.
158
159
    Parameters
160
    ----------
161
    chain :
162
        History and current state.
163
    block :
164
        Block to apply to `chain`.
165
166
    """
167
    validate_header(chain, block.header)
168
    validate_ommers(block.ommers, block.header, chain)
169
170
    block_env = vm.BlockEnvironment(
171
        chain_id=chain.chain_id,
172
        state=chain.state,
173
        block_gas_limit=block.header.gas_limit,
174
        block_hashes=get_last_256_block_hashes(chain),
175
        coinbase=block.header.coinbase,
176
        number=block.header.number,
177
        time=block.header.timestamp,
178
        difficulty=block.header.difficulty,
179
    )
180
181
    block_output = apply_body(
182
        block_env=block_env,
183
        transactions=block.transactions,
184
        ommers=block.ommers,
185
    )
186
    block_state_root = state_root(block_env.state)
187
    transactions_root = root(block_output.transactions_trie)
188
    receipt_root = root(block_output.receipts_trie)
189
    block_logs_bloom = logs_bloom(block_output.block_logs)
190
191
    if block_output.block_gas_used != block.header.gas_used:
192
        raise InvalidBlock(
193
            f"{block_output.block_gas_used} != {block.header.gas_used}"
194
        )
195
    if transactions_root != block.header.transactions_root:
196
        raise InvalidBlock
197
    if block_state_root != block.header.state_root:
198
        raise InvalidBlock
199
    if receipt_root != block.header.receipt_root:
200
        raise InvalidBlock
201
    if block_logs_bloom != block.header.bloom:
202
        raise InvalidBlock
203
204
    chain.blocks.append(block)
205
    if len(chain.blocks) > 255:
206
        # Real clients have to store more blocks to deal with reorgs, but the
207
        # protocol only requires the last 255
208
        chain.blocks = chain.blocks[-255:]

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:
212
    """
213
    Verifies a block header.
214
215
    In order to consider a block's header valid, the logic for the
216
    quantities in the header should match the logic for the block itself.
217
    For example the header timestamp should be greater than the block's parent
218
    timestamp because the block was created *after* the parent block.
219
    Additionally, the block's number should be directly following the parent
220
    block's number since it is the next block in the sequence.
221
222
    Parameters
223
    ----------
224
    chain :
225
        History and current state.
226
    header :
227
        Header to check for correctness.
228
229
    """
230
    if header.number < Uint(1):
231
        raise InvalidBlock
232
    parent_header_number = header.number - Uint(1)
233
    first_block_number = chain.blocks[0].header.number
234
    last_block_number = chain.blocks[-1].header.number
235
236
    if (
237
        parent_header_number < first_block_number
238
        or parent_header_number > last_block_number
239
    ):
240
        raise InvalidBlock
241
242
    parent_header = chain.blocks[
243
        parent_header_number - first_block_number
244
    ].header
245
246
    if header.gas_used > header.gas_limit:
247
        raise InvalidBlock
248
249
    parent_has_ommers = parent_header.ommers_hash != EMPTY_OMMER_HASH
250
    if header.timestamp <= parent_header.timestamp:
251
        raise InvalidBlock
252
    if header.number != parent_header.number + Uint(1):
253
        raise InvalidBlock
254
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
255
        raise InvalidBlock
256
    if len(header.extra_data) > 32:
257
        raise InvalidBlock
258
259
    block_difficulty = calculate_block_difficulty(
260
        header.number,
261
        header.timestamp,
262
        parent_header.timestamp,
263
        parent_header.difficulty,
264
        parent_has_ommers,
265
    )
266
    if header.difficulty != block_difficulty:
267
        raise InvalidBlock
268
269
    block_parent_hash = keccak256(rlp.encode(parent_header))
270
    if header.parent_hash != block_parent_hash:
271
        raise InvalidBlock
272
273
    validate_proof_of_work(header)

generate_header_hash_for_pow

Generate rlp hash of the header which is to be used for Proof-of-Work verification.

In other words, the PoW artefacts mix_digest and nonce are ignored while calculating this hash.

A particular PoW is valid for a single hash, that hash is computed by this function. The nonce and mix_digest are omitted from this hash because they are being changed by miners in their search for a sufficient proof-of-work.

Parameters

header : The header object for which the hash is to be generated.

Returns

hash : Hash32 The PoW valid rlp hash of the passed in header.

def generate_header_hash_for_pow(header: Header) -> Hash32:
277
    """
278
    Generate rlp hash of the header which is to be used for Proof-of-Work
279
    verification.
280
281
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
282
    while calculating this hash.
283
284
    A particular PoW is valid for a single hash, that hash is computed by
285
    this function. The `nonce` and `mix_digest` are omitted from this hash
286
    because they are being changed by miners in their search for a sufficient
287
    proof-of-work.
288
289
    Parameters
290
    ----------
291
    header :
292
        The header object for which the hash is to be generated.
293
294
    Returns
295
    -------
296
    hash : `Hash32`
297
        The PoW valid rlp hash of the passed in header.
298
299
    """
300
    header_data_without_pow_artefacts = (
301
        header.parent_hash,
302
        header.ommers_hash,
303
        header.coinbase,
304
        header.state_root,
305
        header.transactions_root,
306
        header.receipt_root,
307
        header.bloom,
308
        header.difficulty,
309
        header.number,
310
        header.gas_limit,
311
        header.gas_used,
312
        header.timestamp,
313
        header.extra_data,
314
    )
315
316
    return keccak256(rlp.encode(header_data_without_pow_artefacts))

validate_proof_of_work

Validates the Proof of Work constraints.

In order to verify that a miner's proof-of-work is valid for a block, a mix-digest and result are calculated using the hashimoto_light hash function. The mix digest is a hash of the header and the nonce that is passed through and it confirms whether or not proof-of-work was done on the correct block. The result is the actual hash value of the block.

Parameters

header : Header of interest.

def validate_proof_of_work(header: Header) -> None:
320
    """
321
    Validates the Proof of Work constraints.
322
323
    In order to verify that a miner's proof-of-work is valid for a block, a
324
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
325
    hash function. The mix digest is a hash of the header and the nonce that
326
    is passed through and it confirms whether or not proof-of-work was done
327
    on the correct block. The result is the actual hash value of the block.
328
329
    Parameters
330
    ----------
331
    header :
332
        Header of interest.
333
334
    """
335
    header_hash = generate_header_hash_for_pow(header)
336
    # TODO: Memoize this somewhere and read from that data instead of
337
    # calculating cache for every block validation.
338
    cache = generate_cache(header.number)
339
    mix_digest, result = hashimoto_light(
340
        header_hash, header.nonce, cache, dataset_size(header.number)
341
    )
342
    if mix_digest != header.mix_digest:
343
        raise InvalidBlock
344
345
    limit = Uint(U256.MAX_VALUE) + Uint(1)
346
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
347
        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.

Raises

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.

def check_transaction(block_env: ethereum.forks.berlin.vm.BlockEnvironment, ​​block_output: ethereum.forks.berlin.vm.BlockOutput, ​​tx: Transaction) -> Address:
355
    """
356
    Check if the transaction is includable in the block.
357
358
    Parameters
359
    ----------
360
    block_env :
361
        The block scoped environment.
362
    block_output :
363
        The block output for the current block.
364
    tx :
365
        The transaction.
366
367
    Returns
368
    -------
369
    sender_address :
370
        The sender of the transaction.
371
372
    Raises
373
    ------
374
    GasUsedExceedsLimitError :
375
        If the gas used by the transaction exceeds the block's gas limit.
376
    NonceMismatchError :
377
        If the nonce of the transaction is not equal to the sender's nonce.
378
    InsufficientBalanceError :
379
        If the sender's balance is not enough to pay for the transaction.
380
    InvalidSenderError :
381
        If the transaction is from an address that does not exist anymore.
382
383
    """
384
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
385
    if tx.gas > gas_available:
386
        raise GasUsedExceedsLimitError("gas used exceeds limit")
387
    sender_address = recover_sender(block_env.chain_id, tx)
388
    sender_account = get_account(block_env.state, sender_address)
389
390
    max_gas_fee = tx.gas * tx.gas_price
391
392
    if sender_account.nonce > Uint(tx.nonce):
393
        raise NonceMismatchError("nonce too low")
394
    elif sender_account.nonce < Uint(tx.nonce):
395
        raise NonceMismatchError("nonce too high")
396
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
397
        raise InsufficientBalanceError("insufficient sender balance")
398
    if sender_account.code_hash != EMPTY_CODE_HASH:
399
        raise InvalidSenderError("not EOA")
400
401
    return sender_address

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:
410
    """
411
    Make the receipt for a transaction that was executed.
412
413
    Parameters
414
    ----------
415
    tx :
416
        The executed transaction.
417
    error :
418
        Error in the top level frame of the transaction, if any.
419
    cumulative_gas_used :
420
        The total gas used so far in the block after the transaction was
421
        executed.
422
    logs :
423
        The logs produced by the transaction.
424
425
    Returns
426
    -------
427
    receipt :
428
        The receipt for the transaction.
429
430
    """
431
    receipt = Receipt(
432
        succeeded=error is None,
433
        cumulative_gas_used=cumulative_gas_used,
434
        bloom=logs_bloom(logs),
435
        logs=logs,
436
    )
437
438
    return encode_receipt(tx, receipt)

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. ommers : Headers of ancestor blocks which are not direct parents (formerly uncles.)

Returns

block_output : The block output for the current block.

def apply_body(block_env: ethereum.forks.berlin.vm.BlockEnvironment, ​​transactions: Tuple[LegacyTransaction | Bytes, ...], ​​ommers: Tuple[Header, ...]) -> ethereum.forks.berlin.vm.BlockOutput:
446
    """
447
    Executes a block.
448
449
    Many of the contents of a block are stored in data structures called
450
    tries. There is a transactions trie which is similar to a ledger of the
451
    transactions stored in the current block. There is also a receipts trie
452
    which stores the results of executing a transaction, like the post state
453
    and gas used. This function creates and executes the block that is to be
454
    added to the chain.
455
456
    Parameters
457
    ----------
458
    block_env :
459
        The block scoped environment.
460
    transactions :
461
        Transactions included in the block.
462
    ommers :
463
        Headers of ancestor blocks which are not direct parents (formerly
464
        uncles.)
465
466
    Returns
467
    -------
468
    block_output :
469
        The block output for the current block.
470
471
    """
472
    block_output = vm.BlockOutput()
473
474
    for i, tx in enumerate(map(decode_transaction, transactions)):
475
        process_transaction(block_env, block_output, tx, Uint(i))
476
477
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
478
479
    return block_output

validate_ommers

Validates the ommers mentioned in the block.

An ommer block is a block that wasn't canonically added to the blockchain because it wasn't validated as fast as the canonical block but was mined at the same time.

To be considered valid, the ommers must adhere to the rules defined in the Ethereum protocol. The maximum amount of ommers is 2 per block and there cannot be duplicate ommers in a block. Many of the other ommer constraints are listed in the in-line comments of this function.

Parameters

ommers : List of ommers mentioned in the current block. block_header: The header of current block. chain : History and current state.

def validate_ommers(ommers: Tuple[Header, ...], ​​block_header: Header, ​​chain: BlockChain) -> None:
485
    """
486
    Validates the ommers mentioned in the block.
487
488
    An ommer block is a block that wasn't canonically added to the
489
    blockchain because it wasn't validated as fast as the canonical block
490
    but was mined at the same time.
491
492
    To be considered valid, the ommers must adhere to the rules defined in
493
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
494
    there cannot be duplicate ommers in a block. Many of the other ommer
495
    constraints are listed in the in-line comments of this function.
496
497
    Parameters
498
    ----------
499
    ommers :
500
        List of ommers mentioned in the current block.
501
    block_header:
502
        The header of current block.
503
    chain :
504
        History and current state.
505
506
    """
507
    block_hash = keccak256(rlp.encode(block_header))
508
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
509
        raise InvalidBlock
510
511
    if len(ommers) == 0:
512
        # Nothing to validate
513
        return
514
515
    # Check that each ommer satisfies the constraints of a header
516
    for ommer in ommers:
517
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
518
            raise InvalidBlock
519
        validate_header(chain, ommer)
520
    if len(ommers) > 2:
521
        raise InvalidBlock
522
523
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
524
    if len(ommers_hashes) != len(set(ommers_hashes)):
525
        raise InvalidBlock
526
527
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
528
    recent_canonical_block_hashes = {
529
        keccak256(rlp.encode(block.header))
530
        for block in recent_canonical_blocks
531
    }
532
    recent_ommers_hashes: Set[Hash32] = set()
533
    for block in recent_canonical_blocks:
534
        recent_ommers_hashes = recent_ommers_hashes.union(
535
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
536
        )
537
538
    for ommer_index, ommer in enumerate(ommers):
539
        ommer_hash = ommers_hashes[ommer_index]
540
        if ommer_hash == block_hash:
541
            raise InvalidBlock
542
        if ommer_hash in recent_canonical_block_hashes:
543
            raise InvalidBlock
544
        if ommer_hash in recent_ommers_hashes:
545
            raise InvalidBlock
546
547
        # Ommer age with respect to the current block. For example, an age of
548
        # 1 indicates that the ommer is a sibling of previous block.
549
        ommer_age = block_header.number - ommer.number
550
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
551
            raise InvalidBlock
552
        if ommer.parent_hash not in recent_canonical_block_hashes:
553
            raise InvalidBlock
554
        if ommer.parent_hash == block_header.parent_hash:
555
            raise InvalidBlock

pay_rewards

Pay rewards to the block miner as well as the ommers miners.

The miner of the canonical block is rewarded with the predetermined block reward, BLOCK_REWARD, plus a variable award based off of the number of ommer blocks that were mined around the same time, and included in the canonical block's header. An ommer block is a block that wasn't added to the canonical blockchain because it wasn't validated as fast as the accepted block but was mined at the same time. Although not all blocks that are mined are added to the canonical chain, miners are still paid a reward for their efforts. This reward is called an ommer reward and is calculated based on the number associated with the ommer block that they mined.

Parameters

state : Current account state. block_number : Position of the block within the chain. coinbase : Address of account which receives block reward and transaction fees. ommers : List of ommers mentioned in the current block.

def pay_rewards(state: State, ​​block_number: Uint, ​​coinbase: Address, ​​ommers: Tuple[Header, ...]) -> None:
564
    """
565
    Pay rewards to the block miner as well as the ommers miners.
566
567
    The miner of the canonical block is rewarded with the predetermined
568
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
569
    number of ommer blocks that were mined around the same time, and included
570
    in the canonical block's header. An ommer block is a block that wasn't
571
    added to the canonical blockchain because it wasn't validated as fast as
572
    the accepted block but was mined at the same time. Although not all blocks
573
    that are mined are added to the canonical chain, miners are still paid a
574
    reward for their efforts. This reward is called an ommer reward and is
575
    calculated based on the number associated with the ommer block that they
576
    mined.
577
578
    Parameters
579
    ----------
580
    state :
581
        Current account state.
582
    block_number :
583
        Position of the block within the chain.
584
    coinbase :
585
        Address of account which receives block reward and transaction fees.
586
    ommers :
587
        List of ommers mentioned in the current block.
588
589
    """
590
    ommer_count = U256(len(ommers))
591
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
592
    create_ether(state, coinbase, miner_reward)
593
594
    for ommer in ommers:
595
        # Ommer age with respect to the current block.
596
        ommer_age = U256(block_number - ommer.number)
597
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
598
        create_ether(state, ommer.coinbase, ommer_miner_reward)

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.berlin.vm.BlockEnvironment, ​​block_output: ethereum.forks.berlin.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
607
    """
608
    Execute a transaction against the provided environment.
609
610
    This function processes the actions needed to execute a transaction.
611
    It decrements the sender's account balance after calculating the gas fee
612
    and refunds them the proper amount after execution. Calling contracts,
613
    deploying code, and incrementing nonces are all examples of actions that
614
    happen within this function or from a call made within this function.
615
616
    Accounts that are marked for deletion are processed and destroyed after
617
    execution.
618
619
    Parameters
620
    ----------
621
    block_env :
622
        Environment for the Ethereum Virtual Machine.
623
    block_output :
624
        The block output for the current block.
625
    tx :
626
        Transaction to execute.
627
    index:
628
        Index of the transaction in the block.
629
630
    """
631
    trie_set(
632
        block_output.transactions_trie,
633
        rlp.encode(index),
634
        encode_transaction(tx),
635
    )
636
637
    intrinsic_gas = validate_transaction(tx)
638
639
    sender = check_transaction(
640
        block_env=block_env,
641
        block_output=block_output,
642
        tx=tx,
643
    )
644
645
    sender_account = get_account(block_env.state, sender)
646
647
    gas = tx.gas - intrinsic_gas
648
    increment_nonce(block_env.state, sender)
649
650
    gas_fee = tx.gas * tx.gas_price
651
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
652
    set_account_balance(
653
        block_env.state, sender, U256(sender_balance_after_gas_fee)
654
    )
655
656
    access_list_addresses = set()
657
    access_list_storage_keys = set()
658
    if isinstance(tx, AccessListTransaction):
659
        for access in tx.access_list:
660
            access_list_addresses.add(access.account)
661
            for slot in access.slots:
662
                access_list_storage_keys.add((access.account, slot))
663
664
    tx_env = vm.TransactionEnvironment(
665
        origin=sender,
666
        gas_price=tx.gas_price,
667
        gas=gas,
668
        access_list_addresses=access_list_addresses,
669
        access_list_storage_keys=access_list_storage_keys,
670
        index_in_block=index,
671
        tx_hash=get_transaction_hash(encode_transaction(tx)),
672
    )
673
674
    message = prepare_message(block_env, tx_env, tx)
675
676
    tx_output = process_message_call(message)
677
678
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
679
    tx_gas_refund = min(
680
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
681
    )
682
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
683
    tx_gas_left = tx.gas - tx_gas_used_after_refund
684
    gas_refund_amount = tx_gas_left * tx.gas_price
685
686
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
687
688
    # refund gas
689
    sender_balance_after_refund = get_account(
690
        block_env.state, sender
691
    ).balance + U256(gas_refund_amount)
692
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
693
694
    # transfer miner fees
695
    coinbase_balance_after_mining_fee = get_account(
696
        block_env.state, block_env.coinbase
697
    ).balance + U256(transaction_fee)
698
    if coinbase_balance_after_mining_fee != 0:
699
        set_account_balance(
700
            block_env.state,
701
            block_env.coinbase,
702
            coinbase_balance_after_mining_fee,
703
        )
704
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
705
        destroy_account(block_env.state, block_env.coinbase)
706
707
    for address in tx_output.accounts_to_delete:
708
        destroy_account(block_env.state, address)
709
710
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
711
712
    block_output.block_gas_used += tx_gas_used_after_refund
713
714
    receipt = make_receipt(
715
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
716
    )
717
718
    receipt_key = rlp.encode(Uint(index))
719
    block_output.receipt_keys += (receipt_key,)
720
721
    trie_set(
722
        block_output.receipts_trie,
723
        receipt_key,
724
        receipt,
725
    )
726
727
    block_output.block_logs += tx_output.logs

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:
731
    """
732
    Validates the gas limit for a block.
733
734
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
735
    quotient of the parent block's gas limit and the
736
    ``LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is passed
737
    through as a parameter is greater than or equal to the *sum* of the
738
    parent's gas and the adjustment delta then the limit for gas is too high
739
    and fails this function's check. Similarly, if the limit is less than or
740
    equal to the *difference* of the parent's gas and the adjustment delta *or*
741
    the predefined ``LIMIT_MINIMUM`` then this function's check fails because
742
    the gas limit doesn't allow for a sufficient or reasonable amount of gas to
743
    be used on a block.
744
745
    Parameters
746
    ----------
747
    gas_limit :
748
        Gas limit to validate.
749
750
    parent_gas_limit :
751
        Gas limit of the parent block.
752
753
    Returns
754
    -------
755
    check : `bool`
756
        True if gas limit constraints are satisfied, False otherwise.
757
758
    """
759
    max_adjustment_delta = parent_gas_limit // GasCosts.LIMIT_ADJUSTMENT_FACTOR
760
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
761
        return False
762
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
763
        return False
764
    if gas_limit < GasCosts.LIMIT_MINIMUM:
765
        return False
766
767
    return True

calculate_block_difficulty

Computes difficulty of a block using its header and parent header.

The difficulty is determined by the time the block was created after its parent. The offset is calculated using the parent block's difficulty, parent_difficulty, and the timestamp between blocks. This offset is then added to the parent difficulty and is stored as the difficulty variable. If the time between the block and its parent is too short, the offset will result in a positive number thus making the sum of parent_difficulty and offset to be a greater value in order to avoid mass forking. But, if the time is long enough, then the offset results in a negative value making the block less difficult than its parent.

The base standard for a block's difficulty is the predefined value set for the genesis block since it has no parent. So, a block can't be less difficult than the genesis block, therefore each block's difficulty is set to the maximum value between the calculated difficulty and the MINIMUM_DIFFICULTY.

Parameters

block_number : Block number of the block. block_timestamp : Timestamp of the block. parent_timestamp : Timestamp of the parent block. parent_difficulty : difficulty of the parent block. parent_has_ommers: does the parent have ommers.

Returns

difficulty : ethereum.base_types.Uint Computed difficulty for a block.

def calculate_block_difficulty(block_number: Uint, ​​block_timestamp: U256, ​​parent_timestamp: U256, ​​parent_difficulty: Uint, ​​parent_has_ommers: bool) -> Uint:
777
    """
778
    Computes difficulty of a block using its header and parent header.
779
780
    The difficulty is determined by the time the block was created after its
781
    parent. The ``offset`` is calculated using the parent block's difficulty,
782
    ``parent_difficulty``, and the timestamp between blocks. This offset is
783
    then added to the parent difficulty and is stored as the ``difficulty``
784
    variable. If the time between the block and its parent is too short, the
785
    offset will result in a positive number thus making the sum of
786
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
787
    avoid mass forking. But, if the time is long enough, then the offset
788
    results in a negative value making the block less difficult than
789
    its parent.
790
791
    The base standard for a block's difficulty is the predefined value
792
    set for the genesis block since it has no parent. So, a block
793
    can't be less difficult than the genesis block, therefore each block's
794
    difficulty is set to the maximum value between the calculated
795
    difficulty and the ``MINIMUM_DIFFICULTY``.
796
797
    Parameters
798
    ----------
799
    block_number :
800
        Block number of the block.
801
    block_timestamp :
802
        Timestamp of the block.
803
    parent_timestamp :
804
        Timestamp of the parent block.
805
    parent_difficulty :
806
        difficulty of the parent block.
807
    parent_has_ommers:
808
        does the parent have ommers.
809
810
    Returns
811
    -------
812
    difficulty : `ethereum.base_types.Uint`
813
        Computed difficulty for a block.
814
815
    """
816
    offset = (
817
        int(parent_difficulty)
818
        // 2048
819
        * max(
820
            (2 if parent_has_ommers else 1)
821
            - int(block_timestamp - parent_timestamp) // 9,
822
            -99,
823
        )
824
    )
825
    difficulty = int(parent_difficulty) + offset
826
    # Historical Note: The difficulty bomb was not present in Ethereum at the
827
    # start of Frontier, but was added shortly after launch. However since the
828
    # bomb has no effect prior to block 200000 we pretend it existed from
829
    # genesis.
830
    # See https://github.com/ethereum/go-ethereum/pull/1588
831
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
832
    if num_bomb_periods >= 0:
833
        difficulty += 2**num_bomb_periods
834
835
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
836
    # the bomb. This bug does not matter because the difficulty is always much
837
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
838
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))