ethereum.gray_glacier.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)

MAX_OMMER_DEPTH

65
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

66
BOMB_DELAY_BLOCKS = 11400000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

70
@dataclass
class BlockChain:

blocks

76
    blocks: List[Block]

state

77
    state: State

chain_id

78
    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:
82
    """
83
    Transforms the state from the previous hard fork (`old`) into the block
84
    chain object for this hard fork and returns it.
85
86
    When forks need to implement an irregular state transition, this function
87
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
88
    an example.
89
90
    Parameters
91
    ----------
92
    old :
93
        Previous block chain object.
94
95
    Returns
96
    -------
97
    new : `BlockChain`
98
        Upgraded block chain object for this hard fork.
99
    """
100
    return old

get_last_256_block_hashes

Obtain the list of hashes of the previous 256 blocks in order of increasing block number.

This function will return less hashes for the first 256 blocks.

The BLOCKHASH opcode needs to access the latest hashes on the chain, therefore this function retrieves them.

Parameters

chain : History and current state.

Returns

recent_block_hashes : List[Hash32] Hashes of the recent 256 blocks in order of increasing block number.

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

check_transaction

Check if the transaction is includable in the block.

Parameters

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

Returns

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

Raises

InvalidBlock : If the transaction is not includable.

def check_transaction(tx: Transaction, ​​base_fee_per_gas: Uint, ​​gas_available: Uint, ​​chain_id: U64) -> Tuple[Address, Uint]:
397
    """
398
    Check if the transaction is includable in the block.
399
400
    Parameters
401
    ----------
402
    tx :
403
        The transaction.
404
    base_fee_per_gas :
405
        The block base fee.
406
    gas_available :
407
        The gas remaining in the block.
408
    chain_id :
409
        The ID of the current chain.
410
411
    Returns
412
    -------
413
    sender_address :
414
        The sender of the transaction.
415
    effective_gas_price :
416
        The price to charge for gas when the transaction is executed.
417
418
    Raises
419
    ------
420
    InvalidBlock :
421
        If the transaction is not includable.
422
    """
423
    if tx.gas > gas_available:
424
        raise InvalidBlock
425
    sender_address = recover_sender(chain_id, tx)
426
427
    if isinstance(tx, FeeMarketTransaction):
428
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
429
            raise InvalidBlock
430
        if tx.max_fee_per_gas < base_fee_per_gas:
431
            raise InvalidBlock
432
433
        priority_fee_per_gas = min(
434
            tx.max_priority_fee_per_gas,
435
            tx.max_fee_per_gas - base_fee_per_gas,
436
        )
437
        effective_gas_price = priority_fee_per_gas + base_fee_per_gas
438
    else:
439
        if tx.gas_price < base_fee_per_gas:
440
            raise InvalidBlock
441
        effective_gas_price = tx.gas_price
442
443
    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]:
452
    """
453
    Make the receipt for a transaction that was executed.
454
455
    Parameters
456
    ----------
457
    tx :
458
        The executed transaction.
459
    error :
460
        Error in the top level frame of the transaction, if any.
461
    cumulative_gas_used :
462
        The total gas used so far in the block after the transaction was
463
        executed.
464
    logs :
465
        The logs produced by the transaction.
466
467
    Returns
468
    -------
469
    receipt :
470
        The receipt for the transaction.
471
    """
472
    receipt = Receipt(
473
        succeeded=error is None,
474
        cumulative_gas_used=cumulative_gas_used,
475
        bloom=logs_bloom(logs),
476
        logs=logs,
477
    )
478
479
    if isinstance(tx, AccessListTransaction):
480
        return b"\x01" + rlp.encode(receipt)
481
    elif isinstance(tx, FeeMarketTransaction):
482
        return b"\x02" + rlp.encode(receipt)
483
    else:
484
        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.

487
@dataclass
class ApplyBodyOutput:

block_gas_used

507
    block_gas_used: Uint

