ethereum.berlin.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

58
GAS_LIMIT_ADJUSTMENT_FACTOR = 1024

GAS_LIMIT_MINIMUM

59
GAS_LIMIT_MINIMUM = 5000

MINIMUM_DIFFICULTY

60
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

61
MAX_OMMER_DEPTH = 6

BOMB_DELAY_BLOCKS

62
BOMB_DELAY_BLOCKS = 9000000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

66
@dataclass
class BlockChain:

blocks

72
    blocks: List[Block]

state

73
    state: State

chain_id

74
    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:
78
    """
79
    Transforms the state from the previous hard fork (`old`) into the block
80
    chain object for this hard fork and returns it.
81
82
    When forks need to implement an irregular state transition, this function
83
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
84
    an example.
85
86
    Parameters
87
    ----------
88
    old :
89
        Previous block chain object.
90
91
    Returns
92
    -------
93
    new : `BlockChain`
94
        Upgraded block chain object for this hard fork.
95
    """
96
    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]:
100
    """
101
    Obtain the list of hashes of the previous 256 blocks in order of
102
    increasing block number.
103
104
    This function will return less hashes for the first 256 blocks.
105
106
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
107
    therefore this function retrieves them.
108
109
    Parameters
110
    ----------
111
    chain :
112
        History and current state.
113
114
    Returns
115
    -------
116
    recent_block_hashes : `List[Hash32]`
117
        Hashes of the recent 256 blocks in order of increasing block number.
118
    """
119
    recent_blocks = chain.blocks[-255:]
120
    # TODO: This function has not been tested rigorously
121
    if len(recent_blocks) == 0:
122
        return []
123
124
    recent_block_hashes = []
125
126
    for block in recent_blocks:
127
        prev_block_hash = block.header.parent_hash
128
        recent_block_hashes.append(prev_block_hash)
129
130
    # We are computing the hash only for the most recent block and not for
131
    # the rest of the blocks as they have successors which have the hash of
132
    # the current block as parent hash.
133
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
134
    recent_block_hashes.append(most_recent_block_hash)
135
136
    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:
140
    """
141
    Attempts to apply a block to an existing block chain.
142
143
    All parts of the block's contents need to be verified before being added
144
    to the chain. Blocks are verified by ensuring that the contents of the
145
    block make logical sense with the contents of the parent block. The
146
    information in the block's header must also match the corresponding
147
    information in the block.
148
149
    To implement Ethereum, in theory clients are only required to store the
150
    most recent 255 blocks of the chain since as far as execution is
151
    concerned, only those blocks are accessed. Practically, however, clients
152
    should store more blocks to handle reorgs.
153
154
    Parameters
155
    ----------
156
    chain :
157
        History and current state.
158
    block :
159
        Block to apply to `chain`.
160
    """
161
    parent_header = chain.blocks[-1].header
162
    validate_header(block.header, parent_header)
163
    validate_ommers(block.ommers, block.header, chain)
164
    apply_body_output = apply_body(
165
        chain.state,
166
        get_last_256_block_hashes(chain),
167
        block.header.coinbase,
168
        block.header.number,
169
        block.header.gas_limit,
170
        block.header.timestamp,
171
        block.header.difficulty,
172
        block.transactions,
173
        block.ommers,
174
        chain.chain_id,
175
    )
176
    if apply_body_output.block_gas_used != block.header.gas_used:
177
        raise InvalidBlock
178
    if apply_body_output.transactions_root != block.header.transactions_root:
179
        raise InvalidBlock
180
    if apply_body_output.state_root != block.header.state_root:
181
        raise InvalidBlock
182
    if apply_body_output.receipt_root != block.header.receipt_root:
183
        raise InvalidBlock
184
    if apply_body_output.block_logs_bloom != block.header.bloom:
185
        raise InvalidBlock
186
187
    chain.blocks.append(block)
188
    if len(chain.blocks) > 255:
