ethereum.berlin.forkethereum.london.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

BASE_FEE_MAX_CHANGE_DENOMINATOR

68
BASE_FEE_MAX_CHANGE_DENOMINATOR = Uint(8)

ELASTICITY_MULTIPLIER

69
ELASTICITY_MULTIPLIER = Uint(2)

GAS_LIMIT_ADJUSTMENT_FACTOR

70
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

71
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

72
MINIMUM_DIFFICULTY = Uint(131072)

INITIAL_BASE_FEE

73
INITIAL_BASE_FEE = Uint(1000000000)

MAX_OMMER_DEPTH

74
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

66
BOMB_DELAY_BLOCKS = 9000000
75
BOMB_DELAY_BLOCKS = 9700000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

79
@dataclass
class BlockChain:

blocks

85
    blocks: List[Block]

state

86
    state: State

chain_id

87
    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:
91
    """
92
    Transforms the state from the previous hard fork (`old`) into the block
93
    chain object for this hard fork and returns it.
94
95
    When forks need to implement an irregular state transition, this function
96
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
97
    an example.
98
99
    Parameters
100
    ----------
101
    old :
102
        Previous block chain object.
103
104
    Returns
105
    -------
106
    new : `BlockChain`
107
        Upgraded block chain object for this hard fork.
108
    """
109
    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]:
113
    """
114
    Obtain the list of hashes of the previous 256 blocks in order of
115
    increasing block number.
116
117
    This function will return less hashes for the first 256 blocks.
118
119
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
120
    therefore this function retrieves them.
121
122
    Parameters
123
    ----------
124
    chain :
125
        History and current state.
126
127
    Returns
128
    -------
129
    recent_block_hashes : `List[Hash32]`
130
        Hashes of the recent 256 blocks in order of increasing block number.
131
    """
132
    recent_blocks = chain.blocks[-255:]
133
    # TODO: This function has not been tested rigorously
134
    if len(recent_blocks) == 0:
135
        return []
136
137
    recent_block_hashes = []
138
139
    for block in recent_blocks:
140
        prev_block_hash = block.header.parent_hash
141
        recent_block_hashes.append(prev_block_hash)
142
143
    # We are computing the hash only for the most recent block and not for
144
    # the rest of the blocks as they have successors which have the hash of
145
    # the current block as parent hash.
146
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
147
    recent_block_hashes.append(most_recent_block_hash)
148
149
    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:
153
    """
154
    Attempts to apply a block to an existing block chain.
155
156
    All parts of the block's contents need to be verified before being added
157
    to the chain. Blocks are verified by ensuring that the contents of the
158
    block make logical sense with the contents of the parent block. The
159
    information in the block's header must also match the corresponding
160
    information in the block.
161
162
    To implement Ethereum, in theory clients are only required to store the
163
    most recent 255 blocks of the chain since as far as execution is
164
    concerned, only those blocks are accessed. Practically, however, clients
165
    should store more blocks to handle reorgs.
166
167
    Parameters
168
    ----------
169
    chain :
170
        History and current state.
171
    block :
172
        Block to apply to `chain`.
173
    """
174
    validate_header(chain, block.header)
175
    validate_ommers(block.ommers, block.header, chain)
176
177
    block_env = vm.BlockEnvironment(
178
        chain_id=chain.chain_id,
179
        state=chain.state,
180
        block_gas_limit=block.header.gas_limit,
181
        block_hashes=get_last_256_block_hashes(chain),
182
        coinbase=block.header.coinbase,
183
        number=block.header.number,
184
        base_fee_per_gas=block.header.base_fee_per_gas,
185
        time=block.header.timestamp,
186
        difficulty=block.header.difficulty,
187
    )
188
189
    block_output = apply_body(
190
        block_env=block_env,
191
        transactions=block.transactions,
192
        ommers=block.ommers,
193
    )
194
    block_state_root = state_root(block_env.state)
195
    transactions_root = root(block_output.transactions_trie)
