ethereum.muir_glacier.forkethereum.berlin.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

55
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

56
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

57
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

58
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

59
BOMB_DELAY_BLOCKS = 9000000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

63
@dataclass
class BlockChain:

blocks

69
    blocks: List[Block]

state

70
    state: State

chain_id

71
    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:
75
    """
76
    Transforms the state from the previous hard fork (`old`) into the block
77
    chain object for this hard fork and returns it.
78
79
    When forks need to implement an irregular state transition, this function
80
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
81
    an example.
82
83
    Parameters
84
    ----------
85
    old :
86
        Previous block chain object.
87
88
    Returns
89
    -------
90
    new : `BlockChain`
91
        Upgraded block chain object for this hard fork.
92
    """
93
    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]:
97
    """
98
    Obtain the list of hashes of the previous 256 blocks in order of
99
    increasing block number.
100
101
    This function will return less hashes for the first 256 blocks.
102
103
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
104
    therefore this function retrieves them.
105
106
    Parameters
107
    ----------
108
    chain :
109
        History and current state.
110
111
    Returns
112
    -------
113
    recent_block_hashes : `List[Hash32]`
114
        Hashes of the recent 256 blocks in order of increasing block number.
115
    """
116
    recent_blocks = chain.blocks[-255:]
117
    # TODO: This function has not been tested rigorously
118
    if len(recent_blocks) == 0:
119
        return []
120
121
    recent_block_hashes = []
122
123
    for block in recent_blocks:
124
        prev_block_hash = block.header.parent_hash
125
        recent_block_hashes.append(prev_block_hash)
126
127
    # We are computing the hash only for the most recent block and not for
128
    # the rest of the blocks as they have successors which have the hash of
129
    # the current block as parent hash.
130
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
131
    recent_block_hashes.append(most_recent_block_hash)
132
133
    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:
137
    """
138
    Attempts to apply a block to an existing block chain.
139
140
    All parts of the block's contents need to be verified before being added
141
    to the chain. Blocks are verified by ensuring that the contents of the
142
    block make logical sense with the contents of the parent block. The
143
    information in the block's header must also match the corresponding
144
    information in the block.
145
146
    To implement Ethereum, in theory clients are only required to store the
147
    most recent 255 blocks of the chain since as far as execution is
148
    concerned, only those blocks are accessed. Practically, however, clients
149
    should store more blocks to handle reorgs.
150
151
    Parameters
152
    ----------
153
    chain :
154
        History and current state.
155
    block :
156
        Block to apply to `chain`.
157
    """
158
    parent_header = chain.blocks[-1].header
159
    validate_header(block.header, parent_header)
160
    validate_ommers(block.ommers, block.header, chain)
161
    apply_body_output = apply_body(
162
        chain.state,
163
        get_last_256_block_hashes(chain),
164
        block.header.coinbase,
165
        block.header.number,
166
        block.header.gas_limit,
167
        block.header.timestamp,
168
        block.header.difficulty,
169
        block.transactions,
170
        block.ommers,
171
        chain.chain_id,
172
    )
173
    if apply_body_output.block_gas_used != block.header.gas_used:
174
        raise InvalidBlock(
175
            f"{apply_body_output.block_gas_used} != {block.header.gas_used}"
176
        )
177
    if apply_body_output.transactions_root != block.header.transactions_root:
178
        raise InvalidBlock
179
    if apply_body_output.state_root != block.header.state_root:
180
        raise InvalidBlock
181
    if apply_body_output.receipt_root != block.header.receipt_root:
182
        raise InvalidBlock
183
    if apply_body_output.block_logs_bloom != block.header.bloom:
184
        raise InvalidBlock
185
186
    chain.blocks.append(block)
187
    if len(chain.blocks) > 255:
188
        # Real clients have to store more blocks to deal with reorgs, but the
189
        # protocol only requires the last 255