transactions_root

508
    transactions_root: Root

receipt_root

509
    receipt_root: Root

block_logs_bloom

510
    block_logs_bloom: Bloom

state_root

511
    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:
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
    state :
540
        Current account state.
541
    block_hashes :
542
        List of hashes of the previous 256 blocks in the order of
543
        increasing block number.
544
    coinbase :
545
        Address of account which receives block reward and transaction fees.
546
    block_number :
547
        Position of the block within the chain.
548
    base_fee_per_gas :
549
        Base fee per gas of within the block.
550
    block_gas_limit :
551
        Initial amount of gas available for execution in this block.
552
    block_time :
553
        Time the block was produced, measured in seconds since the epoch.
554
    block_difficulty :
555
        Difficulty of the block.
556
    transactions :
557
        Transactions included in the block.
558
    ommers :
559
        Headers of ancestor blocks which are not direct parents (formerly
560
        uncles.)
561
    chain_id :
562
        ID of the executing chain.
563
564
    Returns
565
    -------
566
    apply_body_output : `ApplyBodyOutput`
567
        Output of applying the block body to the state.
568
    """
569
    gas_available = block_gas_limit
570
    transactions_trie: Trie[
571
        Bytes, Optional[Union[Bytes, LegacyTransaction]]
572
    ] = Trie(secured=False, default=None)
573
    receipts_trie: Trie[Bytes, Optional[Union[Bytes, Receipt]]] = Trie(
574
        secured=False, default=None
575
    )
576
    block_logs: Tuple[Log, ...] = ()
577
578
    for i, tx in enumerate(map(decode_transaction, transactions)):
579
        trie_set(
580
            transactions_trie, rlp.encode(Uint(i)), encode_transaction(tx)
581
        )
582
583
        sender_address, effective_gas_price = check_transaction(
584
            tx, base_fee_per_gas, gas_available, chain_id
585
        )
586
587
        env = vm.Environment(
588
            caller=sender_address,
589
            origin=sender_address,
590
            block_hashes=block_hashes,
591
            coinbase=coinbase,
592
            number=block_number,
593
            gas_limit=block_gas_limit,
594
            base_fee_per_gas=base_fee_per_gas,
595
            gas_price=effective_gas_price,
596
            time=block_time,
597
            difficulty=block_difficulty,
598
            state=state,
599
            chain_id=chain_id,
600
            traces=[],
601
        )
602
603
        gas_used, logs, error = process_transaction(env, tx)
604
        gas_available -= gas_used
605
606
        receipt = make_receipt(
607
            tx, error, (block_gas_limit - gas_available), logs
608
        )
609
610
        trie_set(
611
            receipts_trie,
612
            rlp.encode(Uint(i)),
613
            receipt,
614
        )
615
616
        block_logs += logs
617
618
    pay_rewards(state, block_number, coinbase, ommers)
619
620
    block_gas_used = block_gas_limit - gas_available
621
622
    block_logs_bloom = logs_bloom(block_logs)
623
624
    return ApplyBodyOutput(
625
        block_gas_used,
626
        root(transactions_trie),
627
        root(receipts_trie),
628
        block_logs_bloom,
629
        state_root(state),
630
    )

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:
636
    """
637
    Validates the ommers mentioned in the block.
638
639
    An ommer block is a block that wasn't canonically added to the
640
    blockchain because it wasn't validated as fast as the canonical block
641
    but was mined at the same time.
642
643
    To be considered valid, the ommers must adhere to the rules defined in
644
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
645
    there cannot be duplicate ommers in a block. Many of the other ommer
646
    constraints are listed in the in-line comments of this function.
647
648
    Parameters
649
    ----------
650
    ommers :
651
        List of ommers mentioned in the current block.
652
    block_header:
653
        The header of current block.
654
    chain :
655
        History and current state.