196
    receipt_root = root(block_output.receipts_trie)
197
    block_logs_bloom = logs_bloom(block_output.block_logs)
198
199
    if block_output.block_gas_used != block.header.gas_used:
200
        raise InvalidBlock(
201
            f"{block_output.block_gas_used} != {block.header.gas_used}"
202
        )
203
    if transactions_root != block.header.transactions_root:
204
        raise InvalidBlock
205
    if block_state_root != block.header.state_root:
206
        raise InvalidBlock
207
    if receipt_root != block.header.receipt_root:
208
        raise InvalidBlock
209
    if block_logs_bloom != block.header.bloom:
210
        raise InvalidBlock
211
212
    chain.blocks.append(block)
213
    if len(chain.blocks) > 255:
214
        # Real clients have to store more blocks to deal with reorgs, but the
215
        # protocol only requires the last 255
216
        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:
225
    """
226
    Calculates the base fee per gas for the block.
227
228
    Parameters
229
    ----------
230
    block_gas_limit :
231
        Gas limit of the block for which the base fee is being calculated.
232
    parent_gas_limit :
233
        Gas limit of the parent block.
234
    parent_gas_used :
235
        Gas used in the parent block.
236
    parent_base_fee_per_gas :
237
        Base fee per gas of the parent block.
238
239
    Returns
240
    -------
241
    base_fee_per_gas : `Uint`
242
        Base fee per gas for the block.
243
    """
244
    parent_gas_target = parent_gas_limit // ELASTICITY_MULTIPLIER
245
    if not check_gas_limit(block_gas_limit, parent_gas_limit):
246
        raise InvalidBlock
247
248
    if parent_gas_used == parent_gas_target:
249
        expected_base_fee_per_gas = parent_base_fee_per_gas
250
    elif parent_gas_used > parent_gas_target:
251
        gas_used_delta = parent_gas_used - parent_gas_target
252
253
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
254
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
255
256
        base_fee_per_gas_delta = max(
257
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR,
258
            Uint(1),
259
        )
260
261
        expected_base_fee_per_gas = (
262
            parent_base_fee_per_gas + base_fee_per_gas_delta
263
        )
264
    else:
265
        gas_used_delta = parent_gas_target - parent_gas_used
266
267
        parent_fee_gas_delta = parent_base_fee_per_gas * gas_used_delta
268
        target_fee_gas_delta = parent_fee_gas_delta // parent_gas_target
269
270
        base_fee_per_gas_delta = (
271
            target_fee_gas_delta // BASE_FEE_MAX_CHANGE_DENOMINATOR
272
        )
273
274
        expected_base_fee_per_gas = (
275
            parent_base_fee_per_gas - base_fee_per_gas_delta
276
        )
277
278
    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:
282
    """
283
    Verifies a block header.
284
285
    In order to consider a block's header valid, the logic for the
286
    quantities in the header should match the logic for the block itself.
287
    For example the header timestamp should be greater than the block's parent
288
    timestamp because the block was created *after* the parent block.
289
    Additionally, the block's number should be directly following the parent
290
    block's number since it is the next block in the sequence.
291
292
    Parameters
293
    ----------
294
    chain :
295
        History and current state.
296
    header :
297
        Header to check for correctness.
298
    """
299
    if header.number < Uint(1):
300
        raise InvalidBlock
301
    parent_header_number = header.number - Uint(1)
302
    first_block_number = chain.blocks[0].header.number
303
    last_block_number = chain.blocks[-1].header.number
304
305
    if (
306
        parent_header_number < first_block_number
307
        or parent_header_number > last_block_number
308
    ):
309
        raise InvalidBlock
310
311
    parent_header = chain.blocks[
312
        parent_header_number - first_block_number
313
    ].header
314
315
    if header.gas_used > header.gas_limit:
316
        raise InvalidBlock
317
318
    expected_base_fee_per_gas = INITIAL_BASE_FEE
319
    if header.number != .block_number:
320
        # For every block except the first, calculate the base fee per gas