189
        # Real clients have to store more blocks to deal with reorgs, but the
190
        # protocol only requires the last 255
191
        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:
195
    """
196
    Verifies a block header.
197
198
    In order to consider a block's header valid, the logic for the
199
    quantities in the header should match the logic for the block itself.
200
    For example the header timestamp should be greater than the block's parent
201
    timestamp because the block was created *after* the parent block.
202
    Additionally, the block's number should be directly following the parent
203
    block's number since it is the next block in the sequence.
204
205
    Parameters
206
    ----------
207
    header :
208
        Header to check for correctness.
209
    parent_header :
210
        Parent Header of the header to check for correctness
211
    """
212
    parent_has_ommers = parent_header.ommers_hash != EMPTY_OMMER_HASH
213
    if header.timestamp <= parent_header.timestamp:
214
        raise InvalidBlock
215
    if header.number != parent_header.number + 1:
216
        raise InvalidBlock
217
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
218
        raise InvalidBlock
219
    if len(header.extra_data) > 32:
220
        raise InvalidBlock
221
222
    block_difficulty = calculate_block_difficulty(
223
        header.number,
224
        header.timestamp,
225
        parent_header.timestamp,
226
        parent_header.difficulty,
227
        parent_has_ommers,
228
    )
229
    if header.difficulty != block_difficulty:
230
        raise InvalidBlock
231
232
    block_parent_hash = keccak256(rlp.encode(parent_header))
233
    if header.parent_hash != block_parent_hash:
234
        raise InvalidBlock
235
236
    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:
240
    """
241
    Generate rlp hash of the header which is to be used for Proof-of-Work
242
    verification.
243
244
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
245
    while calculating this hash.
246
247
    A particular PoW is valid for a single hash, that hash is computed by
248
    this function. The `nonce` and `mix_digest` are omitted from this hash
249
    because they are being changed by miners in their search for a sufficient
250
    proof-of-work.
251
252
    Parameters
253
    ----------
254
    header :
255
        The header object for which the hash is to be generated.
256
257
    Returns
258
    -------
259
    hash : `Hash32`
260
        The PoW valid rlp hash of the passed in header.
261
    """
262
    header_data_without_pow_artefacts = (
263
        header.parent_hash,
264
        header.ommers_hash,
265
        header.coinbase,
266
        header.state_root,
267
        header.transactions_root,
268
        header.receipt_root,
269
        header.bloom,
270
        header.difficulty,
271
        header.number,
272
        header.gas_limit,
273
        header.gas_used,
274
        header.timestamp,
275
        header.extra_data,
276
    )
277
278
    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:
282
    """
283
    Validates the Proof of Work constraints.
284
285
    In order to verify that a miner's proof-of-work is valid for a block, a
286
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
287
    hash function. The mix digest is a hash of the header and the nonce that
288
    is passed through and it confirms whether or not proof-of-work was done
289
    on the correct block. The result is the actual hash value of the block.
290
291
    Parameters
292
    ----------
293
    header :
294
        Header of interest.
295
    """
296
    header_hash = generate_header_hash_for_pow(header)
297
    # TODO: Memoize this somewhere and read from that data instead of
298
    # calculating cache for every block validation.
299
    cache = generate_cache(header.number)
300
    mix_digest, result = hashimoto_light(
301
        header_hash, header.nonce, cache, dataset_size(header.number)
302
    )
303
    if mix_digest != header.mix_digest:
304
        raise InvalidBlock
305
    if Uint.from_be_bytes(result) > (U256_CEIL_VALUE // header.difficulty):
306
        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:
314
    """
315
    Check if the transaction is includable in the block.
316
317
    Parameters
318
    ----------
319
    tx :
320
        The transaction.
321
    gas_available :
322
        The gas remaining in the block.
323
    chain_id :
324
        The ID of the current chain.
325
326
    Returns
327
    -------
328
    sender_address :
329
        The sender of the transaction.
330
331
    Raises
332
    ------
333
    InvalidBlock :
334
        If the transaction is not includable.
335
    """
336
    if tx.gas > gas_available:
337
        raise InvalidBlock
338
    sender_address = recover_sender(chain_id, tx)
339
340
    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, ...]) -> Union[Bytes, Receipt]:
