ethereum.london.fork

Ethereum Specification ^^^^^^^^^^^^^^^^^^^^^^

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

BASE_FEE_MAX_CHANGE_DENOMINATOR

60
BASE_FEE_MAX_CHANGE_DENOMINATOR = Uint(8)

ELASTICITY_MULTIPLIER

61
ELASTICITY_MULTIPLIER = Uint(2)

GAS_LIMIT_ADJUSTMENT_FACTOR

62
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

63
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

64
MINIMUM_DIFFICULTY = Uint(131072)

INITIAL_BASE_FEE

65
INITIAL_BASE_FEE = Uint(1000000000)

MAX_OMMER_DEPTH

66
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

67
BOMB_DELAY_BLOCKS = 9700000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

71
@dataclass
class BlockChain:

blocks

77
    blocks: List[Block]

state

78
    state: State

chain_id

79
    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:
83
    """
84
    Transforms the state from the previous hard fork (`old`) into the block
85
    chain object for this hard fork and returns it.
86
87
    When forks need to implement an irregular state transition, this function
88
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
89
    an example.
90
91
    Parameters
92
    ----------
93
    old :
94
        Previous block chain object.
95
96
    Returns
97
    -------
98
    new : `BlockChain`
99
        Upgraded block chain object for this hard fork.
100
    """
101
    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]:
105
    """
106
    Obtain the list of hashes of the previous 256 blocks in order of
107
    increasing block number.
108
109
    This function will return less hashes for the first 256 blocks.
110
111
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
112
    therefore this function retrieves them.
113
114
    Parameters
115
    ----------
116
    chain :
117
        History and current state.
118
119
    Returns
120
    -------
121
    recent_block_hashes : `List[Hash32]`
122
        Hashes of the recent 256 blocks in order of increasing block number.
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
    parent_header = chain.blocks[-1].header
167
    validate_header(block.header, parent_header)
168
    validate_ommers(block.ommers, block.header, chain)
169
    apply_body_output = apply_body(
170
        chain.state,
171
        get_last_256_block_hashes(chain),
172
        block.header.coinbase,
173
        block.header.number,
174
        block.header.base_fee_per_gas,
175
        block.header.gas_limit,
176
        block.header.timestamp,
177
        block.header.difficulty,
178
        block.transactions,
179
        block.ommers,
180
        chain.chain_id,
181
    )
182
    if apply_body_output.block_gas_used != block.header.gas_used:
183
        raise InvalidBlock(
184
            f"{apply_body_output.block_gas_used} != {block.header.gas_used}"
185
        )
186
    if apply_body_output.transactions_root != block.header.transactions_root:
187
        raise InvalidBlock
188
    if apply_body_output.state_root != block.header.state_root:
189
        raise InvalidBlock
190
    if apply_body_output.receipt_root != block.header.receipt_root:
191
        raise InvalidBlock
192
    if apply_body_output.block_logs_bloom != block.header.bloom:
193
        raise InvalidBlock
194
195
    chain.blocks.append(block)
196
    if len(chain.blocks) > 255:
197
        # Real clients have to store more blocks to deal with reorgs, but the
198
        # protocol only requires the last 255
199
        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:
208
    """
209
    Calculates the base fee per gas for the block.
210
211
    Parameters
212
    ----------
213
    block_gas_limit :
214
        Gas limit of the block for which the base fee is being calculated.
215
    parent_gas_limit :
216
        Gas limit of the parent block.
217
    parent_gas_used :
218
        Gas used in the parent block.
219
    parent_base_fee_per_gas :
220
        Base fee per gas of the parent block.
221
222
    Returns
223
    -------
224
    base_fee_per_gas : `Uint`
225
        Base fee per gas for the block.
226
    """
227
    parent_gas_target = parent_gas_limit // ELASTICITY_MULTIPLIER
228
    if not check_gas_limit(block_gas_limit, parent_gas_limit):
229
        raise InvalidBlock
230
231
    if parent_gas_used == parent_gas_target:
232
        expected_base_fee_per_gas = parent_base_fee_per_gas
233
    elif parent_gas_used > parent_gas_target:
234
        gas_used_delta = parent_gas_used - parent_gas_target
235
236
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
237
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
238
239
        base_fee_per_gas_delta = max(
240
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR,
241
            Uint(1),
242
        )
243
244
        expected_base_fee_per_gas = (
245
            parent_base_fee_per_gas + base_fee_per_gas_delta
246
        )
247
    else:
248
        gas_used_delta = parent_gas_target - parent_gas_used
249
250
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
251
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
252
253
        base_fee_per_gas_delta = (
254
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR
255
        )
256
257
        expected_base_fee_per_gas = (
258
            parent_base_fee_per_gas - base_fee_per_gas_delta
259
        )
260
261
    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

header : Header to check for correctness. parent_header : Parent Header of the header to check for correctness

def validate_header(header: Header, ​​parent_header: Header) -> None:
265
    """
