ethereum.berlin.forkethereum.london.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

BASE_FEE_MAX_CHANGE_DENOMINATOR

61
BASE_FEE_MAX_CHANGE_DENOMINATOR = Uint(8)

ELASTICITY_MULTIPLIER

62
ELASTICITY_MULTIPLIER = Uint(2)

GAS_LIMIT_ADJUSTMENT_FACTOR

63
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

64
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

65
MINIMUM_DIFFICULTY = Uint(131072)

INITIAL_BASE_FEE

66
INITIAL_BASE_FEE = Uint(1000000000)

MAX_OMMER_DEPTH

67
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

63
BOMB_DELAY_BLOCKS = 9000000
68
BOMB_DELAY_BLOCKS = 9700000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

72
@dataclass
class BlockChain:

blocks

78
    blocks: List[Block]

state

79
    state: State

chain_id

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

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]:
428
    """
429
    Check if the transaction is includable in the block.
430
431
    Parameters
432
    ----------
433
    block_env :
434
        The block scoped environment.
435
    block_output :
436
        The block output for the current block.
437
    tx :
438
        The transaction.
439
440
    Returns
441
    -------
442
    sender_address :
443
        The sender of the transaction.
444
    effective_gas_price :
445
        The price to charge for gas when the transaction is executed.
446
447
    Raises
448
    ------
449
    InvalidBlock :
450
        If the transaction is not includable.
451
    """
452
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
453
    if tx.gas > gas_available:
454
        raise InvalidBlock
455
    sender_address = recover_sender(block_env.chain_id, tx)
456
    sender_account = get_account(block_env.state, sender_address)
457
375
    max_gas_fee = tx.gas * tx.gas_price
458
    if isinstance(tx, FeeMarketTransaction):
459
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
460
            raise InvalidBlock
461
        if tx.max_fee_per_gas < block_env.base_fee_per_gas:
462
            raise InvalidBlock
463
464
        priority_fee_per_gas = min(
465
            tx.max_priority_fee_per_gas,
466
            tx.max_fee_per_gas - block_env.base_fee_per_gas,
467
        )
468
        effective_gas_price = priority_fee_per_gas + block_env.base_fee_per_gas
469
        max_gas_fee = tx.gas * tx.max_fee_per_gas
470
    else:
471
        if tx.gas_price < block_env.base_fee_per_gas:
472
            raise InvalidBlock
473
        effective_gas_price = tx.gas_price
474
        max_gas_fee = tx.gas * tx.gas_price
475
476
    if sender_account.nonce != tx.nonce:
477
        raise InvalidBlock
478
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
479
        raise InvalidBlock
480
    if sender_account.code:
481
        raise InvalidSenderError("not EOA")
482
384
    return sender_address
483
    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]:
492
    """
493
    Make the receipt for a transaction that was executed.
494
495
    Parameters
496
    ----------
497
    tx :
498
        The executed transaction.
499
    error :
500
        Error in the top level frame of the transaction, if any.
501
    cumulative_gas_used :
502
        The total gas used so far in the block after the transaction was
503
        executed.
504
    logs :
505
        The logs produced by the transaction.
506
507
    Returns
508
    -------
509
    receipt :
510
        The receipt for the transaction.
511
    """
512
    receipt = Receipt(
513
        succeeded=error is None,
514
        cumulative_gas_used=cumulative_gas_used,
515
        bloom=logs_bloom(logs),
516
        logs=logs,
517
    )
518
519
    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[Union[LegacyTransaction, Bytes], ...], ​​ommers: Tuple[Header, ...]) -> ethereum.berlin.vm.BlockOutputethereum.london.vm.BlockOutput:
527
    """
528
    Executes a block.
529
530
    Many of the contents of a block are stored in data structures called
531
    tries. There is a transactions trie which is similar to a ledger of the
532
    transactions stored in the current block. There is also a receipts trie
533
    which stores the results of executing a transaction, like the post state
534
    and gas used. This function creates and executes the block that is to be
535
    added to the chain.
536
537
    Parameters
538
    ----------
539
    block_env :
540
        The block scoped environment.
541
    transactions :
542
        Transactions included in the block.
543
    ommers :
544
        Headers of ancestor blocks which are not direct parents (formerly
545
        uncles.)
546
547
    Returns
548
    -------
549
    block_output :
550
        The block output for the current block.
551
    """
552
    block_output = vm.BlockOutput()
553
554
    for i, tx in enumerate(map(decode_transaction, transactions)):
555
        process_transaction(block_env, block_output, tx, Uint(i))
556
557
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
558
559
    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:
565
    """
566
    Validates the ommers mentioned in the block.
567
568
    An ommer block is a block that wasn't canonically added to the
569
    blockchain because it wasn't validated as fast as the canonical block
570
    but was mined at the same time.
571
572
    To be considered valid, the ommers must adhere to the rules defined in
573
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
574
    there cannot be duplicate ommers in a block. Many of the other ommer
575
    constraints are listed in the in-line comments of this function.
576
577
    Parameters
578
    ----------
579
    ommers :
580
        List of ommers mentioned in the current block.
581
    block_header:
582
        The header of current block.
583
    chain :
584
        History and current state.
585
    """
586
    block_hash = keccak256(rlp.encode(block_header))
587
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
588
        raise InvalidBlock
589
590
    if len(ommers) == 0:
591
        # Nothing to validate
592
        return
593
594
    # Check that each ommer satisfies the constraints of a header
595
    for ommer in ommers:
596
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
597
            raise InvalidBlock
598
        validate_header(chain, ommer)
599
    if len(ommers) > 2:
600
        raise InvalidBlock
601
602
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
603
    if len(ommers_hashes) != len(set(ommers_hashes)):
604
        raise InvalidBlock
605
606
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
607
    recent_canonical_block_hashes = {
608
        keccak256(rlp.encode(block.header))
609
        for block in recent_canonical_blocks
610
    }
611
    recent_ommers_hashes: Set[Hash32] = set()
612
    for block in recent_canonical_blocks:
613
        recent_ommers_hashes = recent_ommers_hashes.union(
614
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
615
        )
616
617
    for ommer_index, ommer in enumerate(ommers):
618
        ommer_hash = ommers_hashes[ommer_index]
619
        if ommer_hash == block_hash:
620
            raise InvalidBlock
621
        if ommer_hash in recent_canonical_block_hashes:
622
            raise InvalidBlock
623
        if ommer_hash in recent_ommers_hashes:
624
            raise InvalidBlock
625
626
        # Ommer age with respect to the current block. For example, an age of
627
        # 1 indicates that the ommer is a sibling of previous block.
628
        ommer_age = block_header.number - ommer.number
629
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
630
            raise InvalidBlock
631
        if ommer.parent_hash not in recent_canonical_block_hashes:
632
            raise InvalidBlock
633
        if ommer.parent_hash == block_header.parent_hash:
634
            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:
643
    """
644
    Pay rewards to the block miner as well as the ommers miners.
645
646
    The miner of the canonical block is rewarded with the predetermined
647
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
648
    number of ommer blocks that were mined around the same time, and included
649
    in the canonical block's header. An ommer block is a block that wasn't
650
    added to the canonical blockchain because it wasn't validated as fast as
651
    the accepted block but was mined at the same time. Although not all blocks
652
    that are mined are added to the canonical chain, miners are still paid a
653
    reward for their efforts. This reward is called an ommer reward and is
654
    calculated based on the number associated with the ommer block that they
655
    mined.
656
657
    Parameters
658
    ----------
659
    state :
660
        Current account state.
661
    block_number :
662
        Position of the block within the chain.
663
    coinbase :
664
        Address of account which receives block reward and transaction fees.
665
    ommers :
666
        List of ommers mentioned in the current block.
667
    """