349
    """
350
    Make the receipt for a transaction that was executed.
351
352
    Parameters
353
    ----------
354
    tx :
355
        The executed transaction.
356
    error :
357
        Error in the top level frame of the transaction, if any.
358
    cumulative_gas_used :
359
        The total gas used so far in the block after the transaction was
360
        executed.
361
    logs :
362
        The logs produced by the transaction.
363
364
    Returns
365
    -------
366
    receipt :
367
        The receipt for the transaction.
368
    """
369
    receipt = Receipt(
370
        succeeded=error is None,
371
        cumulative_gas_used=cumulative_gas_used,
372
        bloom=logs_bloom(logs),
373
        logs=logs,
374
    )
375
376
    if isinstance(tx, AccessListTransaction):
377
        return b"\x01" + rlp.encode(receipt)
378
    else:
379
        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.

382
@dataclass
class ApplyBodyOutput:

block_gas_used

402
    block_gas_used: Uint

transactions_root

403
    transactions_root: Root

receipt_root

404
    receipt_root: Root

block_logs_bloom

405
    block_logs_bloom: Bloom

state_root

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

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:
525
    """
526
    Validates the ommers mentioned in the block.
527
528
    An ommer block is a block that wasn't canonically added to the
529
    blockchain because it wasn't validated as fast as the canonical block
530
    but was mined at the same time.
531
532
    To be considered valid, the ommers must adhere to the rules defined in
533
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
534
    there cannot be duplicate ommers in a block. Many of the other ommer
535
    constraints are listed in the in-line comments of this function.
536
537
    Parameters
538
    ----------
539
    ommers :
540
        List of ommers mentioned in the current block.
541
    block_header:
542
        The header of current block.
543
    chain :
544
        History and current state.
545
    """
546
    block_hash = rlp.rlp_hash(block_header)
547
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
548
        raise InvalidBlock
549
550
    if len(ommers) == 0:
551
        # Nothing to validate
552
        return
553
554
    # Check that each ommer satisfies the constraints of a header
555
    for ommer in ommers:
556
        if 1 > ommer.number or ommer.number >= block_header.number:
557
            raise InvalidBlock
558
        ommer_parent_header = chain.blocks[
559
            -(block_header.number - ommer.number) - 1
560
        ].header
561
        validate_header(ommer, ommer_parent_header)
562
    if len(ommers) > 2:
563
        raise InvalidBlock
564
565
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
566
    if len(ommers_hashes) != len(set(ommers_hashes)):
567
        raise InvalidBlock
568
569
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + 1) :]
570
    recent_canonical_block_hashes = {
571
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
572
    }
573
    recent_ommers_hashes: Set[Hash32] = set()
574
    for block in recent_canonical_blocks:
575
        recent_ommers_hashes = recent_ommers_hashes.union(
576
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
577
        )
578
579
    for ommer_index, ommer in enumerate(ommers):
580
        ommer_hash = ommers_hashes[ommer_index]
581
        if ommer_hash == block_hash:
582
            raise InvalidBlock
583
        if ommer_hash in recent_canonical_block_hashes:
584
            raise InvalidBlock
585
        if ommer_hash in recent_ommers_hashes:
586
            raise InvalidBlock
587
588
        # Ommer age with respect to the current block. For example, an age of
589
        # 1 indicates that the ommer is a sibling of previous block.
590
        ommer_age = block_header.number - ommer.number
591
        if 1 > ommer_age or ommer_age > MAX_OMMER_DEPTH:
592
            raise InvalidBlock
593
        if ommer.parent_hash not in recent_canonical_block_hashes:
594
            raise InvalidBlock