266
    Verifies a block header.
267
268
    In order to consider a block's header valid, the logic for the
269
    quantities in the header should match the logic for the block itself.
270
    For example the header timestamp should be greater than the block's parent
271
    timestamp because the block was created *after* the parent block.
272
    Additionally, the block's number should be directly following the parent
273
    block's number since it is the next block in the sequence.
274
275
    Parameters
276
    ----------
277
    header :
278
        Header to check for correctness.
279
    parent_header :
280
        Parent Header of the header to check for correctness
281
    """
282
    if header.gas_used > header.gas_limit:
283
        raise InvalidBlock
284
285
    expected_base_fee_per_gas = INITIAL_BASE_FEE
286
    if header.number != FORK_CRITERIA.block_number:
287
        # For every block except the first, calculate the base fee per gas
288
        # based on the parent block.
289
        expected_base_fee_per_gas = calculate_base_fee_per_gas(
290
            header.gas_limit,
291
            parent_header.gas_limit,
292
            parent_header.gas_used,
293
            parent_header.base_fee_per_gas,
294
        )
295
296
    if expected_base_fee_per_gas != header.base_fee_per_gas:
297
        raise InvalidBlock
298
299
    parent_has_ommers = parent_header.ommers_hash != EMPTY_OMMER_HASH
300
    if header.timestamp <= parent_header.timestamp:
301
        raise InvalidBlock
302
    if header.number != parent_header.number + Uint(1):
303
        raise InvalidBlock
304
    if len(header.extra_data) > 32:
305
        raise InvalidBlock
306
307
    block_difficulty = calculate_block_difficulty(
308
        header.number,
309
        header.timestamp,
310
        parent_header.timestamp,
311
        parent_header.difficulty,
312
        parent_has_ommers,
313
    )
314
    if header.difficulty != block_difficulty:
315
        raise InvalidBlock
316
317
    block_parent_hash = keccak256(rlp.encode(parent_header))
318
    if header.parent_hash != block_parent_hash:
319
        raise InvalidBlock
320
321
    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:
325
    """
326
    Generate rlp hash of the header which is to be used for Proof-of-Work
327
    verification.
328
329
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
330
    while calculating this hash.
331
332
    A particular PoW is valid for a single hash, that hash is computed by
333
    this function. The `nonce` and `mix_digest` are omitted from this hash
334
    because they are being changed by miners in their search for a sufficient
335
    proof-of-work.
336
337
    Parameters
338
    ----------
339
    header :
340
        The header object for which the hash is to be generated.
341
342
    Returns
343
    -------
344
    hash : `Hash32`
345
        The PoW valid rlp hash of the passed in header.
346
    """
347
    header_data_without_pow_artefacts = (
348
        header.parent_hash,
349
        header.ommers_hash,
350
        header.coinbase,
351
        header.state_root,
352
        header.transactions_root,
353
        header.receipt_root,
354
        header.bloom,
355
        header.difficulty,
356
        header.number,
357
        header.gas_limit,
358
        header.gas_used,
359
        header.timestamp,
360
        header.extra_data,
361
        header.base_fee_per_gas,
362
    )
363
364
    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:
368
    """
369
    Validates the Proof of Work constraints.
370
371
    In order to verify that a miner's proof-of-work is valid for a block, a
372
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
373
    hash function. The mix digest is a hash of the header and the nonce that
374
    is passed through and it confirms whether or not proof-of-work was done
375
    on the correct block. The result is the actual hash value of the block.
376
377
    Parameters
378
    ----------
379
    header :
380
        Header of interest.