668
    ommer_count = U256(len(ommers))
669
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
670
    create_ether(state, coinbase, miner_reward)
671
672
    for ommer in ommers:
673
        # Ommer age with respect to the current block.
674
        ommer_age = U256(block_number - ommer.number)
675
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
676
        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:
685
    """
686
    Execute a transaction against the provided environment.
687
688
    This function processes the actions needed to execute a transaction.
689
    It decrements the sender's account after calculating the gas fee and
690
    refunds them the proper amount after execution. Calling contracts,
691
    deploying code, and incrementing nonces are all examples of actions that
692
    happen within this function or from a call made within this function.
693
694
    Accounts that are marked for deletion are processed and destroyed after
695
    execution.
696
697
    Parameters
698
    ----------
699
    block_env :
700
        Environment for the Ethereum Virtual Machine.
701
    block_output :
702
        The block output for the current block.
703
    tx :
704
        Transaction to execute.
705
    index:
706
        Index of the transaction in the block.
707
    """
708
    trie_set(
709
        block_output.transactions_trie,
710
        rlp.encode(index),
711
        encode_transaction(tx),
712
    )
713
714
    intrinsic_gas = validate_transaction(tx)
715
617
    sender = check_transaction(
716
    (
717
        sender,
718
        effective_gas_price,
719
    ) = check_transaction(
720
        block_env=block_env,
721
        block_output=block_output,
722
        tx=tx,
723
    )
724
725
    sender_account = get_account(block_env.state, sender)
726
727
    effective_gas_fee = tx.gas * effective_gas_price
728
729
    gas = tx.gas - intrinsic_gas
730
    increment_nonce(block_env.state, sender)
731
628
    gas_fee = tx.gas * tx.gas_price
629
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
732
    sender_balance_after_gas_fee = (
733
        Uint(sender_account.balance) - effective_gas_fee
734
    )
735
    set_account_balance(
736
        block_env.state, sender, U256(sender_balance_after_gas_fee)
737
    )
738
739
    access_list_addresses = set()
740
    access_list_storage_keys = set()
636
    if isinstance(tx, AccessListTransaction):
741
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
742
        for access in tx.access_list:
743
            access_list_addresses.add(access.account)
744
            for slot in access.slots:
745
                access_list_storage_keys.add((access.account, slot))
746
747
    tx_env = vm.TransactionEnvironment(
748
        origin=sender,
644
        gas_price=tx.gas_price,
749
        gas_price=effective_gas_price,
750
        gas=gas,
751
        access_list_addresses=access_list_addresses,
752
        access_list_storage_keys=access_list_storage_keys,
753
        index_in_block=index,
754
        tx_hash=get_transaction_hash(encode_transaction(tx)),
755
        traces=[],
756
    )
757
758
    message = prepare_message(block_env, tx_env, tx)
759
760
    tx_output = process_message_call(message)
761
762
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
763
    tx_gas_refund = min(
659
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
764
        tx_gas_used_before_refund // Uint(5), Uint(tx_output.refund_counter)
765
    )
766
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
767
    tx_gas_left = tx.gas - tx_gas_used_after_refund
663
    gas_refund_amount = tx_gas_left * tx.gas_price
768
    gas_refund_amount = tx_gas_left * effective_gas_price
769
665
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
770
    # For non-1559 transactions effective_gas_price == tx.gas_price
771
    priority_fee_per_gas = effective_gas_price - block_env.base_fee_per_gas
772
    transaction_fee = tx_gas_used_after_refund * priority_fee_per_gas
773
774
    # refund gas
775
    sender_balance_after_refund = get_account(
776
        block_env.state, sender
777
    ).balance + U256(gas_refund_amount)
778
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
779
780
    # transfer miner fees
781
    coinbase_balance_after_mining_fee = get_account(
782
        block_env.state, block_env.coinbase
783
    ).balance + U256(transaction_fee)
784
    if coinbase_balance_after_mining_fee != 0:
785
        set_account_balance(
786
            block_env.state,
787
            block_env.coinbase,
788
            coinbase_balance_after_mining_fee,
789
        )
790
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
791
        destroy_account(block_env.state, block_env.coinbase)
792
793
    for address in tx_output.accounts_to_delete:
794
        destroy_account(block_env.state, address)
795
796
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
797
798
    block_output.block_gas_used += tx_gas_used_after_refund
799
800
    receipt = make_receipt(
801
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
802
    )
803
804
    receipt_key = rlp.encode(Uint(index))
805
    block_output.receipt_keys += (receipt_key,)
806
807
    trie_set(
808
        block_output.receipts_trie,
809
        receipt_key,
810
        receipt,
811
    )
812
813
    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:
817
    """
818
    Validates the gas limit for a block.
819
820
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
821
    quotient of the parent block's gas limit and the
822
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
823
    passed through as a parameter is greater than or equal to the *sum* of
824
    the parent's gas and the adjustment delta then the limit for gas is too
825
    high and fails this function's check. Similarly, if the limit is less
826
    than or equal to the *difference* of the parent's gas and the adjustment
827
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
828
    check fails because the gas limit doesn't allow for a sufficient or
829
    reasonable amount of gas to be used on a block.
830
831
    Parameters
832
    ----------
833
    gas_limit :
834
        Gas limit to validate.
835
836
    parent_gas_limit :
837
        Gas limit of the parent block.
838
839
    Returns
840
    -------
841
    check : `bool`
842
        True if gas limit constraints are satisfied, False otherwise.
843
    """
844
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
845
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
846
        return False
847
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
848
        return False
849
    if gas_limit < GAS_LIMIT_MINIMUM:
850
        return False
851
852
    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:
862
    """
863
    Computes difficulty of a block using its header and parent header.
864
865
    The difficulty is determined by the time the block was created after its
866
    parent. The ``offset`` is calculated using the parent block's difficulty,
867
    ``parent_difficulty``, and the timestamp between blocks. This offset is
868
    then added to the parent difficulty and is stored as the ``difficulty``
869
    variable. If the time between the block and its parent is too short, the
870
    offset will result in a positive number thus making the sum of
871
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
872
    avoid mass forking. But, if the time is long enough, then the offset
873
    results in a negative value making the block less difficult than
874
    its parent.
875
876
    The base standard for a block's difficulty is the predefined value
877
    set for the genesis block since it has no parent. So, a block
878
    can't be less difficult than the genesis block, therefore each block's
879
    difficulty is set to the maximum value between the calculated
880
    difficulty and the ``GENESIS_DIFFICULTY``.
881
882
    Parameters
883
    ----------
884
    block_number :
885
        Block number of the block.
886
    block_timestamp :
887
        Timestamp of the block.
888
    parent_timestamp :
889
        Timestamp of the parent block.
890
    parent_difficulty :
891
        difficulty of the parent block.
892
    parent_has_ommers:
893
        does the parent have ommers.
894
895
    Returns
896
    -------
897
    difficulty : `ethereum.base_types.Uint`
898
        Computed difficulty for a block.
899
    """
900
    offset = (
901
        int(parent_difficulty)
902
        // 2048
903
        * max(
904
            (2 if parent_has_ommers else 1)
905
            - int(block_timestamp - parent_timestamp) // 9,
906
            -99,
907
        )
908
    )
909
    difficulty = int(parent_difficulty) + offset
910
    # Historical Note: The difficulty bomb was not present in Ethereum at the
911
    # start of Frontier, but was added shortly after launch. However since the
912
    # bomb has no effect prior to block 200000 we pretend it existed from
913
    # genesis.
914
    # See https://github.com/ethereum/go-ethereum/pull/1588
915
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
916
    if num_bomb_periods >= 0:
917
        difficulty += 2**num_bomb_periods
918
919
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
920
    # the bomb. This bug does not matter because the difficulty is always much
921
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
922
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))