190
        chain.blocks = chain.blocks[-255:]

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:
194
    """
195
    Verifies a block header.
196
197
    In order to consider a block's header valid, the logic for the
198
    quantities in the header should match the logic for the block itself.
199
    For example the header timestamp should be greater than the block's parent
200
    timestamp because the block was created *after* the parent block.
201
    Additionally, the block's number should be directly following the parent
202
    block's number since it is the next block in the sequence.
203
204
    Parameters
205
    ----------
206
    header :
207
        Header to check for correctness.
208
    parent_header :
209
        Parent Header of the header to check for correctness
210
    """
211
    parent_has_ommers = parent_header.ommers_hash != EMPTY_OMMER_HASH
212
    if header.timestamp <= parent_header.timestamp:
213
        raise InvalidBlock
214
    if header.number != parent_header.number + Uint(1):
215
        raise InvalidBlock
216
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
217
        raise InvalidBlock
218
    if len(header.extra_data) > 32:
219
        raise InvalidBlock
220
221
    block_difficulty = calculate_block_difficulty(
222
        header.number,
223
        header.timestamp,
224
        parent_header.timestamp,
225
        parent_header.difficulty,
226
        parent_has_ommers,
227
    )
228
    if header.difficulty != block_difficulty:
229
        raise InvalidBlock
230
231
    block_parent_hash = keccak256(rlp.encode(parent_header))
232
    if header.parent_hash != block_parent_hash:
233
        raise InvalidBlock
234
235
    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:
239
    """
240
    Generate rlp hash of the header which is to be used for Proof-of-Work
241
    verification.
242
243
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
244
    while calculating this hash.
245
246
    A particular PoW is valid for a single hash, that hash is computed by
247
    this function. The `nonce` and `mix_digest` are omitted from this hash
248
    because they are being changed by miners in their search for a sufficient
249
    proof-of-work.
250
251
    Parameters
252
    ----------
253
    header :
254
        The header object for which the hash is to be generated.
255
256
    Returns
257
    -------
258
    hash : `Hash32`
259
        The PoW valid rlp hash of the passed in header.
260
    """
261
    header_data_without_pow_artefacts = (
262
        header.parent_hash,
263
        header.ommers_hash,
264
        header.coinbase,
265
        header.state_root,
266
        header.transactions_root,
267
        header.receipt_root,
268
        header.bloom,
269
        header.difficulty,
270
        header.number,
271
        header.gas_limit,
272
        header.gas_used,
273
        header.timestamp,
274
        header.extra_data,
275
    )
276
277
    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:
281
    """
282
    Validates the Proof of Work constraints.
283
284
    In order to verify that a miner's proof-of-work is valid for a block, a
285
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
286
    hash function. The mix digest is a hash of the header and the nonce that
287
    is passed through and it confirms whether or not proof-of-work was done
288
    on the correct block. The result is the actual hash value of the block.
289
290
    Parameters
291
    ----------
292
    header :
293
        Header of interest.
294
    """
295
    header_hash = generate_header_hash_for_pow(header)
296
    # TODO: Memoize this somewhere and read from that data instead of
297
    # calculating cache for every block validation.
298
    cache = generate_cache(header.number)
299
    mix_digest, result = hashimoto_light(
300
        header_hash, header.nonce, cache, dataset_size(header.number)
301
    )
302
    if mix_digest != header.mix_digest:
303
        raise InvalidBlock
304
305
    limit = Uint(U256.MAX_VALUE) + Uint(1)
306
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
307
        raise InvalidBlock

check_transaction

Check if the transaction is includable in the block.

Parameters

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

Returns

sender_address : The sender of the transaction.

Raises

InvalidBlock : If the transaction is not includable.

def check_transaction(tx: Transaction, ​​gas_available: Uint, ​​chain_id: U64) -> Address:
315
    """
316
    Check if the transaction is includable in the block.
317
318
    Parameters
319
    ----------
320
    tx :
321
        The transaction.
322
    gas_available :
323
        The gas remaining in the block.
324
    chain_id :
325
        The ID of the current chain.
326
327
    Returns
328
    -------
329
    sender_address :
330
        The sender of the transaction.
331
332
    Raises
333
    ------
334
    InvalidBlock :
335
        If the transaction is not includable.
336
    """
337
    if tx.gas > gas_available:
338
        raise InvalidBlock
339
    sender_address = recover_sender(chain_id, tx)