321
        # based on the parent block.
322
        expected_base_fee_per_gas = calculate_base_fee_per_gas(
323
            header.gas_limit,
324
            parent_header.gas_limit,
325
            parent_header.gas_used,
326
            parent_header.base_fee_per_gas,
327
        )
328
329
    if expected_base_fee_per_gas != header.base_fee_per_gas:
330
        raise InvalidBlock
331
332
    parent_has_ommers = parent_header.ommers_hash != EMPTY_OMMER_HASH
333
    if header.timestamp <= parent_header.timestamp:
334
        raise InvalidBlock
335
    if header.number != parent_header.number + Uint(1):
250
        raise InvalidBlock
251
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
336
        raise InvalidBlock
337
    if len(header.extra_data) > 32:
338
        raise InvalidBlock
339
340
    block_difficulty = calculate_block_difficulty(
341
        header.number,
342
        header.timestamp,
343
        parent_header.timestamp,
344
        parent_header.difficulty,
345
        parent_has_ommers,
346
    )
347
    if header.difficulty != block_difficulty:
348
        raise InvalidBlock
349
350
    block_parent_hash = keccak256(rlp.encode(parent_header))
351
    if header.parent_hash != block_parent_hash:
352
        raise InvalidBlock
353
354
    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:
358
    """
359
    Generate rlp hash of the header which is to be used for Proof-of-Work
360
    verification.
361
362
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
363
    while calculating this hash.
364
365
    A particular PoW is valid for a single hash, that hash is computed by
366
    this function. The `nonce` and `mix_digest` are omitted from this hash
367
    because they are being changed by miners in their search for a sufficient
368
    proof-of-work.
369
370
    Parameters
371
    ----------
372
    header :
373
        The header object for which the hash is to be generated.
374
375
    Returns
376
    -------
377
    hash : `Hash32`
378
        The PoW valid rlp hash of the passed in header.
379
    """
380
    header_data_without_pow_artefacts = (
381
        header.parent_hash,
382
        header.ommers_hash,
383
        header.coinbase,
384
        header.state_root,
385
        header.transactions_root,
386
        header.receipt_root,
387
        header.bloom,
388
        header.difficulty,
389
        header.number,
390
        header.gas_limit,
391
        header.gas_used,
392
        header.timestamp,
309
        header.extra_data,
393
        header.extra_data,
394
        header.base_fee_per_gas,
395
    )
396
397
    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:
401
    """
402
    Validates the Proof of Work constraints.
403
404
    In order to verify that a miner's proof-of-work is valid for a block, a
405
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
406
    hash function. The mix digest is a hash of the header and the nonce that
407
    is passed through and it confirms whether or not proof-of-work was done
408
    on the correct block. The result is the actual hash value of the block.
409
410
    Parameters
411
    ----------
412
    header :
413
        Header of interest.
414
    """
415
    header_hash = generate_header_hash_for_pow(header)
416
    # TODO: Memoize this somewhere and read from that data instead of
417
    # calculating cache for every block validation.
418
    cache = generate_cache(header.number)
419
    mix_digest, result = hashimoto_light(
420
        header_hash, header.nonce, cache, dataset_size(header.number)
421
    )
422
    if mix_digest != header.mix_digest:
423
        raise InvalidBlock
424
425
    limit = Uint(U256.MAX_VALUE) + Uint(1)
426
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
427
        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.

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.