381
    """
382
    header_hash = generate_header_hash_for_pow(header)
383
    # TODO: Memoize this somewhere and read from that data instead of
384
    # calculating cache for every block validation.
385
    cache = generate_cache(header.number)
386
    mix_digest, result = hashimoto_light(
387
        header_hash, header.nonce, cache, dataset_size(header.number)
388
    )
389
    if mix_digest != header.mix_digest:
390
        raise InvalidBlock
391
392
    limit = Uint(U256.MAX_VALUE) + Uint(1)
393
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
394
        raise InvalidBlock

check_transaction

Check if the transaction is includable in the block.

Parameters

tx : The transaction. base_fee_per_gas : The block base fee. gas_available : The gas remaining in the block. chain_id : The ID of the current chain.

Returns

sender_address : The sender of the transaction. effective_gas_price : The price to charge for gas when the transaction is executed.

Raises

InvalidBlock : If the transaction is not includable.

def check_transaction(tx: Transaction, ​​base_fee_per_gas: Uint, ​​gas_available: Uint, ​​chain_id: U64) -> Tuple[Address, Uint]:
403
    """
404
    Check if the transaction is includable in the block.
405
406
    Parameters
407
    ----------
408
    tx :
409
        The transaction.
410
    base_fee_per_gas :
411
        The block base fee.
412
    gas_available :
413
        The gas remaining in the block.
414
    chain_id :
415
        The ID of the current chain.
416
417
    Returns
418
    -------
419
    sender_address :
420
        The sender of the transaction.
421
    effective_gas_price :
422
        The price to charge for gas when the transaction is executed.
423
424
    Raises
425
    ------
426
    InvalidBlock :
427
        If the transaction is not includable.
428
    """
429
    if tx.gas > gas_available:
430
        raise InvalidBlock
431
    sender_address = recover_sender(chain_id, tx)
432
433
    if isinstance(tx, FeeMarketTransaction):
434
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
435
            raise InvalidBlock
436
        if tx.max_fee_per_gas < base_fee_per_gas:
437
            raise InvalidBlock
438
439
        priority_fee_per_gas = min(
440
            tx.max_priority_fee_per_gas,
441
            tx.max_fee_per_gas - base_fee_per_gas,
442
        )
443
        effective_gas_price = priority_fee_per_gas + base_fee_per_gas
444
    else:
445
        if tx.gas_price < base_fee_per_gas:
446
            raise InvalidBlock
447
        effective_gas_price = tx.gas_price
448
449
    return sender_address, effective_gas_price

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, ...]) -> Union[Bytes, Receipt]:
458
    """
459
    Make the receipt for a transaction that was executed.
460
461
    Parameters
462
    ----------
463
    tx :
464
        The executed transaction.
465
    error :
466
        Error in the top level frame of the transaction, if any.
467
    cumulative_gas_used :
468
        The total gas used so far in the block after the transaction was
469
        executed.
470
    logs :
471
        The logs produced by the transaction.
472
473
    Returns
474
    -------
475
    receipt :
476
        The receipt for the transaction.
477
    """
478
    receipt = Receipt(
479
        succeeded=error is None,
480
        cumulative_gas_used=cumulative_gas_used,
481
        bloom=logs_bloom(logs),
482
        logs=logs,
483
    )
484
485
    if isinstance(tx, AccessListTransaction):
486
        return b"\x01" + rlp.encode(receipt)
487
    elif isinstance(tx, FeeMarketTransaction):
488
        return b"\x02" + rlp.encode(receipt)
489
    else:
490
        return receipt

ApplyBodyOutput

Output from applying the block body to the present state.

Contains the following:

block_gas_used : ethereum.base_types.Uint Gas used for executing all transactions. transactions_root : ethereum.fork_types.Root Trie root of all the transactions in the block. receipt_root : ethereum.fork_types.Root Trie root of all the receipts in the block. block_logs_bloom : Bloom Logs bloom of all the logs included in all the transactions of the block. state_root : ethereum.fork_types.Root State root after all transactions have been executed.

493
@dataclass
class ApplyBodyOutput:

block_gas_used

513
    block_gas_used: Uint

transactions_root

514
    transactions_root: Root

receipt_root

515
    receipt_root: Root

block_logs_bloom

516
    block_logs_bloom: Bloom

state_root

517
    state_root: Root

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

state : Current account state. block_hashes : List of hashes of the previous 256 blocks in the order of increasing block number. coinbase : Address of account which receives block reward and transaction fees. block_number : Position of the block within the chain. base_fee_per_gas : Base fee per gas of within the block. block_gas_limit : Initial amount of gas available for execution in this block. block_time : Time the block was produced, measured in seconds since the epoch. block_difficulty : Difficulty of the block. transactions : Transactions included in the block. ommers : Headers of ancestor blocks which are not direct parents (formerly uncles.) chain_id : ID of the executing chain.

Returns

apply_body_output : ApplyBodyOutput Output of applying the block body to the state.

def apply_body(state: State, ​​block_hashes: List[Hash32], ​​coinbase: Address, ​​block_number: Uint, ​​base_fee_per_gas: Uint, ​​block_gas_limit: Uint, ​​block_time: U256, ​​block_difficulty: Uint, ​​transactions: Tuple[Union[LegacyTransaction, Bytes], ...], ​​ommers: Tuple[Header, ...], ​​chain_id: U64) -> ApplyBodyOutput:
533
    """