656
    """
657
    block_hash = keccak256(rlp.encode(block_header))
658
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
659
        raise InvalidBlock
660
661
    if len(ommers) == 0:
662
        # Nothing to validate
663
        return
664
665
    # Check that each ommer satisfies the constraints of a header
666
    for ommer in ommers:
667
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
668
            raise InvalidBlock
669
        ommer_parent_header = chain.blocks[
670
            -(block_header.number - ommer.number) - 1
671
        ].header
672
        validate_header(ommer, ommer_parent_header)
673
    if len(ommers) > 2:
674
        raise InvalidBlock
675
676
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
677
    if len(ommers_hashes) != len(set(ommers_hashes)):
678
        raise InvalidBlock
679
680
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
681
    recent_canonical_block_hashes = {
682
        keccak256(rlp.encode(block.header))
683
        for block in recent_canonical_blocks
684
    }
685
    recent_ommers_hashes: Set[Hash32] = set()
686
    for block in recent_canonical_blocks:
687
        recent_ommers_hashes = recent_ommers_hashes.union(
688
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
689
        )
690
691
    for ommer_index, ommer in enumerate(ommers):
692
        ommer_hash = ommers_hashes[ommer_index]
693
        if ommer_hash == block_hash:
694
            raise InvalidBlock
695
        if ommer_hash in recent_canonical_block_hashes:
696
            raise InvalidBlock
697
        if ommer_hash in recent_ommers_hashes:
698
            raise InvalidBlock
699
700
        # Ommer age with respect to the current block. For example, an age of
701
        # 1 indicates that the ommer is a sibling of previous block.
702
        ommer_age = block_header.number - ommer.number
703
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
704
            raise InvalidBlock
705
        if ommer.parent_hash not in recent_canonical_block_hashes:
706
            raise InvalidBlock
707
        if ommer.parent_hash == block_header.parent_hash:
708
            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:
717
    """
718
    Pay rewards to the block miner as well as the ommers miners.
719
720
    The miner of the canonical block is rewarded with the predetermined
721
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
722
    number of ommer blocks that were mined around the same time, and included
723
    in the canonical block's header. An ommer block is a block that wasn't
724
    added to the canonical blockchain because it wasn't validated as fast as
725
    the accepted block but was mined at the same time. Although not all blocks
726
    that are mined are added to the canonical chain, miners are still paid a
727
    reward for their efforts. This reward is called an ommer reward and is
728
    calculated based on the number associated with the ommer block that they
729
    mined.
730
731
    Parameters
732
    ----------
733
    state :
734
        Current account state.
735
    block_number :
736
        Position of the block within the chain.
737
    coinbase :
738
        Address of account which receives block reward and transaction fees.
739
    ommers :
740
        List of ommers mentioned in the current block.
741
    """
742
    ommer_count = U256(len(ommers))
743
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
744
    create_ether(state, coinbase, miner_reward)
745
746
    for ommer in ommers:
747
        # Ommer age with respect to the current block.
748
        ommer_age = U256(block_number - ommer.number)
749
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
750
        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.gray_glacier.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...], Optional[EthereumException]]:
756
    """
757
    Execute a transaction against the provided environment.
758
759
    This function processes the actions needed to execute a transaction.
760
    It decrements the sender's account after calculating the gas fee and
761
    refunds them the proper amount after execution. Calling contracts,
762
    deploying code, and incrementing nonces are all examples of actions that
763
    happen within this function or from a call made within this function.
764
765
    Accounts that are marked for deletion are processed and destroyed after
766
    execution.
767
768
    Parameters
769
    ----------
770
    env :
771
        Environment for the Ethereum Virtual Machine.
772
    tx :
773
        Transaction to execute.
774
775
    Returns
776
    -------
777
    gas_left : `ethereum.base_types.U256`
778
        Remaining gas after execution.
779
    logs : `Tuple[ethereum.blocks.Log, ...]`
780
        Logs generated during execution.
