ethereum.berlin.forkethereum.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

63
BOMB_DELAY_BLOCKS = 9000000
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 != .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):
219
        raise InvalidBlock
220
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
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,
278
        header.extra_data,
360
        header.extra_data,
361
        header.base_fee_per_gas,
362
    )
363
364
    return rlp.rlp_hash(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) -> AddressTuple[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
345
    return sender_address
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[Exception], ​​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)
383
    else:
384
        return 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
480
        sender_address = check_transaction(tx, gas_available, chain_id)
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,
489
            gas_price=tx.gas_price,
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 = rlp.rlp_hash(block_header)
664
    if rlp.rlp_hash(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 = [rlp.rlp_hash(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
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
689
    }
690
    recent_ommers_hashes: Set[Hash32] = set()
691
    for block in recent_canonical_blocks:
692
        recent_ommers_hashes = recent_ommers_hashes.union(
693
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
694
        )
695
696
    for ommer_index, ommer in enumerate(ommers):
697
        ommer_hash = ommers_hashes[ommer_index]
698
        if ommer_hash == block_hash:
699
            raise InvalidBlock
700
        if ommer_hash in recent_canonical_block_hashes:
701
            raise InvalidBlock
702
        if ommer_hash in recent_ommers_hashes:
703
            raise InvalidBlock
704
705
        # Ommer age with respect to the current block. For example, an age of
706
        # 1 indicates that the ommer is a sibling of previous block.
707
        ommer_age = block_header.number - ommer.number
708
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
709
            raise InvalidBlock
710
        if ommer.parent_hash not in recent_canonical_block_hashes:
711
            raise InvalidBlock
712
        if ommer.parent_hash == block_header.parent_hash:
713
            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:
722
    """
723
    Pay rewards to the block miner as well as the ommers miners.
724
725
    The miner of the canonical block is rewarded with the predetermined
726
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
727
    number of ommer blocks that were mined around the same time, and included
728
    in the canonical block's header. An ommer block is a block that wasn't
729
    added to the canonical blockchain because it wasn't validated as fast as
730
    the accepted block but was mined at the same time. Although not all blocks
731
    that are mined are added to the canonical chain, miners are still paid a
732
    reward for their efforts. This reward is called an ommer reward and is
733
    calculated based on the number associated with the ommer block that they
734
    mined.
735
736
    Parameters
737
    ----------
738
    state :
739
        Current account state.
740
    block_number :
741
        Position of the block within the chain.
742
    coinbase :
743
        Address of account which receives block reward and transaction fees.
744
    ommers :
745
        List of ommers mentioned in the current block.
746
    """
747
    ommer_count = U256(len(ommers))
748
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
749
    create_ether(state, coinbase, miner_reward)
750
751
    for ommer in ommers:
752
        # Ommer age with respect to the current block.
753
        ommer_age = U256(block_number - ommer.number)
754
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
755
        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.berlin.vm.Environmentethereum.london.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...], Optional[Exception]]:
761
    """
762
    Execute a transaction against the provided environment.
763
764
    This function processes the actions needed to execute a transaction.
765
    It decrements the sender's account after calculating the gas fee and
766
    refunds them the proper amount after execution. Calling contracts,
767
    deploying code, and incrementing nonces are all examples of actions that
768
    happen within this function or from a call made within this function.
769
770
    Accounts that are marked for deletion are processed and destroyed after
771
    execution.
772
773
    Parameters
774
    ----------
775
    env :
776
        Environment for the Ethereum Virtual Machine.
777
    tx :
778
        Transaction to execute.
779
780
    Returns
781
    -------
782
    gas_left : `ethereum.base_types.U256`
783
        Remaining gas after execution.
784
    logs : `Tuple[ethereum.blocks.Log, ...]`
785
        Logs generated during execution.
786
    """
787
    if not validate_transaction(tx):
788
        raise InvalidBlock
789
790
    sender = env.origin
791
    sender_account = get_account(env.state, sender)
680
    gas_fee = tx.gas * tx.gas_price
792
793
    max_gas_fee: Uint
794
    if isinstance(tx, FeeMarketTransaction):
795
        max_gas_fee = Uint(tx.gas) * Uint(tx.max_fee_per_gas)
796
    else:
797
        max_gas_fee = Uint(tx.gas) * Uint(tx.gas_price)
798
    if sender_account.nonce != tx.nonce:
799
        raise InvalidBlock
683
    if Uint(sender_account.balance) < gas_fee + Uint(tx.value):