def check_transaction(block_env: ethereum.berlin.vm.BlockEnvironmentethereum.london.vm.BlockEnvironment, ​​block_output: ethereum.berlin.vm.BlockOutputethereum.london.vm.BlockOutput, ​​tx: Transaction) -> AddressTuple[Address, Uint]:
435
    """
436
    Check if the transaction is includable in the block.
437
438
    Parameters
439
    ----------
440
    block_env :
441
        The block scoped environment.
442
    block_output :
443
        The block output for the current block.
444
    tx :
445
        The transaction.
446
447
    Returns
448
    -------
449
    sender_address :
450
        The sender of the transaction.
451
    effective_gas_price :
452
        The price to charge for gas when the transaction is executed.
453
454
    Raises
455
    ------
456
    InvalidBlock :
457
        If the transaction is not includable.
458
    GasUsedExceedsLimitError :
459
        If the gas used by the transaction exceeds the block's gas limit.
460
    NonceMismatchError :
461
        If the nonce of the transaction is not equal to the sender's nonce.
462
    InsufficientBalanceError :
463
        If the sender's balance is not enough to pay for the transaction.
464
    InvalidSenderError :
465
        If the transaction is from an address that does not exist anymore.
466
    PriorityFeeGreaterThanMaxFeeError:
467
        If the priority fee is greater than the maximum fee per gas.
468
    InsufficientMaxFeePerGasError :
469
        If the maximum fee per gas is insufficient for the transaction.
470
    """
471
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
472
    if tx.gas > gas_available:
473
        raise GasUsedExceedsLimitError("gas used exceeds limit")
474
    sender_address = recover_sender(block_env.chain_id, tx)
475
    sender_account = get_account(block_env.state, sender_address)
476
384
    max_gas_fee = tx.gas * tx.gas_price
477
    if isinstance(tx, FeeMarketTransaction):
478
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
479
            raise PriorityFeeGreaterThanMaxFeeError(
480
                "priority fee greater than max fee"
481
            )
482
        if tx.max_fee_per_gas < block_env.base_fee_per_gas:
483
            raise InsufficientMaxFeePerGasError(
484
                tx.max_fee_per_gas, block_env.base_fee_per_gas
485
            )
486
487
        priority_fee_per_gas = min(
488
            tx.max_priority_fee_per_gas,
489
            tx.max_fee_per_gas - block_env.base_fee_per_gas,
490
        )
491
        effective_gas_price = priority_fee_per_gas + block_env.base_fee_per_gas
492
        max_gas_fee = tx.gas * tx.max_fee_per_gas
493
    else:
494
        if tx.gas_price < block_env.base_fee_per_gas:
495
            raise InvalidBlock
496
        effective_gas_price = tx.gas_price
497
        max_gas_fee = tx.gas * tx.gas_price
498
499
    if sender_account.nonce > Uint(tx.nonce):
500
        raise NonceMismatchError("nonce too low")
501
    elif sender_account.nonce < Uint(tx.nonce):
502
        raise NonceMismatchError("nonce too high")
503
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
504
        raise InsufficientBalanceError("insufficient sender balance")
505
    if sender_account.code:
506
        raise InvalidSenderError("not EOA")
507
395
    return sender_address
508
    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, ...]) -> Bytes | Receipt:
517
    """
518
    Make the receipt for a transaction that was executed.
519
520
    Parameters
521
    ----------
522
    tx :
523
        The executed transaction.
524
    error :
525
        Error in the top level frame of the transaction, if any.
526
    cumulative_gas_used :
527
        The total gas used so far in the block after the transaction was
528
        executed.
529
    logs :
530
        The logs produced by the transaction.
531
532
    Returns
533
    -------
534
    receipt :
535
        The receipt for the transaction.
536
    """
537
    receipt = Receipt(
538
        succeeded=error is None,
539
        cumulative_gas_used=cumulative_gas_used,
540
        bloom=logs_bloom(logs),
541
        logs=logs,
542
    )
543
544
    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.berlin.vm.BlockEnvironmentethereum.london.vm.BlockEnvironment, ​​transactions: Tuple[LegacyTransaction | Bytes, ...], ​​ommers: Tuple[Header, ...]) -> ethereum.berlin.vm.BlockOutputethereum.london.vm.BlockOutput:
552
    """
553
    Executes a block.
554
555
    Many of the contents of a block are stored in data structures called
556
    tries. There is a transactions trie which is similar to a ledger of the
557
    transactions stored in the current block. There is also a receipts trie
558
    which stores the results of executing a transaction, like the post state
559
    and gas used. This function creates and executes the block that is to be
560
    added to the chain.
561
562
    Parameters
563
    ----------
564
    block_env :
565
        The block scoped environment.
566
    transactions :
567
        Transactions included in the block.
568
    ommers :
569
        Headers of ancestor blocks which are not direct parents (formerly
570
        uncles.)
571
572
    Returns
573
    -------
574
    block_output :
575
        The block output for the current block.
576
    """
577
    block_output = vm.BlockOutput()
578
579
    for i, tx in enumerate(map(decode_transaction, transactions)):
580
        process_transaction(block_env, block_output, tx, Uint(i))
581
582
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
583
584
    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:
590
    """
591
    Validates the ommers mentioned in the block.
592
593
    An ommer block is a block that wasn't canonically added to the
594
    blockchain because it wasn't validated as fast as the canonical block
595
    but was mined at the same time.
596
597
    To be considered valid, the ommers must adhere to the rules defined in
598
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
599
    there cannot be duplicate ommers in a block. Many of the other ommer
600
    constraints are listed in the in-line comments of this function.
601
602
    Parameters
603
    ----------
604
    ommers :
605
        List of ommers mentioned in the current block.
606
    block_header:
607
        The header of current block.
608
    chain :
609
        History and current state.
610
    """
611
    block_hash = keccak256(rlp.encode(block_header))
612
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
613
        raise InvalidBlock
614
615
    if len(ommers) == 0:
616
        # Nothing to validate
617
        return
618
619
    # Check that each ommer satisfies the constraints of a header
620
    for ommer in ommers:
621
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
622
            raise InvalidBlock
623
        validate_header(chain, ommer)
624
    if len(ommers) > 2:
625
        raise InvalidBlock
626
627
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
628
    if len(ommers_hashes) != len(set(ommers_hashes)):
629
        raise InvalidBlock
630
631
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
632
    recent_canonical_block_hashes = {
633
        keccak256(rlp.encode(block.header))
634
        for block in recent_canonical_blocks
635
    }
636
    recent_ommers_hashes: Set[Hash32] = set()
637
    for block in recent_canonical_blocks:
638
        recent_ommers_hashes = recent_ommers_hashes.union(
639
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
640
        )
641
642
    for ommer_index, ommer in enumerate(ommers):
643
        ommer_hash = ommers_hashes[ommer_index]
644
        if ommer_hash == block_hash:
645
            raise InvalidBlock
646
        if ommer_hash in recent_canonical_block_hashes:
647
            raise InvalidBlock
648
        if ommer_hash in recent_ommers_hashes:
649
            raise InvalidBlock
650
651
        # Ommer age with respect to the current block. For example, an age of
652
        # 1 indicates that the ommer is a sibling of previous block.
653
        ommer_age = block_header.number - ommer.number
654
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
655
            raise InvalidBlock
656
        if ommer.parent_hash not in recent_canonical_block_hashes:
657
            raise InvalidBlock
658
        if ommer.parent_hash == block_header.parent_hash:
659
            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:
668
    """
669
    Pay rewards to the block miner as well as the ommers miners.
670
671
    The miner of the canonical block is rewarded with the predetermined
672
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
673
    number of ommer blocks that were mined around the same time, and included
674
    in the canonical block's header. An ommer block is a block that wasn't
675
    added to the canonical blockchain because it wasn't validated as fast as
676
    the accepted block but was mined at the same time. Although not all blocks
677
    that are mined are added to the canonical chain, miners are still paid a
678
    reward for their efforts. This reward is called an ommer reward and is
679
    calculated based on the number associated with the ommer block that they
680
    mined.
681
682
    Parameters
683
    ----------
684
    state :
685
        Current account state.
686
    block_number :
687
        Position of the block within the chain.
688
    coinbase :
689
        Address of account which receives block reward and transaction fees.
690
    ommers :
691
        List of ommers mentioned in the current block.
692
    """
693
    ommer_count = U256(len(ommers))
694
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
695
    create_ether(state, coinbase, miner_reward)