534
    Executes a block.
535
536
    Many of the contents of a block are stored in data structures called
537
    tries. There is a transactions trie which is similar to a ledger of the
538
    transactions stored in the current block. There is also a receipts trie
539
    which stores the results of executing a transaction, like the post state
540
    and gas used. This function creates and executes the block that is to be
541
    added to the chain.
542
543
    Parameters
544
    ----------
545
    state :
546
        Current account state.
547
    block_hashes :
548
        List of hashes of the previous 256 blocks in the order of
549
        increasing block number.
550
    coinbase :
551
        Address of account which receives block reward and transaction fees.
552
    block_number :
553
        Position of the block within the chain.
554
    base_fee_per_gas :
555
        Base fee per gas of within the block.
556
    block_gas_limit :
557
        Initial amount of gas available for execution in this block.
558
    block_time :
559
        Time the block was produced, measured in seconds since the epoch.
560
    block_difficulty :
561
        Difficulty of the block.
562
    transactions :
563
        Transactions included in the block.
564
    ommers :
565
        Headers of ancestor blocks which are not direct parents (formerly
566
        uncles.)
567
    chain_id :
568
        ID of the executing chain.
569
570
    Returns
571
    -------
572
    apply_body_output : `ApplyBodyOutput`
573
        Output of applying the block body to the state.
574
    """
575
    gas_available = block_gas_limit
576
    transactions_trie: Trie[
577
        Bytes, Optional[Union[Bytes, LegacyTransaction]]
578
    ] = Trie(secured=False, default=None)
579
    receipts_trie: Trie[Bytes, Optional[Union[Bytes, Receipt]]] = Trie(
580
        secured=False, default=None
581
    )
582
    block_logs: Tuple[Log, ...] = ()
583
584
    for i, tx in enumerate(map(decode_transaction, transactions)):
585
        trie_set(
586
            transactions_trie, rlp.encode(Uint(i)), encode_transaction(tx)
587
        )
588
589
        sender_address, effective_gas_price = check_transaction(
590
            tx, base_fee_per_gas, gas_available, chain_id
591
        )
592
593
        env = vm.Environment(
594
            caller=sender_address,
595
            origin=sender_address,
596
            block_hashes=block_hashes,
597
            coinbase=coinbase,
598
            number=block_number,
599
            gas_limit=block_gas_limit,
600
            base_fee_per_gas=base_fee_per_gas,
601
            gas_price=effective_gas_price,
602
            time=block_time,
603
            difficulty=block_difficulty,
604
            state=state,
605
            chain_id=chain_id,
606
            traces=[],
607
        )
608
609
        gas_used, logs, error = process_transaction(env, tx)
610
        gas_available -= gas_used
611
612
        receipt = make_receipt(
613
            tx, error, (block_gas_limit - gas_available), logs
614
        )
615
616
        trie_set(
617
            receipts_trie,
618
            rlp.encode(Uint(i)),
619
            receipt,
620
        )
621
622
        block_logs += logs
623
624
    pay_rewards(state, block_number, coinbase, ommers)
625
626
    block_gas_used = block_gas_limit - gas_available
627
628
    block_logs_bloom = logs_bloom(block_logs)
629
630
    return ApplyBodyOutput(
631
        block_gas_used,
632
        root(transactions_trie),
633
        root(receipts_trie),
634
        block_logs_bloom,
635
        state_root(state),
636
    )

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:
642
    """
643
    Validates the ommers mentioned in the block.
644
645
    An ommer block is a block that wasn't canonically added to the
646
    blockchain because it wasn't validated as fast as the canonical block
647
    but was mined at the same time.
648
649
    To be considered valid, the ommers must adhere to the rules defined in
650
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
651
    there cannot be duplicate ommers in a block. Many of the other ommer