595
        if ommer.parent_hash == block_header.parent_hash:
596
            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:
605
    """
606
    Pay rewards to the block miner as well as the ommers miners.
607
608
    The miner of the canonical block is rewarded with the predetermined
609
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
610
    number of ommer blocks that were mined around the same time, and included
611
    in the canonical block's header. An ommer block is a block that wasn't
612
    added to the canonical blockchain because it wasn't validated as fast as
613
    the accepted block but was mined at the same time. Although not all blocks
614
    that are mined are added to the canonical chain, miners are still paid a
615
    reward for their efforts. This reward is called an ommer reward and is
616
    calculated based on the number associated with the ommer block that they
617
    mined.
618
619
    Parameters
620
    ----------
621
    state :
622
        Current account state.
623
    block_number :
624
        Position of the block within the chain.
625
    coinbase :
626
        Address of account which receives block reward and transaction fees.
627
    ommers :
628
        List of ommers mentioned in the current block.
629
    """
630
    miner_reward = BLOCK_REWARD + (len(ommers) * (BLOCK_REWARD // 32))
631
    create_ether(state, coinbase, miner_reward)
632
633
    for ommer in ommers:
634
        # Ommer age with respect to the current block.
635
        ommer_age = U256(block_number - ommer.number)
636
        ommer_miner_reward = ((8 - ommer_age) * BLOCK_REWARD) // 8
637
        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.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...], Optional[Exception]]:
643
    """
644
    Execute a transaction against the provided environment.
645
646
    This function processes the actions needed to execute a transaction.
647
    It decrements the sender's account after calculating the gas fee and
648
    refunds them the proper amount after execution. Calling contracts,
649
    deploying code, and incrementing nonces are all examples of actions that
650
    happen within this function or from a call made within this function.
651
652
    Accounts that are marked for deletion are processed and destroyed after
653
    execution.
654
655
    Parameters
656
    ----------
657
    env :
658
        Environment for the Ethereum Virtual Machine.
659
    tx :
660
        Transaction to execute.
661
662
    Returns
663
    -------
664
    gas_left : `ethereum.base_types.U256`
665
        Remaining gas after execution.
666
    logs : `Tuple[ethereum.blocks.Log, ...]`
667
        Logs generated during execution.
668
    """
669
    if not validate_transaction(tx):
670
        raise InvalidBlock
671
672
    sender = env.origin
673
    sender_account = get_account(env.state, sender)
674
    gas_fee = tx.gas * tx.gas_price
675
    if sender_account.nonce != tx.nonce:
676
        raise InvalidBlock
677
    if sender_account.balance < gas_fee + tx.value:
678
        raise InvalidBlock
679
    if sender_account.code != bytearray():
680
        raise InvalidBlock
681
682
    gas = tx.gas - calculate_intrinsic_cost(tx)
683
    increment_nonce(env.state, sender)
684
    sender_balance_after_gas_fee = sender_account.balance - gas_fee
685
    set_account_balance(env.state, sender, sender_balance_after_gas_fee)
686
687
    preaccessed_addresses = set()
688
    preaccessed_storage_keys = set()
689
    if isinstance(tx, AccessListTransaction):
690
        for address, keys in tx.access_list:
691
            preaccessed_addresses.add(address)
692
            for key in keys:
693
                preaccessed_storage_keys.add((address, key))
694
695
    message = prepare_message(
696
        sender,
697
        tx.to,
698
        tx.value,
699
        tx.data,
700
        gas,
701
        env,
702
        preaccessed_addresses=frozenset(preaccessed_addresses),
703
        preaccessed_storage_keys=frozenset(preaccessed_storage_keys),
704
    )
705
706
    output = process_message_call(message, env)
707
708
    gas_used = tx.gas - output.gas_left