800
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
801
        raise InvalidBlock
802
    if sender_account.code != bytearray():
803
        raise InvalidSenderError("not EOA")
804
805
    effective_gas_fee = tx.gas * env.gas_price
806
807
    gas = tx.gas - calculate_intrinsic_cost(tx)
808
    increment_nonce(env.state, sender)
690
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
809
810
    sender_balance_after_gas_fee = (
811
        Uint(sender_account.balance) - effective_gas_fee
812
    )
813
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
814
815
    preaccessed_addresses = set()
816
    preaccessed_storage_keys = set()
695
    if isinstance(tx, AccessListTransaction):
817
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
818
        for address, keys in tx.access_list:
819
            preaccessed_addresses.add(address)
820
            for key in keys:
821
                preaccessed_storage_keys.add((address, key))
822
823
    message = prepare_message(
824
        sender,
825
        tx.to,
826
        tx.value,
827
        tx.data,
828
        gas,
829
        env,
830
        preaccessed_addresses=frozenset(preaccessed_addresses),
831
        preaccessed_storage_keys=frozenset(preaccessed_storage_keys),
832
    )
833
834
    output = process_message_call(message, env)
835
836
    gas_used = tx.gas - output.gas_left
715
    gas_refund = min(gas_used // Uint(2), Uint(output.refund_counter))
716
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
717
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
837
    gas_refund = min(gas_used // Uint(5), Uint(output.refund_counter))
838
    gas_refund_amount = (output.gas_left + gas_refund) * env.gas_price
839
840
    # For non-1559 transactions env.gas_price == tx.gas_price
841
    priority_fee_per_gas = env.gas_price - env.base_fee_per_gas
842
    transaction_fee = (
843
        tx.gas - output.gas_left - gas_refund
844
    ) * priority_fee_per_gas
845
846
    total_gas_used = gas_used - gas_refund
847
848
    # refund gas
849
    sender_balance_after_refund = get_account(
850
        env.state, sender
851
    ).balance + U256(gas_refund_amount)
852
    set_account_balance(env.state, sender, sender_balance_after_refund)
853
854
    # transfer miner fees
855
    coinbase_balance_after_mining_fee = get_account(
856
        env.state, env.coinbase
857
    ).balance + U256(transaction_fee)
858
    if coinbase_balance_after_mining_fee != 0:
859
        set_account_balance(
860
            env.state, env.coinbase, coinbase_balance_after_mining_fee
861
        )
862
    elif account_exists_and_is_empty(env.state, env.coinbase):
863
        destroy_account(env.state, env.coinbase)
864
865
    for address in output.accounts_to_delete:
866
        destroy_account(env.state, address)
867
868
    for address in output.touched_accounts:
869
        if account_exists_and_is_empty(env.state, address):
870
            destroy_account(env.state, address)
871
872
    return total_gas_used, output.logs, output.error

validate_transaction

Verifies a transaction.

The gas in a transaction gets used to pay for the intrinsic cost of operations, therefore if there is insufficient gas then it would not be possible to execute a transaction and it will be declared invalid.

Additionally, the nonce of a transaction must not equal or exceed the limit defined in EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>_. In practice, defining the limit as 2**64-1 has no impact because sending 2**64-1 transactions is improbable. It's not strictly impossible though, 2**64-1 transactions is the entire capacity of the Ethereum blockchain at 2022 gas limits for a little over 22 years.

Parameters

tx : Transaction to validate.

Returns

verified : bool True if the transaction can be executed, or False otherwise.

def validate_transaction(tx: Transaction) -> bool:
876
    """
877
    Verifies a transaction.
878
879
    The gas in a transaction gets used to pay for the intrinsic cost of
880
    operations, therefore if there is insufficient gas then it would not
881
    be possible to execute a transaction and it will be declared invalid.
882
883
    Additionally, the nonce of a transaction must not equal or exceed the
884
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
885
    In practice, defining the limit as ``2**64-1`` has no impact because
886
    sending ``2**64-1`` transactions is improbable. It's not strictly
887
    impossible though, ``2**64-1`` transactions is the entire capacity of the
888
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
889
890
    Parameters
891
    ----------
892
    tx :
893
        Transaction to validate.
894
895
    Returns
896
    -------
897
    verified : `bool`
898
        True if the transaction can be executed, or False otherwise.
899
    """
900
    if calculate_intrinsic_cost(tx) > Uint(tx.gas):
901
        return False
902
    if tx.nonce >= U256(U64.MAX_VALUE):
903
        return False
904
    return True

calculate_intrinsic_cost

Calculates the gas that is charged before execution is started.

The intrinsic cost of the transaction is charged before execution has begun. Functions/operations in the EVM cost money to execute so this intrinsic cost is for the operations that need to be paid for as part of the transaction. Data transfer, for example, is part of this intrinsic cost. It costs ether to send data over the wire and that ether is accounted for in the intrinsic cost calculated in this function. This intrinsic cost must be calculated and paid for before execution in order for all operations to be implemented.

Parameters

tx : Transaction to compute the intrinsic cost of.

Returns

verified : ethereum.base_types.Uint The intrinsic cost of the transaction.

def calculate_intrinsic_cost(tx: Transaction) -> Uint:
908
    """
909
    Calculates the gas that is charged before execution is started.
910
911
    The intrinsic cost of the transaction is charged before execution has
912
    begun. Functions/operations in the EVM cost money to execute so this
913
    intrinsic cost is for the operations that need to be paid for as part of
914
    the transaction. Data transfer, for example, is part of this intrinsic
915
    cost. It costs ether to send data over the wire and that ether is
916
    accounted for in the intrinsic cost calculated in this function. This
917
    intrinsic cost must be calculated and paid for before execution in order
918
    for all operations to be implemented.
919
920
    Parameters
921
    ----------
922
    tx :
923
        Transaction to compute the intrinsic cost of.
924
925
    Returns
926
    -------
927
    verified : `ethereum.base_types.Uint`
928
        The intrinsic cost of the transaction.
929
    """
930
    data_cost = 0
931
932
    for byte in tx.data:
933
        if byte == 0:
934
            data_cost += TX_DATA_COST_PER_ZERO
935
        else:
936
            data_cost += TX_DATA_COST_PER_NON_ZERO
937
938
    if tx.to == Bytes0(b""):
939
        create_cost = TX_CREATE_COST
940
    else:
941
        create_cost = 0
942
943
    access_list_cost = 0
816
    if isinstance(tx, AccessListTransaction):
944
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
945
        for _address, keys in tx.access_list:
946
            access_list_cost += TX_ACCESS_LIST_ADDRESS_COST
947
            access_list_cost += len(keys) * TX_ACCESS_LIST_STORAGE_KEY_COST
948
949
    return Uint(TX_BASE_COST + data_cost + create_cost + access_list_cost)

recover_sender

Extracts the sender address from a transaction.

The v, r, and s values are the three parts that make up the signature of a transaction. In order to recover the sender of a transaction the two components needed are the signature (v, r, and s) and the signing hash of the transaction. The sender's public key can be obtained with these two values and therefore the sender address can be retrieved.

Parameters

tx : Transaction of interest. chain_id : ID of the executing chain.

Returns

sender : ethereum.fork_types.Address The address of the account that signed the transaction.

def recover_sender(chain_id: U64, ​​tx: Transaction) -> Address:
953
    """
954
    Extracts the sender address from a transaction.
955
956
    The v, r, and s values are the three parts that make up the signature
957
    of a transaction. In order to recover the sender of a transaction the two
958
    components needed are the signature (``v``, ``r``, and ``s``) and the
959
    signing hash of the transaction. The sender's public key can be obtained
960
    with these two values and therefore the sender address can be retrieved.
961
962
    Parameters
963
    ----------
964
    tx :
965
        Transaction of interest.
966
    chain_id :
967
        ID of the executing chain.
968
969
    Returns
970
    -------
971
    sender : `ethereum.fork_types.Address`
972
        The address of the account that signed the transaction.
973
    """
974
    r, s = tx.r, tx.s
975
    if U256(0) >= r or r >= SECP256K1N:
976
        raise InvalidBlock
977
    if U256(0) >= s or s > SECP256K1N // U256(2):
978
        raise InvalidBlock
979
980
    if isinstance(tx, LegacyTransaction):
981
        v = tx.v
982
        if v == 27 or v == 28:
983
            public_key = secp256k1_recover(
984
                r, s, v - U256(27), signing_hash_pre155(tx)
985
            )
986
        else:
987
            chain_id_x2 = U256(chain_id) * U256(2)
988
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
989
                raise InvalidBlock
990
            public_key = secp256k1_recover(
991
                r,
992
                s,
993
                v - U256(35) - chain_id_x2,
994
                signing_hash_155(tx, chain_id),
995
            )
996
    elif isinstance(tx, AccessListTransaction):
997
        public_key = secp256k1_recover(
998
            r, s, tx.y_parity, signing_hash_2930(tx)
871
        )
999
        )
1000
    elif isinstance(tx, FeeMarketTransaction):
1001
        public_key = secp256k1_recover(
1002
            r, s, tx.y_parity, signing_hash_1559(tx)
1003
        )
1004
1005
    return Address(keccak256(public_key)[12:32])

signing_hash_pre155

Compute the hash of a transaction used in a legacy (pre EIP 155) signature.

Parameters

tx : Transaction of interest.

Returns

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

def signing_hash_pre155(tx: TransactionLegacyTransaction) -> Hash32:
1009
    """
1010
    Compute the hash of a transaction used in a legacy (pre EIP 155) signature.
1011
1012
    Parameters
1013
    ----------
1014
    tx :
1015
        Transaction of interest.
1016
1017
    Returns
1018
    -------
1019
    hash : `ethereum.crypto.hash.Hash32`
1020
        Hash of the transaction.
1021
    """
1022
    return keccak256(
1023
        rlp.encode(
1024
            (
1025
                tx.nonce,
1026
                tx.gas_price,
1027
                tx.gas,
1028
                tx.to,
1029
                tx.value,
1030
                tx.data,
1031
            )
1032
        )
1033
    )

signing_hash_155

Compute the hash of a transaction used in a EIP 155 signature.

Parameters

tx : Transaction of interest. chain_id : The id of the current chain.

Returns

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

def signing_hash_155(tx: TransactionLegacyTransaction, ​​chain_id: U64) -> Hash32:
1037
    """
1038
    Compute the hash of a transaction used in a EIP 155 signature.
1039
1040
    Parameters
1041
    ----------
1042
    tx :
1043
        Transaction of interest.
1044
    chain_id :
1045
        The id of the current chain.
1046
1047
    Returns
1048
    -------
1049
    hash : `ethereum.crypto.hash.Hash32`
1050
        Hash of the transaction.
1051
    """
1052
    return keccak256(
1053
        rlp.encode(
1054
            (
1055
                tx.nonce,
1056
                tx.gas_price,
1057
                tx.gas,
1058
                tx.to,
1059
                tx.value,
1060
                tx.data,
1061
                chain_id,
1062
                Uint(0),
1063
                Uint(0),
1064
            )
1065
        )
1066
    )

signing_hash_2930

Compute the hash of a transaction used in a EIP 2930 signature.

Parameters

tx : Transaction of interest.

Returns

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

def signing_hash_2930(tx: AccessListTransaction) -> Hash32:
1070
    """
1071
    Compute the hash of a transaction used in a EIP 2930 signature.
1072
1073
    Parameters
1074
    ----------
1075
    tx :
1076
        Transaction of interest.
1077
1078
    Returns
1079
    -------
1080
    hash : `ethereum.crypto.hash.Hash32`
1081
        Hash of the transaction.
1082
    """
1083
    return keccak256(
1084
        b"\x01"
1085
        + rlp.encode(
1086
            (
1087
                tx.chain_id,
1088
                tx.nonce,
1089
                tx.gas_price,
1090
                tx.gas,
1091
                tx.to,
1092
                tx.value,
1093
                tx.data,
1094
                tx.access_list,
1095
            )
1096
        )
1097
    )

signing_hash_1559

Compute the hash of a transaction used in a EIP 1559 signature.

Parameters

tx : Transaction of interest.

Returns

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

def signing_hash_1559(tx: FeeMarketTransaction) -> Hash32:
1101
    """
1102
    Compute the hash of a transaction used in a EIP 1559 signature.
1103
1104
    Parameters
1105
    ----------
1106
    tx :
1107
        Transaction of interest.
1108
1109
    Returns
1110
    -------
1111
    hash : `ethereum.crypto.hash.Hash32`
1112
        Hash of the transaction.
1113
    """
1114
    return keccak256(
1115
        b"\x02"
1116
        + rlp.encode(
1117
            (
1118
                tx.chain_id,
1119
                tx.nonce,
1120
                tx.max_priority_fee_per_gas,
1121
                tx.max_fee_per_gas,
1122
                tx.gas,
1123
                tx.to,
1124
                tx.value,
1125
                tx.data,
1126
                tx.access_list,
1127
            )
1128
        )
1129
    )

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:
1133
    """
1134
    Computes the hash of a block header.
1135
1136
    The header hash of a block is the canonical hash that is used to refer
1137
    to a specific block and completely distinguishes a block from another.
1138
1139
    ``keccak256`` is a function that produces a 256 bit hash of any input.
1140
    It also takes in any number of bytes as an input and produces a single
1141
    hash for them. A hash is a completely unique output for a single input.
1142
    So an input corresponds to one unique hash that can be used to identify
1143
    the input exactly.
1144
1145
    Prior to using the ``keccak256`` hash function, the header must be
1146
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
1147
    RLP encoding the header converts it into a space-efficient format that
1148
    allows for easy transfer of data between nodes. The purpose of RLP is to
1149
    encode arbitrarily nested arrays of binary data, and RLP is the primary
1150
    encoding method used to serialize objects in Ethereum's execution layer.
1151
    The only purpose of RLP is to encode structure; encoding specific data
1152
    types (e.g. strings, floats) is left up to higher-order protocols.
1153
1154
    Parameters
1155
    ----------
1156
    header :
1157
        Header of interest.
1158
1159
    Returns
1160
    -------
1161
    hash : `ethereum.crypto.hash.Hash32`
1162
        Hash of the header.
1163
    """
1164
    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:
1168
    """
1169
    Validates the gas limit for a block.
1170
1171
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
1172
    quotient of the parent block's gas limit and the
1173
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
1174
    passed through as a parameter is greater than or equal to the *sum* of
1175
    the parent's gas and the adjustment delta then the limit for gas is too
1176
    high and fails this function's check. Similarly, if the limit is less
1177
    than or equal to the *difference* of the parent's gas and the adjustment
1178
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
1179
    check fails because the gas limit doesn't allow for a sufficient or
1180
    reasonable amount of gas to be used on a block.
1181
1182
    Parameters
1183
    ----------
1184
    gas_limit :
1185
        Gas limit to validate.
1186
1187
    parent_gas_limit :
1188
        Gas limit of the parent block.
1189
1190
    Returns
1191
    -------
1192
    check : `bool`
1193
        True if gas limit constraints are satisfied, False otherwise.
1194
    """
1195
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
1196
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
1197
        return False
1198
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
1199
        return False
1200
    if gas_limit < GAS_LIMIT_MINIMUM:
1201
        return False
1202
1203
    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:
1213
    """
1214
    Computes difficulty of a block using its header and parent header.
1215
1216
    The difficulty is determined by the time the block was created after its
1217
    parent. The ``offset`` is calculated using the parent block's difficulty,
1218
    ``parent_difficulty``, and the timestamp between blocks. This offset is
1219
    then added to the parent difficulty and is stored as the ``difficulty``
1220
    variable. If the time between the block and its parent is too short, the
1221
    offset will result in a positive number thus making the sum of
1222
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
1223
    avoid mass forking. But, if the time is long enough, then the offset
1224
    results in a negative value making the block less difficult than
1225
    its parent.
1226
1227
    The base standard for a block's difficulty is the predefined value
1228
    set for the genesis block since it has no parent. So, a block
1229
    can't be less difficult than the genesis block, therefore each block's
1230
    difficulty is set to the maximum value between the calculated
1231
    difficulty and the ``GENESIS_DIFFICULTY``.
1232
1233
    Parameters
1234
    ----------
1235
    block_number :
1236
        Block number of the block.
1237
    block_timestamp :
1238
        Timestamp of the block.
1239
    parent_timestamp :
1240
        Timestamp of the parent block.
1241
    parent_difficulty :
1242
        difficulty of the parent block.
1243
    parent_has_ommers:
1244
        does the parent have ommers.
1245
1246
    Returns
1247
    -------
1248
    difficulty : `ethereum.base_types.Uint`
1249
        Computed difficulty for a block.
1250
    """
1251
    offset = (
1252
        int(parent_difficulty)
1253
        // 2048
1254
        * max(
1255
            (2 if parent_has_ommers else 1)
1256
            - int(block_timestamp - parent_timestamp) // 9,
1257
            -99,
1258
        )
1259
    )
1260
    difficulty = int(parent_difficulty) + offset
1261
    # Historical Note: The difficulty bomb was not present in Ethereum at the
1262
    # start of Frontier, but was added shortly after launch. However since the
1263
    # bomb has no effect prior to block 200000 we pretend it existed from
1264
    # genesis.
1265
    # See https://github.com/ethereum/go-ethereum/pull/1588
1266
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
1267
    if num_bomb_periods >= 0:
1268
        difficulty += 2**num_bomb_periods
1269
1270
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
1271
    # the bomb. This bug does not matter because the difficulty is always much
1272
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
1273
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))