781
    """
782
    if not validate_transaction(tx):
783
        raise InvalidBlock
784
785
    sender = env.origin
786
    sender_account = get_account(env.state, sender)
787
788
    max_gas_fee: Uint
789
    if isinstance(tx, FeeMarketTransaction):
790
        max_gas_fee = Uint(tx.gas) * Uint(tx.max_fee_per_gas)
791
    else:
792
        max_gas_fee = Uint(tx.gas) * Uint(tx.gas_price)
793
    if sender_account.nonce != tx.nonce:
794
        raise InvalidBlock
795
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
796
        raise InvalidBlock
797
    if sender_account.code != bytearray():
798
        raise InvalidSenderError("not EOA")
799
800
    effective_gas_fee = tx.gas * env.gas_price
801
802
    gas = tx.gas - calculate_intrinsic_cost(tx)
803
    increment_nonce(env.state, sender)
804
805
    sender_balance_after_gas_fee = (
806
        Uint(sender_account.balance) - effective_gas_fee
807
    )
808
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
809
810
    preaccessed_addresses = set()
811
    preaccessed_storage_keys = set()
812
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
813
        for address, keys in tx.access_list:
814
            preaccessed_addresses.add(address)
815
            for key in keys:
816
                preaccessed_storage_keys.add((address, key))
817
818
    message = prepare_message(
819
        sender,
820
        tx.to,
821
        tx.value,
822
        tx.data,
823
        gas,
824
        env,
825
        preaccessed_addresses=frozenset(preaccessed_addresses),
826
        preaccessed_storage_keys=frozenset(preaccessed_storage_keys),
827
    )
828
829
    output = process_message_call(message, env)
830
831
    gas_used = tx.gas - output.gas_left
832
    gas_refund = min(gas_used // Uint(5), Uint(output.refund_counter))
833
    gas_refund_amount = (output.gas_left + gas_refund) * env.gas_price
834
835
    # For non-1559 transactions env.gas_price == tx.gas_price
836
    priority_fee_per_gas = env.gas_price - env.base_fee_per_gas
837
    transaction_fee = (
838
        tx.gas - output.gas_left - gas_refund
839
    ) * priority_fee_per_gas
840
841
    total_gas_used = gas_used - gas_refund
842
843
    # refund gas
844
    sender_balance_after_refund = get_account(
845
        env.state, sender
846
    ).balance + U256(gas_refund_amount)
847
    set_account_balance(env.state, sender, sender_balance_after_refund)
848
849
    # transfer miner fees
850
    coinbase_balance_after_mining_fee = get_account(
851
        env.state, env.coinbase
852
    ).balance + U256(transaction_fee)
853
    if coinbase_balance_after_mining_fee != 0:
854
        set_account_balance(
855
            env.state, env.coinbase, coinbase_balance_after_mining_fee
856
        )
857
    elif account_exists_and_is_empty(env.state, env.coinbase):
858
        destroy_account(env.state, env.coinbase)
859
860
    for address in output.accounts_to_delete:
861
        destroy_account(env.state, address)
862
863
    for address in output.touched_accounts:
864
        if account_exists_and_is_empty(env.state, address):
865
            destroy_account(env.state, address)
866
867
    return total_gas_used, output.logs, output.error

compute_header_hash

Computes the hash of a block header.

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

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

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

Parameters

header : Header of interest.

Returns

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

def compute_header_hash(header: Header) -> Hash32:
871
    """
872
    Computes the hash of a block header.
873
874
    The header hash of a block is the canonical hash that is used to refer
875
    to a specific block and completely distinguishes a block from another.
876
877
    ``keccak256`` is a function that produces a 256 bit hash of any input.
878
    It also takes in any number of bytes as an input and produces a single
879
    hash for them. A hash is a completely unique output for a single input.
880
    So an input corresponds to one unique hash that can be used to identify
881
    the input exactly.
882
883
    Prior to using the ``keccak256`` hash function, the header must be