340
341
    return sender_address

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, ...]) -> ReceiptUnion[Bytes, Receipt]:
350
    """
351
    Make the receipt for a transaction that was executed.
352
353
    Parameters
354
    ----------
355
    tx :
356
        The executed transaction.
357
    error :
358
        Error in the top level frame of the transaction, if any.
359
    cumulative_gas_used :
360
        The total gas used so far in the block after the transaction was
361
        executed.
362
    logs :
363
        The logs produced by the transaction.
364
365
    Returns
366
    -------
367
    receipt :
368
        The receipt for the transaction.
369
    """
370
    receipt = Receipt(
371
        succeeded=error is None,
372
        cumulative_gas_used=cumulative_gas_used,
373
        bloom=logs_bloom(logs),
374
        logs=logs,
375
    )
376
373
    return receipt
377
    if isinstance(tx, AccessListTransaction):
378
        return b"\x01" + rlp.encode(receipt)
379
    else:
380
        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.

383
@dataclass
class ApplyBodyOutput:

block_gas_used

403
    block_gas_used: Uint

transactions_root

404
    transactions_root: Root

receipt_root

405
    receipt_root: Root

block_logs_bloom

406
    block_logs_bloom: Bloom

state_root

407
    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. 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, ​​block_gas_limit: Uint, ​​block_time: U256, ​​block_difficulty: Uint, ​​transactions: Tuple[TransactionUnion[LegacyTransaction, Bytes], ...], ​​ommers: Tuple[Header, ...], ​​chain_id: U64) -> ApplyBodyOutput:
422
    """
423
    Executes a block.
424
425
    Many of the contents of a block are stored in data structures called
426
    tries. There is a transactions trie which is similar to a ledger of the
427
    transactions stored in the current block. There is also a receipts trie
428
    which stores the results of executing a transaction, like the post state
429
    and gas used. This function creates and executes the block that is to be
430
    added to the chain.
431
432
    Parameters
433
    ----------
434
    state :
435
        Current account state.
436
    block_hashes :
437
        List of hashes of the previous 256 blocks in the order of
438
        increasing block number.
439
    coinbase :
440
        Address of account which receives block reward and transaction fees.
441
    block_number :
442
        Position of the block within the chain.
443
    block_gas_limit :
444
        Initial amount of gas available for execution in this block.
445
    block_time :
446
        Time the block was produced, measured in seconds since the epoch.
447
    block_difficulty :
448
        Difficulty of the block.
449
    transactions :
450
        Transactions included in the block.
451
    ommers :
452
        Headers of ancestor blocks which are not direct parents (formerly
453
        uncles.)
454
    chain_id :
455
        ID of the executing chain.
456
457
    Returns
458
    -------
459
    apply_body_output : `ApplyBodyOutput`
460
        Output of applying the block body to the state.
461
    """
462
    gas_available = block_gas_limit
456
    transactions_trie: Trie[Bytes, Optional[Transaction]] = Trie(
457
        secured=False, default=None
458
    )