652
    constraints are listed in the in-line comments of this function.
653
654
    Parameters
655
    ----------
656
    ommers :
657
        List of ommers mentioned in the current block.
658
    block_header:
659
        The header of current block.
660
    chain :
661
        History and current state.
662
    """
663
    block_hash = keccak256(rlp.encode(block_header))
664
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
665
        raise InvalidBlock
666
667
    if len(ommers) == 0:
668
        # Nothing to validate
669
        return
670
671
    # Check that each ommer satisfies the constraints of a header
672
    for ommer in ommers:
673
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
674
            raise InvalidBlock
675
        ommer_parent_header = chain.blocks[
676
            -(block_header.number - ommer.number) - 1
677
        ].header
678
        validate_header(ommer, ommer_parent_header)
679
    if len(ommers) > 2:
680
        raise InvalidBlock
681
682
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
683
    if len(ommers_hashes) != len(set(ommers_hashes)):
684
        raise InvalidBlock
685
686
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
687
    recent_canonical_block_hashes = {
688
        keccak256(rlp.encode(block.header))
689
        for block in recent_canonical_blocks
690
    }
691
    recent_ommers_hashes: Set[Hash32] = set()
692
    for block in recent_canonical_blocks:
693
        recent_ommers_hashes = recent_ommers_hashes.union(
694
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
695
        )
696
697
    for ommer_index, ommer in enumerate(ommers):
698
        ommer_hash = ommers_hashes[ommer_index]
699
        if ommer_hash == block_hash:
700
            raise InvalidBlock
701
        if ommer_hash in recent_canonical_block_hashes:
702
            raise InvalidBlock
703
        if ommer_hash in recent_ommers_hashes:
704
            raise InvalidBlock
705
706
        # Ommer age with respect to the current block. For example, an age of
707
        # 1 indicates that the ommer is a sibling of previous block.
708
        ommer_age = block_header.number - ommer.number
709
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
710
            raise InvalidBlock
711
        if ommer.parent_hash not in recent_canonical_block_hashes:
712
            raise InvalidBlock
713
        if ommer.parent_hash == block_header.parent_hash:
714
            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:
723
    """
724
    Pay rewards to the block miner as well as the ommers miners.
725
726
    The miner of the canonical block is rewarded with the predetermined
727
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
728
    number of ommer blocks that were mined around the same time, and included
729
    in the canonical block's header. An ommer block is a block that wasn't
730
    added to the canonical blockchain because it wasn't validated as fast as
731
    the accepted block but was mined at the same time. Although not all blocks
732
    that are mined are added to the canonical chain, miners are still paid a
733
    reward for their efforts. This reward is called an ommer reward and is
734
    calculated based on the number associated with the ommer block that they
735
    mined.
736
737
    Parameters
738
    ----------
739
    state :
740
        Current account state.
741
    block_number :
742
        Position of the block within the chain.
743
    coinbase :
744
        Address of account which receives block reward and transaction fees.
745
    ommers :
746
        List of ommers mentioned in the current block.
747
    """
748
    ommer_count = U256(len(ommers))
749
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
750
    create_ether(state, coinbase, miner_reward)
751
752
    for ommer in ommers:
753
        # Ommer age with respect to the current block.
754
        ommer_age = U256(block_number - ommer.number)
755
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
756
        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 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

env : Environment for the Ethereum Virtual Machine. tx : Transaction to execute.

Returns

gas_left : ethereum.base_types.U256 Remaining gas after execution. logs : Tuple[ethereum.blocks.Log, ...] Logs generated during execution.

def process_transaction(env: ethereum.london.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...], Optional[EthereumException]]:
762
    """
763
    Execute a transaction against the provided environment.
764
765
    This function processes the actions needed to execute a transaction.
766
    It decrements the sender's account after calculating the gas fee and
767
    refunds them the proper amount after execution. Calling contracts,
768
    deploying code, and incrementing nonces are all examples of actions that
769
    happen within this function or from a call made within this function.
770
771
    Accounts that are marked for deletion are processed and destroyed after
772
    execution.
773
774
    Parameters
775
    ----------
776
    env :
777
        Environment for the Ethereum Virtual Machine.
778
    tx :
779
        Transaction to execute.
780
781
    Returns
782
    -------
783
    gas_left : `ethereum.base_types.U256`
784
        Remaining gas after execution.