884
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
885
    RLP encoding the header converts it into a space-efficient format that
886
    allows for easy transfer of data between nodes. The purpose of RLP is to
887
    encode arbitrarily nested arrays of binary data, and RLP is the primary
888
    encoding method used to serialize objects in Ethereum's execution layer.
889
    The only purpose of RLP is to encode structure; encoding specific data
890
    types (e.g. strings, floats) is left up to higher-order protocols.
891
892
    Parameters
893
    ----------
894
    header :
895
        Header of interest.
896
897
    Returns
898
    -------
899
    hash : `ethereum.crypto.hash.Hash32`
900
        Hash of the header.
901
    """
902
    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:
906
    """
907
    Validates the gas limit for a block.
908
909
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
910
    quotient of the parent block's gas limit and the
911
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
912
    passed through as a parameter is greater than or equal to the *sum* of
913
    the parent's gas and the adjustment delta then the limit for gas is too
914
    high and fails this function's check. Similarly, if the limit is less
915
    than or equal to the *difference* of the parent's gas and the adjustment
916
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
917
    check fails because the gas limit doesn't allow for a sufficient or
918
    reasonable amount of gas to be used on a block.
919
920
    Parameters
921
    ----------
922
    gas_limit :
923
        Gas limit to validate.
924
925
    parent_gas_limit :
926
        Gas limit of the parent block.
927
928
    Returns
929
    -------
930
    check : `bool`
931
        True if gas limit constraints are satisfied, False otherwise.
932
    """
933
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
934
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
935
        return False
936
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
937
        return False
938
    if gas_limit < GAS_LIMIT_MINIMUM:
939
        return False
940
941
    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:
951
    """
952
    Computes difficulty of a block using its header and parent header.
953
954
    The difficulty is determined by the time the block was created after its
955
    parent. The ``offset`` is calculated using the parent block's difficulty,
956
    ``parent_difficulty``, and the timestamp between blocks. This offset is
957
    then added to the parent difficulty and is stored as the ``difficulty``
958
    variable. If the time between the block and its parent is too short, the
959
    offset will result in a positive number thus making the sum of
960
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
961
    avoid mass forking. But, if the time is long enough, then the offset
962
    results in a negative value making the block less difficult than
963
    its parent.
964
965
    The base standard for a block's difficulty is the predefined value
966
    set for the genesis block since it has no parent. So, a block
967
    can't be less difficult than the genesis block, therefore each block's
968
    difficulty is set to the maximum value between the calculated
969
    difficulty and the ``GENESIS_DIFFICULTY``.
970
971
    Parameters
972
    ----------
973
    block_number :
974
        Block number of the block.
975
    block_timestamp :
976
        Timestamp of the block.
977
    parent_timestamp :
978
        Timestamp of the parent block.
979
    parent_difficulty :
980
        difficulty of the parent block.
981
    parent_has_ommers:
982
        does the parent have ommers.
983
984
    Returns
985
    -------
986
    difficulty : `ethereum.base_types.Uint`
987
        Computed difficulty for a block.
988
    """
989
    offset = (
990
        int(parent_difficulty)
991
        // 2048
992
        * max(
993
            (2 if parent_has_ommers else 1)
994
            - int(block_timestamp - parent_timestamp) // 9,
995
            -99,
996
        )
997
    )
998
    difficulty = int(parent_difficulty) + offset
999
    # Historical Note: The difficulty bomb was not present in Ethereum at the
1000
    # start of Frontier, but was added shortly after launch. However since the
1001
    # bomb has no effect prior to block 200000 we pretend it existed from
1002
    # genesis.
1003
    # See https://github.com/ethereum/go-ethereum/pull/1588
1004
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
1005
    if num_bomb_periods >= 0:
1006
        difficulty += 2**num_bomb_periods
1007
1008
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
1009
    # the bomb. This bug does not matter because the difficulty is always much
1010
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
1011
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))