459
    receipts_trie: Trie[Bytes, Optional[Receipt]] = Trie(
463
    transactions_trie: Trie[
464
        Bytes, Optional[Union[Bytes, LegacyTransaction]]
465
    ] = Trie(secured=False, default=None)
466
    receipts_trie: Trie[Bytes, Optional[Union[Bytes, Receipt]]] = Trie(
467
        secured=False, default=None
468
    )
469
    block_logs: Tuple[Log, ...] = ()
470
464
    for i, tx in enumerate(transactions):
465
        trie_set(transactions_trie, rlp.encode(Uint(i)), tx)
471
    for i, tx in enumerate(map(decode_transaction, transactions)):
472
        trie_set(
473
            transactions_trie, rlp.encode(Uint(i)), encode_transaction(tx)
474
        )
475
476
        sender_address = check_transaction(tx, gas_available, chain_id)
477
478
        env = vm.Environment(
479
            caller=sender_address,
480
            origin=sender_address,
481
            block_hashes=block_hashes,
482
            coinbase=coinbase,
483
            number=block_number,
484
            gas_limit=block_gas_limit,
485
            gas_price=tx.gas_price,
486
            time=block_time,
487
            difficulty=block_difficulty,
488
            state=state,
489
            chain_id=chain_id,
490
            traces=[],
491
        )
492
493
        gas_used, logs, error = process_transaction(env, tx)
494
        gas_available -= gas_used
495
496
        receipt = make_receipt(
497
            tx, error, (block_gas_limit - gas_available), logs
498
        )
499
500
        trie_set(
501
            receipts_trie,
502
            rlp.encode(Uint(i)),
503
            receipt,
504
        )
505
506
        block_logs += logs
507
508
    pay_rewards(state, block_number, coinbase, ommers)
509
510
    block_gas_used = block_gas_limit - gas_available
511
512
    block_logs_bloom = logs_bloom(block_logs)
513
514
    return ApplyBodyOutput(
515
        block_gas_used,
516
        root(transactions_trie),
517
        root(receipts_trie),
518
        block_logs_bloom,
519
        state_root(state),
520
    )

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:
526
    """
527
    Validates the ommers mentioned in the block.
528
529
    An ommer block is a block that wasn't canonically added to the
530
    blockchain because it wasn't validated as fast as the canonical block
531
    but was mined at the same time.
532
533
    To be considered valid, the ommers must adhere to the rules defined in
534
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
535
    there cannot be duplicate ommers in a block. Many of the other ommer
536
    constraints are listed in the in-line comments of this function.
537
538
    Parameters
539
    ----------
540
    ommers :
541
        List of ommers mentioned in the current block.
542
    block_header:
543
        The header of current block.
544
    chain :
545
        History and current state.
546
    """
547
    block_hash = rlp.rlp_hash(block_header)
548
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
549
        raise InvalidBlock
550
551
    if len(ommers) == 0:
552
        # Nothing to validate
553
        return
554
555
    # Check that each ommer satisfies the constraints of a header
556
    for ommer in ommers:
557
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
558
            raise InvalidBlock
559
        ommer_parent_header = chain.blocks[
560
            -(block_header.number - ommer.number) - 1
561
        ].header
562
        validate_header(ommer, ommer_parent_header)
563
    if len(ommers) > 2:
564
        raise InvalidBlock
565
566
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
567
    if len(ommers_hashes) != len(set(ommers_hashes)):
568
        raise InvalidBlock
569
570
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
571
    recent_canonical_block_hashes = {
572
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
573
    }
574
    recent_ommers_hashes: Set[Hash32] = set()
575
    for block in recent_canonical_blocks:
576
        recent_ommers_hashes = recent_ommers_hashes.union(
577
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
578
        )
579
580
    for ommer_index, ommer in enumerate(ommers):
581
        ommer_hash = ommers_hashes[ommer_index]
582
        if ommer_hash == block_hash:
583
            raise InvalidBlock
584
        if ommer_hash in recent_canonical_block_hashes:
585
            raise InvalidBlock
586
        if ommer_hash in recent_ommers_hashes:
587
            raise InvalidBlock
588
589
        # Ommer age with respect to the current block. For example, an age of
590
        # 1 indicates that the ommer is a sibling of previous block.
591
        ommer_age = block_header.number - ommer.number
592
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
593
            raise InvalidBlock
594
        if ommer.parent_hash not in recent_canonical_block_hashes:
595
            raise InvalidBlock
596
        if ommer.parent_hash == block_header.parent_hash:
597
            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:
606
    """
607
    Pay rewards to the block miner as well as the ommers miners.
608
609
    The miner of the canonical block is rewarded with the predetermined
610
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
611
    number of ommer blocks that were mined around the same time, and included
612
    in the canonical block's header. An ommer block is a block that wasn't
613
    added to the canonical blockchain because it wasn't validated as fast as
614
    the accepted block but was mined at the same time. Although not all blocks
615
    that are mined are added to the canonical chain, miners are still paid a
616
    reward for their efforts. This reward is called an ommer reward and is
617
    calculated based on the number associated with the ommer block that they
618
    mined.
619
620
    Parameters
621
    ----------
622
    state :
623
        Current account state.
624
    block_number :
625
        Position of the block within the chain.
626
    coinbase :
627
        Address of account which receives block reward and transaction fees.
628
    ommers :
629
        List of ommers mentioned in the current block.
630
    """
631
    ommer_count = U256(len(ommers))
632
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
633
    create_ether(state, coinbase, miner_reward)
634
635
    for ommer in ommers:
636
        # Ommer age with respect to the current block.
637
        ommer_age = U256(block_number - ommer.number)
638
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
639
        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.muir_glacier.vm.Environmentethereum.berlin.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...], Optional[Exception]]:
645
    """
646
    Execute a transaction against the provided environment.
647
648
    This function processes the actions needed to execute a transaction.
649
    It decrements the sender's account after calculating the gas fee and
650
    refunds them the proper amount after execution. Calling contracts,
651
    deploying code, and incrementing nonces are all examples of actions that
652
    happen within this function or from a call made within this function.
653
654
    Accounts that are marked for deletion are processed and destroyed after
655
    execution.
656
657
    Parameters
658
    ----------
659
    env :
660
        Environment for the Ethereum Virtual Machine.
661
    tx :
662
        Transaction to execute.
663
664
    Returns
665
    -------
666
    gas_left : `ethereum.base_types.U256`
667
        Remaining gas after execution.
668
    logs : `Tuple[ethereum.blocks.Log, ...]`
669
        Logs generated during execution.
670
    """
671
    if not validate_transaction(tx):
672
        raise InvalidBlock
673
674
    sender = env.origin
675
    sender_account = get_account(env.state, sender)
676
    gas_fee = tx.gas * tx.gas_price
677
    if sender_account.nonce != tx.nonce:
678
        raise InvalidBlock
679
    if Uint(sender_account.balance) < gas_fee + Uint(tx.value):
680
        raise InvalidBlock
681
    if sender_account.code != bytearray():
682
        raise InvalidSenderError("not EOA")
683
684
    gas = tx.gas - calculate_intrinsic_cost(tx)
685
    increment_nonce(env.state, sender)
686
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
687
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
688
689
    preaccessed_addresses = set()
690
    preaccessed_storage_keys = set()
691
    if isinstance(tx, AccessListTransaction):
692
        for address, keys in tx.access_list:
693
            preaccessed_addresses.add(address)
694
            for key in keys:
695
                preaccessed_storage_keys.add((address, key))
696
697
    message = prepare_message(
698
        sender,
699
        tx.to,
700
        tx.value,
701
        tx.data,
702
        gas,
703
        env,
704
        preaccessed_addresses=frozenset(preaccessed_addresses),
705
        preaccessed_storage_keys=frozenset(preaccessed_storage_keys),
706
    )
707
708
    output = process_message_call(message, env)
709
710
    gas_used = tx.gas - output.gas_left