709
    gas_refund = min(gas_used // 2, output.refund_counter)
710
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
711
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
712
    total_gas_used = gas_used - gas_refund
713
714
    # refund gas
715
    sender_balance_after_refund = (
716
        get_account(env.state, sender).balance + gas_refund_amount
717
    )
718
    set_account_balance(env.state, sender, sender_balance_after_refund)
719
720
    # transfer miner fees
721
    coinbase_balance_after_mining_fee = (
722
        get_account(env.state, env.coinbase).balance + transaction_fee
723
    )
724
    if coinbase_balance_after_mining_fee != 0:
725
        set_account_balance(
726
            env.state, env.coinbase, coinbase_balance_after_mining_fee
727
        )
728
    elif account_exists_and_is_empty(env.state, env.coinbase):
729
        destroy_account(env.state, env.coinbase)
730
731
    for address in output.accounts_to_delete:
732
        destroy_account(env.state, address)
733
734
    for address in output.touched_accounts:
735
        if account_exists_and_is_empty(env.state, address):
736
            destroy_account(env.state, address)
737
738
    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:
742
    """
743
    Verifies a transaction.
744
745
    The gas in a transaction gets used to pay for the intrinsic cost of
746
    operations, therefore if there is insufficient gas then it would not
747
    be possible to execute a transaction and it will be declared invalid.
748
749
    Additionally, the nonce of a transaction must not equal or exceed the
750
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
751
    In practice, defining the limit as ``2**64-1`` has no impact because
752
    sending ``2**64-1`` transactions is improbable. It's not strictly
753
    impossible though, ``2**64-1`` transactions is the entire capacity of the
754
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
755
756
    Parameters
757
    ----------
758
    tx :
759
        Transaction to validate.
760
761
    Returns
762
    -------
763
    verified : `bool`
764
        True if the transaction can be executed, or False otherwise.
765
    """
766
    return calculate_intrinsic_cost(tx) <= tx.gas and tx.nonce < 2**64 - 1

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:
770
    """
771
    Calculates the gas that is charged before execution is started.
772
773
    The intrinsic cost of the transaction is charged before execution has
774
    begun. Functions/operations in the EVM cost money to execute so this
775
    intrinsic cost is for the operations that need to be paid for as part of
776
    the transaction. Data transfer, for example, is part of this intrinsic
777
    cost. It costs ether to send data over the wire and that ether is
778
    accounted for in the intrinsic cost calculated in this function. This
779
    intrinsic cost must be calculated and paid for before execution in order
780
    for all operations to be implemented.
781
782
    Parameters
783
    ----------
784
    tx :
785
        Transaction to compute the intrinsic cost of.
786
787
    Returns
788
    -------
789
    verified : `ethereum.base_types.Uint`
790
        The intrinsic cost of the transaction.
791
    """
792
    data_cost = 0
793
794
    for byte in tx.data:
795
        if byte == 0:
796
            data_cost += TX_DATA_COST_PER_ZERO
797
        else:
798
            data_cost += TX_DATA_COST_PER_NON_ZERO
799
800
    if tx.to == Bytes0(b""):
801
        create_cost = TX_CREATE_COST
802
    else:
803
        create_cost = 0
804
805
    access_list_cost = 0
806
    if isinstance(tx, AccessListTransaction):
807
        for _address, keys in tx.access_list:
808
            access_list_cost += TX_ACCESS_LIST_ADDRESS_COST
809
            access_list_cost += len(keys) * TX_ACCESS_LIST_STORAGE_KEY_COST
810
811
    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:
815
    """
816
    Extracts the sender address from a transaction.
817
818
    The v, r, and s values are the three parts that make up the signature
819
    of a transaction. In order to recover the sender of a transaction the two
820
    components needed are the signature (``v``, ``r``, and ``s``) and the
821
    signing hash of the transaction. The sender's public key can be obtained
822
    with these two values and therefore the sender address can be retrieved.
823
824
    Parameters
825
    ----------
826
    tx :
827
        Transaction of interest.
828
    chain_id :
829
        ID of the executing chain.
830
831
    Returns
832
    -------
833
    sender : `ethereum.fork_types.Address`
834
        The address of the account that signed the transaction.
835
    """
836
    r, s = tx.r, tx.s
837
    if 0 >= r or r >= SECP256K1N:
838
        raise InvalidBlock
839
    if 0 >= s or s > SECP256K1N // 2:
840
        raise InvalidBlock
841
842
    if isinstance(tx, LegacyTransaction):
843
        v = tx.v
844
        if v == 27 or v == 28:
845
            public_key = secp256k1_recover(
846
                r, s, v - 27, signing_hash_pre155(tx)
847
            )
848
        else:
849
            if v != 35 + chain_id * 2 and v != 36 + chain_id * 2:
850
                raise InvalidBlock
851
            public_key = secp256k1_recover(
852
                r, s, v - 35 - chain_id * 2, signing_hash_155(tx, chain_id)
853
            )
854
    elif isinstance(tx, AccessListTransaction):
855
        public_key = secp256k1_recover(
856
            r, s, tx.y_parity, signing_hash_2930(tx)
857
        )
858
859
    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: Transaction) -> Hash32:
863
    """
864
    Compute the hash of a transaction used in a legacy (pre EIP 155) signature.
865
866
    Parameters
867
    ----------
868
    tx :
869
        Transaction of interest.
870
871
    Returns
872
    -------
873
    hash : `ethereum.crypto.hash.Hash32`
874
        Hash of the transaction.
875
    """
876
    return keccak256(
877
        rlp.encode(
878
            (
879
                tx.nonce,
880
                tx.gas_price,
881
                tx.gas,
882
                tx.to,
883
                tx.value,
884
                tx.data,
885
            )
886
        )
887
    )

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: Transaction, ​​chain_id: U64) -> Hash32:
891
    """
892
    Compute the hash of a transaction used in a EIP 155 signature.
893
894
    Parameters
895
    ----------
896
    tx :
897
        Transaction of interest.
898
    chain_id :
899
        The id of the current chain.
900
901
    Returns
902
    -------
903
    hash : `ethereum.crypto.hash.Hash32`
904
        Hash of the transaction.
905
    """
906
    return keccak256(
907
        rlp.encode(
908
            (
909
                tx.nonce,
910
                tx.gas_price,
911
                tx.gas,
912
                tx.to,
913
                tx.value,
914
                tx.data,
915
                chain_id,
916
                Uint(0),
917
                Uint(0),
918
            )
919
        )
920
    )

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:
924
    """
925
    Compute the hash of a transaction used in a EIP 2930 signature.
926
927
    Parameters
928
    ----------
929
    tx :
930
        Transaction of interest.
931
932
    Returns
933
    -------
934
    hash : `ethereum.crypto.hash.Hash32`
935
        Hash of the transaction.
936
    """
937
    return keccak256(
938
        b"\x01"
939
        + rlp.encode(
940
            (
941
                tx.chain_id,
942
                tx.nonce,
943
                tx.gas_price,
944
                tx.gas,
945
                tx.to,
946
                tx.value,
947
                tx.data,
948
                tx.access_list,
949
            )
950
        )
951
    )

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:
955
    """
956
    Computes the hash of a block header.
957
958
    The header hash of a block is the canonical hash that is used to refer
959
    to a specific block and completely distinguishes a block from another.
960
961
    ``keccak256`` is a function that produces a 256 bit hash of any input.
962
    It also takes in any number of bytes as an input and produces a single
963
    hash for them. A hash is a completely unique output for a single input.
964
    So an input corresponds to one unique hash that can be used to identify
965
    the input exactly.
966
967
    Prior to using the ``keccak256`` hash function, the header must be
968
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
969
    RLP encoding the header converts it into a space-efficient format that
970
    allows for easy transfer of data between nodes. The purpose of RLP is to
971
    encode arbitrarily nested arrays of binary data, and RLP is the primary
972
    encoding method used to serialize objects in Ethereum's execution layer.
973
    The only purpose of RLP is to encode structure; encoding specific data
974
    types (e.g. strings, floats) is left up to higher-order protocols.
975
976
    Parameters
977
    ----------
978
    header :
979
        Header of interest.
980
981
    Returns
982
    -------
983
    hash : `ethereum.crypto.hash.Hash32`
984
        Hash of the header.
985
    """