785
    logs : `Tuple[ethereum.blocks.Log, ...]`
786
        Logs generated during execution.
787
    """
788
    if not validate_transaction(tx):
789
        raise InvalidBlock
790
791
    sender = env.origin
792
    sender_account = get_account(env.state, sender)
793
794
    max_gas_fee: Uint
795
    if isinstance(tx, FeeMarketTransaction):
796
        max_gas_fee = Uint(tx.gas) * Uint(tx.max_fee_per_gas)
797
    else:
798
        max_gas_fee = Uint(tx.gas) * Uint(tx.gas_price)
799
    if sender_account.nonce != tx.nonce:
800
        raise InvalidBlock
801
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
802
        raise InvalidBlock
803
    if sender_account.code != bytearray():
804
        raise InvalidSenderError("not EOA")
805
806
    effective_gas_fee = tx.gas * env.gas_price
807
808
    gas = tx.gas - calculate_intrinsic_cost(tx)
809
    increment_nonce(env.state, sender)
810
811
    sender_balance_after_gas_fee = (
812
        Uint(sender_account.balance) - effective_gas_fee
813
    )
814
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
815
816
    preaccessed_addresses = set()
817
    preaccessed_storage_keys = set()
818
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
819
        for address, keys in tx.access_list:
820
            preaccessed_addresses.add(address)
821
            for key in keys:
822
                preaccessed_storage_keys.add((address, key))
823
824
    message = prepare_message(
825
        sender,
826
        tx.to,
827
        tx.value,
828
        tx.data,
829
        gas,
830
        env,
831
        preaccessed_addresses=frozenset(preaccessed_addresses),
832
        preaccessed_storage_keys=frozenset(preaccessed_storage_keys),
833
    )
834
835
    output = process_message_call(message, env)
836
837
    gas_used = tx.gas - output.gas_left
838
    gas_refund = min(gas_used // Uint(5), Uint(output.refund_counter))
839
    gas_refund_amount = (output.gas_left + gas_refund) * env.gas_price
840
841
    # For non-1559 transactions env.gas_price == tx.gas_price
842
    priority_fee_per_gas = env.gas_price - env.base_fee_per_gas
843
    transaction_fee = (
844
        tx.gas - output.gas_left - gas_refund
845
    ) * priority_fee_per_gas
846
847
    total_gas_used = gas_used - gas_refund
848
849
    # refund gas
850
    sender_balance_after_refund = get_account(
851
        env.state, sender
852
    ).balance + U256(gas_refund_amount)
853
    set_account_balance(env.state, sender, sender_balance_after_refund)
854
855
    # transfer miner fees
856
    coinbase_balance_after_mining_fee = get_account(
857
        env.state, env.coinbase
858
    ).balance + U256(transaction_fee)
859
    if coinbase_balance_after_mining_fee != 0:
860
        set_account_balance(
861
            env.state, env.coinbase, coinbase_balance_after_mining_fee
862
        )
863
    elif account_exists_and_is_empty(env.state, env.coinbase):
864
        destroy_account(env.state, env.coinbase)
865
866
    for address in output.accounts_to_delete:
867
        destroy_account(env.state, address)
868
869
    for address in output.touched_accounts:
870
        if account_exists_and_is_empty(env.state, address):
871
            destroy_account(env.state, address)
872
873
    return total_gas_used, output.logs, output.error

compute_header_hash

Computes the hash of a block header.

The header hash of a block is the canonical hash that is used to refer to a specific block and completely distinguishes a block from another.

keccak256 is a function that produces a 256 bit hash of any input. It also takes in any number of bytes as an input and produces a single hash for them. A hash is a completely unique output for a single input. So an input corresponds to one unique hash that can be used to identify the input exactly.

Prior to using the keccak256 hash function, the header must be encoded using the Recursive-Length Prefix. See :ref:rlp. RLP encoding the header converts it into a space-efficient format that allows for easy transfer of data between nodes. The purpose of RLP is to encode arbitrarily nested arrays of binary data, and RLP is the primary encoding method used to serialize objects in Ethereum's execution layer. The only purpose of RLP is to encode structure; encoding specific data types (e.g. strings, floats) is left up to higher-order protocols.

Parameters

header : Header of interest.

Returns

hash : ethereum.crypto.hash.Hash32 Hash of the header.

def compute_header_hash(header: Header) -> Hash32:
877
    """
878
    Computes the hash of a block header.
879
880
    The header hash of a block is the canonical hash that is used to refer