711
    gas_refund = min(gas_used // Uint(2), Uint(output.refund_counter))
712
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
713
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
714
    total_gas_used = gas_used - gas_refund
715
716
    # refund gas
717
    sender_balance_after_refund = get_account(
718
        env.state, sender
719
    ).balance + U256(gas_refund_amount)
720
    set_account_balance(env.state, sender, sender_balance_after_refund)
721
722
    # transfer miner fees
723
    coinbase_balance_after_mining_fee = get_account(
724
        env.state, env.coinbase
725
    ).balance + U256(transaction_fee)
726
    if coinbase_balance_after_mining_fee != 0:
727
        set_account_balance(
728
            env.state, env.coinbase, coinbase_balance_after_mining_fee
729
        )
730
    elif account_exists_and_is_empty(env.state, env.coinbase):
731
        destroy_account(env.state, env.coinbase)
732
733
    for address in output.accounts_to_delete:
734
        destroy_account(env.state, address)
735
736
    for address in output.touched_accounts:
737
        if account_exists_and_is_empty(env.state, address):
738
            destroy_account(env.state, address)
739
740
    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:
744
    """
745
    Computes the hash of a block header.
746
747
    The header hash of a block is the canonical hash that is used to refer
748
    to a specific block and completely distinguishes a block from another.
749
750
    ``keccak256`` is a function that produces a 256 bit hash of any input.
751
    It also takes in any number of bytes as an input and produces a single
752
    hash for them. A hash is a completely unique output for a single input.
753
    So an input corresponds to one unique hash that can be used to identify
754
    the input exactly.
755
756
    Prior to using the ``keccak256`` hash function, the header must be
757
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
758
    RLP encoding the header converts it into a space-efficient format that
759
    allows for easy transfer of data between nodes. The purpose of RLP is to
760
    encode arbitrarily nested arrays of binary data, and RLP is the primary
761
    encoding method used to serialize objects in Ethereum's execution layer.
762
    The only purpose of RLP is to encode structure; encoding specific data
763
    types (e.g. strings, floats) is left up to higher-order protocols.
764
765
    Parameters
766
    ----------
767
    header :
768
        Header of interest.
769
770
    Returns
771
    -------
772
    hash : `ethereum.crypto.hash.Hash32`
773
        Hash of the header.
774
    """
775
    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:
779
    """
780
    Validates the gas limit for a block.
781
782
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
783
    quotient of the parent block's gas limit and the
784
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
785
    passed through as a parameter is greater than or equal to the *sum* of
786
    the parent's gas and the adjustment delta then the limit for gas is too
787
    high and fails this function's check. Similarly, if the limit is less
788
    than or equal to the *difference* of the parent's gas and the adjustment
789
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
790
    check fails because the gas limit doesn't allow for a sufficient or
791
    reasonable amount of gas to be used on a block.
792
793
    Parameters
794
    ----------
795
    gas_limit :
796
        Gas limit to validate.
797
798
    parent_gas_limit :
799
        Gas limit of the parent block.
800
801
    Returns
802
    -------
803
    check : `bool`
804
        True if gas limit constraints are satisfied, False otherwise.
805
    """
806
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
807
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
808
        return False
809
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
810
        return False
811
    if gas_limit < GAS_LIMIT_MINIMUM:
812
        return False
813
814
    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:
824
    """
825
    Computes difficulty of a block using its header and parent header.
826
827
    The difficulty is determined by the time the block was created after its
828
    parent. The ``offset`` is calculated using the parent block's difficulty,
829
    ``parent_difficulty``, and the timestamp between blocks. This offset is
830
    then added to the parent difficulty and is stored as the ``difficulty``
831
    variable. If the time between the block and its parent is too short, the
832
    offset will result in a positive number thus making the sum of
833
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
834
    avoid mass forking. But, if the time is long enough, then the offset
835
    results in a negative value making the block less difficult than
836
    its parent.
837
838
    The base standard for a block's difficulty is the predefined value
839
    set for the genesis block since it has no parent. So, a block
840
    can't be less difficult than the genesis block, therefore each block's
841
    difficulty is set to the maximum value between the calculated
842
    difficulty and the ``GENESIS_DIFFICULTY``.
843
844
    Parameters
845
    ----------
846
    block_number :
847
        Block number of the block.
848
    block_timestamp :
849
        Timestamp of the block.
850
    parent_timestamp :
851
        Timestamp of the parent block.
852
    parent_difficulty :
853
        difficulty of the parent block.
854
    parent_has_ommers:
855
        does the parent have ommers.
856
857
    Returns
858
    -------
859
    difficulty : `ethereum.base_types.Uint`
860
        Computed difficulty for a block.
861
    """
862
    offset = (
863
        int(parent_difficulty)
864
        // 2048
865
        * max(
866
            (2 if parent_has_ommers else 1)
867
            - int(block_timestamp - parent_timestamp) // 9,
868
            -99,
869
        )
870
    )
871
    difficulty = int(parent_difficulty) + offset
872
    # Historical Note: The difficulty bomb was not present in Ethereum at the
873
    # start of Frontier, but was added shortly after launch. However since the
874
    # bomb has no effect prior to block 200000 we pretend it existed from
875
    # genesis.
876
    # See https://github.com/ethereum/go-ethereum/pull/1588
877
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
878
    if num_bomb_periods >= 0:
879
        difficulty += 2**num_bomb_periods
880
881
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
882
    # the bomb. This bug does not matter because the difficulty is always much
883
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
884
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))