986
    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:
990
    """
991
    Validates the gas limit for a block.
992
993
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
994
    quotient of the parent block's gas limit and the
995
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
996
    passed through as a parameter is greater than or equal to the *sum* of
997
    the parent's gas and the adjustment delta then the limit for gas is too
998
    high and fails this function's check. Similarly, if the limit is less
999
    than or equal to the *difference* of the parent's gas and the adjustment
1000
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
1001
    check fails because the gas limit doesn't allow for a sufficient or
1002
    reasonable amount of gas to be used on a block.
1003
1004
    Parameters
1005
    ----------
1006
    gas_limit :
1007
        Gas limit to validate.
1008
1009
    parent_gas_limit :
1010
        Gas limit of the parent block.
1011
1012
    Returns
1013
    -------
1014
    check : `bool`
1015
        True if gas limit constraints are satisfied, False otherwise.
1016
    """
1017
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
1018
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
1019
        return False
1020
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
1021
        return False
1022
    if gas_limit < GAS_LIMIT_MINIMUM:
1023
        return False
1024
1025
    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:
1035
    """
1036
    Computes difficulty of a block using its header and parent header.
1037
1038
    The difficulty is determined by the time the block was created after its
1039
    parent. The ``offset`` is calculated using the parent block's difficulty,
1040
    ``parent_difficulty``, and the timestamp between blocks. This offset is
1041
    then added to the parent difficulty and is stored as the ``difficulty``
1042
    variable. If the time between the block and its parent is too short, the
1043
    offset will result in a positive number thus making the sum of
1044
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
1045
    avoid mass forking. But, if the time is long enough, then the offset
1046
    results in a negative value making the block less difficult than
1047
    its parent.
1048
1049
    The base standard for a block's difficulty is the predefined value
1050
    set for the genesis block since it has no parent. So, a block
1051
    can't be less difficult than the genesis block, therefore each block's
1052
    difficulty is set to the maximum value between the calculated
1053
    difficulty and the ``GENESIS_DIFFICULTY``.
1054
1055
    Parameters
1056
    ----------
1057
    block_number :
1058
        Block number of the block.
1059
    block_timestamp :
1060
        Timestamp of the block.
1061
    parent_timestamp :
1062
        Timestamp of the parent block.
1063
    parent_difficulty :
1064
        difficulty of the parent block.
1065
    parent_has_ommers:
1066
        does the parent have ommers.
1067
1068
    Returns
1069
    -------
1070
    difficulty : `ethereum.base_types.Uint`
1071
        Computed difficulty for a block.
1072
    """
1073
    offset = (
1074
        int(parent_difficulty)
1075
        // 2048
1076
        * max(
1077
            (2 if parent_has_ommers else 1)
1078
            - int(block_timestamp - parent_timestamp) // 9,
1079
            -99,
1080
        )
1081
    )
1082
    difficulty = int(parent_difficulty) + offset
1083
    # Historical Note: The difficulty bomb was not present in Ethereum at the
1084
    # start of Frontier, but was added shortly after launch. However since the
1085
    # bomb has no effect prior to block 200000 we pretend it existed from
1086
    # genesis.
1087
    # See https://github.com/ethereum/go-ethereum/pull/1588
1088
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
1089
    if num_bomb_periods >= 0:
1090
        difficulty += 2**num_bomb_periods
1091
1092
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
1093
    # the bomb. This bug does not matter because the difficulty is always much
1094
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
1095
    return Uint(max(difficulty, MINIMUM_DIFFICULTY))