696
697
    for ommer in ommers:
698
        # Ommer age with respect to the current block.
699
        ommer_age = U256(block_number - ommer.number)
700
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
701
        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

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.berlin.vm.BlockEnvironmentethereum.london.vm.BlockEnvironment, ​​block_output: ethereum.berlin.vm.BlockOutputethereum.london.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
710
    """
711
    Execute a transaction against the provided environment.
712
713
    This function processes the actions needed to execute a transaction.
714
    It decrements the sender's account after calculating the gas fee and
715
    refunds them the proper amount after execution. Calling contracts,
716
    deploying code, and incrementing nonces are all examples of actions that
717
    happen within this function or from a call made within this function.
718
719
    Accounts that are marked for deletion are processed and destroyed after
720
    execution.
721
722
    Parameters
723
    ----------
724
    block_env :
725
        Environment for the Ethereum Virtual Machine.
726
    block_output :
727
        The block output for the current block.
728
    tx :
729
        Transaction to execute.
730
    index:
731
        Index of the transaction in the block.
732
    """
733
    trie_set(
734
        block_output.transactions_trie,
735
        rlp.encode(index),
736
        encode_transaction(tx),
737
    )
738
739
    intrinsic_gas = validate_transaction(tx)
740
628
    sender = check_transaction(
741
    (
742
        sender,
743
        effective_gas_price,
744
    ) = check_transaction(
745
        block_env=block_env,
746
        block_output=block_output,
747
        tx=tx,
748
    )
749
750
    sender_account = get_account(block_env.state, sender)
751
752
    effective_gas_fee = tx.gas * effective_gas_price
753
754
    gas = tx.gas - intrinsic_gas
755
    increment_nonce(block_env.state, sender)
756
639
    gas_fee = tx.gas * tx.gas_price
640
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
757
    sender_balance_after_gas_fee = (
758
        Uint(sender_account.balance) - effective_gas_fee
759
    )
760
    set_account_balance(
761
        block_env.state, sender, U256(sender_balance_after_gas_fee)
762
    )
763
764
    access_list_addresses = set()
765
    access_list_storage_keys = set()
647
    if isinstance(tx, AccessListTransaction):
766
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
767
        for access in tx.access_list:
768
            access_list_addresses.add(access.account)
769
            for slot in access.slots:
770
                access_list_storage_keys.add((access.account, slot))
771
772
    tx_env = vm.TransactionEnvironment(
773
        origin=sender,
655
        gas_price=tx.gas_price,
774
        gas_price=effective_gas_price,
775
        gas=gas,
776
        access_list_addresses=access_list_addresses,
777
        access_list_storage_keys=access_list_storage_keys,
778
        index_in_block=index,
779
        tx_hash=get_transaction_hash(encode_transaction(tx)),
780
        traces=[],
781
    )
782
783
    message = prepare_message(block_env, tx_env, tx)
784
785
    tx_output = process_message_call(message)
786
787
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
788
    tx_gas_refund = min(
670
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
789
        tx_gas_used_before_refund // Uint(5), Uint(tx_output.refund_counter)
790
    )
791
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
792
    tx_gas_left = tx.gas - tx_gas_used_after_refund
674
    gas_refund_amount = tx_gas_left * tx.gas_price
793
    gas_refund_amount = tx_gas_left * effective_gas_price
794
676
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
795
    # For non-1559 transactions effective_gas_price == tx.gas_price
796
    priority_fee_per_gas = effective_gas_price - block_env.base_fee_per_gas
797
    transaction_fee = tx_gas_used_after_refund * priority_fee_per_gas
798
799
    # refund gas
800
    sender_balance_after_refund = get_account(
801
        block_env.state, sender
802
    ).balance + U256(gas_refund_amount)
803
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
804
805
    # transfer miner fees
806
    coinbase_balance_after_mining_fee = get_account(
807
        block_env.state, block_env.coinbase
808
    ).balance + U256(transaction_fee)
809
    if coinbase_balance_after_mining_fee != 0:
810
        set_account_balance(
811
            block_env.state,
812
            block_env.coinbase,
813
            coinbase_balance_after_mining_fee,
814
        )
815
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
816
        destroy_account(block_env.state, block_env.coinbase)
817
818
    for address in tx_output.accounts_to_delete:
819
        destroy_account(block_env.state, address)
820
821
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
822
823
    block_output.block_gas_used += tx_gas_used_after_refund
824
825
    receipt = make_receipt(
826
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
827
    )
828
829
    receipt_key = rlp.encode(Uint(index))
830
    block_output.receipt_keys += (receipt_key,)
831
832
    trie_set(
833
        block_output.receipts_trie,
834
        receipt_key,
835
        receipt,
836
    )
837
838
    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 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:
842
    """
843
    Validates the gas limit for a block.
844
845
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
846
    quotient of the parent block's gas limit and the
847
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
848
    passed through as a parameter is greater than or equal to the *sum* of
849
    the parent's gas and the adjustment delta then the limit for gas is too
850
    high and fails this function's check. Similarly, if the limit is less
851
    than or equal to the *difference* of the parent's gas and the adjustment
852
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
853
    check fails because the gas limit doesn't allow for a sufficient or
854
    reasonable amount of gas to be used on a block.
855
856
    Parameters
857
    ----------
858
    gas_limit :
859
        Gas limit to validate.
860
861
    parent_gas_limit :
862
        Gas limit of the parent block.
863
864
    Returns
865
    -------
866
    check : `bool`
867
        True if gas limit constraints are satisfied, False otherwise.
868
    """
869
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
870
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
871
        return False
872
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
873
        return False
874
    if gas_limit < GAS_LIMIT_MINIMUM:
875
        return False
876
877
    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:
887
    """
888
    Computes difficulty of a block using its header and parent header.
889
890
    The difficulty is determined by the time the block was created after its
891
    parent. The ``offset`` is calculated using the parent block's difficulty,
892
    ``parent_difficulty``, and the timestamp between blocks. This offset is
893
    then added to the parent difficulty and is stored as the ``difficulty``
894
    variable. If the time between the block and its parent is too short, the
895
    offset will result in a positive number thus making the sum of
896
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
897
    avoid mass forking. But, if the time is long enough, then the offset
898
    results in a negative value making the block less difficult than
899
    its parent.
900
901
    The base standard for a block's difficulty is the predefined value
902
    set for the genesis block since it has no parent. So, a block
903
    can't be less difficult than the genesis block, therefore each block's
904
    difficulty is set to the maximum value between the calculated
905
    difficulty and the ``GENESIS_DIFFICULTY``.
906
907
    Parameters
908
    ----------
909
    block_number :
910
        Block number of the block.
911
    block_timestamp :
912
        Timestamp of the block.
913
    parent_timestamp :
914
        Timestamp of the parent block.
915
    parent_difficulty :
916
        difficulty of the parent block.
917
    parent_has_ommers:
918
        does the parent have ommers.
919
920
    Returns
921
    -------
922
    difficulty : `ethereum.base_types.Uint`
923
        Computed difficulty for a block.
924
    """
925
    offset = (
926
        int(parent_difficulty)
927
        // 2048
928
        * max(
929
            (2 if parent_has_ommers else 1)
930
            - int(block_timestamp - parent_timestamp) // 9,
931
            -99,
932
        )
933
    )
934
    difficulty = int(parent_difficulty) + offset
935
    # Historical Note: The difficulty bomb was not present in Ethereum at the
936
    # start of Frontier, but was added shortly after launch. However since the
937
    # bomb has no effect prior to block 200000 we pretend it existed from
938
    # genesis.
939
    # See https://github.com/ethereum/go-ethereum/pull/1588
940
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
941
    if num_bomb_periods >= 0:
942
        difficulty += 2**num_bomb_periods
943
944
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
945
    # the bomb. This bug does not matter because the difficulty is always much
946
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
947
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))