881
    to a specific block and completely distinguishes a block from another.
882
883
    ``keccak256`` is a function that produces a 256 bit hash of any input.
884
    It also takes in any number of bytes as an input and produces a single
885
    hash for them. A hash is a completely unique output for a single input.
886
    So an input corresponds to one unique hash that can be used to identify
887
    the input exactly.
888
889
    Prior to using the ``keccak256`` hash function, the header must be
890
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
891
    RLP encoding the header converts it into a space-efficient format that
892
    allows for easy transfer of data between nodes. The purpose of RLP is to
893
    encode arbitrarily nested arrays of binary data, and RLP is the primary
894
    encoding method used to serialize objects in Ethereum's execution layer.
895
    The only purpose of RLP is to encode structure; encoding specific data
896
    types (e.g. strings, floats) is left up to higher-order protocols.
897
898
    Parameters
899
    ----------
900
    header :
901
        Header of interest.
902
903
    Returns
904
    -------
905
    hash : `ethereum.crypto.hash.Hash32`
906
        Hash of the header.
907
    """
908
    return keccak256(rlp.encode(header))

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:
912
    """
913
    Validates the gas limit for a block.
914
915
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
916
    quotient of the parent block's gas limit and the
917
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
918
    passed through as a parameter is greater than or equal to the *sum* of
919
    the parent's gas and the adjustment delta then the limit for gas is too
920
    high and fails this function's check. Similarly, if the limit is less
921
    than or equal to the *difference* of the parent's gas and the adjustment
922
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
923
    check fails because the gas limit doesn't allow for a sufficient or
924
    reasonable amount of gas to be used on a block.
925
926
    Parameters
927
    ----------
928
    gas_limit :
929
        Gas limit to validate.
930
931
    parent_gas_limit :
932
        Gas limit of the parent block.
933
934
    Returns
935
    -------
936
    check : `bool`
937
        True if gas limit constraints are satisfied, False otherwise.
938
    """
939
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
940
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
941
        return False
942
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
943
        return False
944
    if gas_limit < GAS_LIMIT_MINIMUM:
945
        return False
946
947
    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 GENESIS_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:
957
    """
958
    Computes difficulty of a block using its header and parent header.
959
960
    The difficulty is determined by the time the block was created after its
961
    parent. The ``offset`` is calculated using the parent block's difficulty,
962
    ``parent_difficulty``, and the timestamp between blocks. This offset is
963
    then added to the parent difficulty and is stored as the ``difficulty``
964
    variable. If the time between the block and its parent is too short, the
965
    offset will result in a positive number thus making the sum of
966
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
967
    avoid mass forking. But, if the time is long enough, then the offset
968
    results in a negative value making the block less difficult than
969
    its parent.
970
971
    The base standard for a block's difficulty is the predefined value
972
    set for the genesis block since it has no parent. So, a block
973
    can't be less difficult than the genesis block, therefore each block's
974
    difficulty is set to the maximum value between the calculated
975
    difficulty and the ``GENESIS_DIFFICULTY``.
976
977
    Parameters
978
    ----------
979
    block_number :
980
        Block number of the block.
981
    block_timestamp :
982
        Timestamp of the block.
983
    parent_timestamp :
984
        Timestamp of the parent block.
985
    parent_difficulty :
986
        difficulty of the parent block.
987
    parent_has_ommers:
988
        does the parent have ommers.
989
990
    Returns
991
    -------
992
    difficulty : `ethereum.base_types.Uint`
993
        Computed difficulty for a block.
994
    """
995
    offset = (
996
        int(parent_difficulty)
997
        // 2048
998
        * max(
999
            (2 if parent_has_ommers else 1)
1000
            - int(block_timestamp - parent_timestamp) // 9,
1001
            -99,
1002
        )
1003
    )
1004
    difficulty = int(parent_difficulty) + offset
1005
    # Historical Note: The difficulty bomb was not present in Ethereum at the
1006
    # start of Frontier, but was added shortly after launch. However since the
1007
    # bomb has no effect prior to block 200000 we pretend it existed from
1008
    # genesis.
1009
    # See https://github.com/ethereum/go-ethereum/pull/1588
1010
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
1011
    if num_bomb_periods >= 0:
1012
        difficulty += 2**num_bomb_periods
1013
1014
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
1015
    # the bomb. This bug does not matter because the difficulty is always much
1016
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
1017
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))