ethereum.constantinople.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

52
GAS_LIMIT_ADJUSTMENT_FACTOR = 1024

GAS_LIMIT_MINIMUM

53
GAS_LIMIT_MINIMUM = 5000

MINIMUM_DIFFICULTY

54
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

55
MAX_OMMER_DEPTH = 6

BOMB_DELAY_BLOCKS

56
BOMB_DELAY_BLOCKS = 5000000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

60
@dataclass
class BlockChain:

blocks

66
    blocks: List[Block]

state

67
    state: State

chain_id

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

373
@dataclass
class ApplyBodyOutput:

block_gas_used

393
    block_gas_used: Uint

transactions_root

394
    transactions_root: Root

receipt_root

395
    receipt_root: Root

block_logs_bloom

396
    block_logs_bloom: Bloom

state_root

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

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:
513
    """
514
    Validates the ommers mentioned in the block.
515
516
    An ommer block is a block that wasn't canonically added to the
517
    blockchain because it wasn't validated as fast as the canonical block
518
    but was mined at the same time.
519
520
    To be considered valid, the ommers must adhere to the rules defined in
521
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
522
    there cannot be duplicate ommers in a block. Many of the other ommer
523
    constraints are listed in the in-line comments of this function.
524
525
    Parameters
526
    ----------
527
    ommers :
528
        List of ommers mentioned in the current block.
529
    block_header:
530
        The header of current block.
531
    chain :
532
        History and current state.
533
    """
534
    block_hash = rlp.rlp_hash(block_header)
535
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
536
        raise InvalidBlock
537
538
    if len(ommers) == 0:
539
        # Nothing to validate
540
        return
541
542
    # Check that each ommer satisfies the constraints of a header
543
    for ommer in ommers:
544
        if 1 > ommer.number or ommer.number >= block_header.number:
545
            raise InvalidBlock
546
        ommer_parent_header = chain.blocks[
547
            -(block_header.number - ommer.number) - 1
548
        ].header
549
        validate_header(ommer, ommer_parent_header)
550
    if len(ommers) > 2:
551
        raise InvalidBlock
552
553
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
554
    if len(ommers_hashes) != len(set(ommers_hashes)):
555
        raise InvalidBlock
556
557
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + 1) :]
558
    recent_canonical_block_hashes = {
559
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
560
    }
561
    recent_ommers_hashes: Set[Hash32] = set()
562
    for block in recent_canonical_blocks:
563
        recent_ommers_hashes = recent_ommers_hashes.union(
564
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
565
        )
566
567
    for ommer_index, ommer in enumerate(ommers):
568
        ommer_hash = ommers_hashes[ommer_index]
569
        if ommer_hash == block_hash:
570
            raise InvalidBlock
571
        if ommer_hash in recent_canonical_block_hashes:
572
            raise InvalidBlock
573
        if ommer_hash in recent_ommers_hashes:
574
            raise InvalidBlock
575
576
        # Ommer age with respect to the current block. For example, an age of
577
        # 1 indicates that the ommer is a sibling of previous block.
578
        ommer_age = block_header.number - ommer.number
579
        if 1 > ommer_age or ommer_age > MAX_OMMER_DEPTH:
580
            raise InvalidBlock
581
        if ommer.parent_hash not in recent_canonical_block_hashes:
582
            raise InvalidBlock
583
        if ommer.parent_hash == block_header.parent_hash:
584
            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:
593
    """
594
    Pay rewards to the block miner as well as the ommers miners.
595
596
    The miner of the canonical block is rewarded with the predetermined
597
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
598
    number of ommer blocks that were mined around the same time, and included
599
    in the canonical block's header. An ommer block is a block that wasn't
600
    added to the canonical blockchain because it wasn't validated as fast as
601
    the accepted block but was mined at the same time. Although not all blocks
602
    that are mined are added to the canonical chain, miners are still paid a
603
    reward for their efforts. This reward is called an ommer reward and is
604
    calculated based on the number associated with the ommer block that they
605
    mined.
606
607
    Parameters
608
    ----------
609
    state :
610
        Current account state.
611
    block_number :
612
        Position of the block within the chain.
613
    coinbase :
614
        Address of account which receives block reward and transaction fees.
615
    ommers :
616
        List of ommers mentioned in the current block.
617
    """
618
    miner_reward = BLOCK_REWARD + (len(ommers) * (BLOCK_REWARD // 32))
619
    create_ether(state, coinbase, miner_reward)
620
621
    for ommer in ommers:
622
        # Ommer age with respect to the current block.
623
        ommer_age = U256(block_number - ommer.number)
624
        ommer_miner_reward = ((8 - ommer_age) * BLOCK_REWARD) // 8
625
        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.constantinople.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...], Optional[Exception]]:
631
    """
632
    Execute a transaction against the provided environment.
633
634
    This function processes the actions needed to execute a transaction.
635
    It decrements the sender's account after calculating the gas fee and
636
    refunds them the proper amount after execution. Calling contracts,
637
    deploying code, and incrementing nonces are all examples of actions that
638
    happen within this function or from a call made within this function.
639
640
    Accounts that are marked for deletion are processed and destroyed after
641
    execution.
642
643
    Parameters
644
    ----------
645
    env :
646
        Environment for the Ethereum Virtual Machine.
647
    tx :
648
        Transaction to execute.
649
650
    Returns
651
    -------
652
    gas_left : `ethereum.base_types.U256`
653
        Remaining gas after execution.
654
    logs : `Tuple[ethereum.blocks.Log, ...]`
655
        Logs generated during execution.
656
    """
657
    if not validate_transaction(tx):
658
        raise InvalidBlock
659
660
    sender = env.origin
661
    sender_account = get_account(env.state, sender)
662
    gas_fee = tx.gas * tx.gas_price
663
    if sender_account.nonce != tx.nonce:
664
        raise InvalidBlock
665
    if sender_account.balance < gas_fee + tx.value:
666
        raise InvalidBlock
667
    if sender_account.code != bytearray():
668
        raise InvalidBlock
669
670
    gas = tx.gas - calculate_intrinsic_cost(tx)
671
    increment_nonce(env.state, sender)
672
    sender_balance_after_gas_fee = sender_account.balance - gas_fee
673
    set_account_balance(env.state, sender, sender_balance_after_gas_fee)
674
675
    message = prepare_message(
676
        sender,
677
        tx.to,
678
        tx.value,
679
        tx.data,
680
        gas,
681
        env,
682
    )
683
684
    output = process_message_call(message, env)
685
686
    gas_used = tx.gas - output.gas_left
687
    gas_refund = min(gas_used // 2, output.refund_counter)
688
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
689
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
690
    total_gas_used = gas_used - gas_refund
691
692
    # refund gas
693
    sender_balance_after_refund = (
694
        get_account(env.state, sender).balance + gas_refund_amount
695
    )
696
    set_account_balance(env.state, sender, sender_balance_after_refund)
697
698
    # transfer miner fees
699
    coinbase_balance_after_mining_fee = (
700
        get_account(env.state, env.coinbase).balance + transaction_fee
701
    )
702
    if coinbase_balance_after_mining_fee != 0:
703
        set_account_balance(
704
            env.state, env.coinbase, coinbase_balance_after_mining_fee
705
        )
706
    elif account_exists_and_is_empty(env.state, env.coinbase):
707
        destroy_account(env.state, env.coinbase)
708
709
    for address in output.accounts_to_delete:
710
        destroy_account(env.state, address)
711
712
    for address in output.touched_accounts:
713
        if account_exists_and_is_empty(env.state, address):
714
            destroy_account(env.state, address)
715
716
    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:
720
    """
721
    Verifies a transaction.
722
723
    The gas in a transaction gets used to pay for the intrinsic cost of
724
    operations, therefore if there is insufficient gas then it would not
725
    be possible to execute a transaction and it will be declared invalid.
726
727
    Additionally, the nonce of a transaction must not equal or exceed the
728
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
729
    In practice, defining the limit as ``2**64-1`` has no impact because
730
    sending ``2**64-1`` transactions is improbable. It's not strictly
731
    impossible though, ``2**64-1`` transactions is the entire capacity of the
732
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
733
734
    Parameters
735
    ----------
736
    tx :
737
        Transaction to validate.
738
739
    Returns
740
    -------
741
    verified : `bool`
742
        True if the transaction can be executed, or False otherwise.
743
    """
744
    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:
748
    """
749
    Calculates the gas that is charged before execution is started.
750
751
    The intrinsic cost of the transaction is charged before execution has
752
    begun. Functions/operations in the EVM cost money to execute so this
753
    intrinsic cost is for the operations that need to be paid for as part of
754
    the transaction. Data transfer, for example, is part of this intrinsic
755
    cost. It costs ether to send data over the wire and that ether is
756
    accounted for in the intrinsic cost calculated in this function. This
757
    intrinsic cost must be calculated and paid for before execution in order
758
    for all operations to be implemented.
759
760
    Parameters
761
    ----------
762
    tx :
763
        Transaction to compute the intrinsic cost of.
764
765
    Returns
766
    -------
767
    verified : `ethereum.base_types.Uint`
768
        The intrinsic cost of the transaction.
769
    """
770
    data_cost = 0
771
772
    for byte in tx.data:
773
        if byte == 0:
774
            data_cost += TX_DATA_COST_PER_ZERO
775
        else:
776
            data_cost += TX_DATA_COST_PER_NON_ZERO
777
778
    if tx.to == Bytes0(b""):
779
        create_cost = TX_CREATE_COST
780
    else:
781
        create_cost = 0
782
783
    return Uint(TX_BASE_COST + data_cost + create_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:
787
    """
788
    Extracts the sender address from a transaction.
789
790
    The v, r, and s values are the three parts that make up the signature
791
    of a transaction. In order to recover the sender of a transaction the two
792
    components needed are the signature (``v``, ``r``, and ``s``) and the
793
    signing hash of the transaction. The sender's public key can be obtained
794
    with these two values and therefore the sender address can be retrieved.
795
796
    Parameters
797
    ----------
798
    tx :
799
        Transaction of interest.
800
    chain_id :
801
        ID of the executing chain.
802
803
    Returns
804
    -------
805
    sender : `ethereum.fork_types.Address`
806
        The address of the account that signed the transaction.
807
    """
808
    v, r, s = tx.v, tx.r, tx.s
809
    if 0 >= r or r >= SECP256K1N:
810
        raise InvalidBlock
811
    if 0 >= s or s > SECP256K1N // 2:
812
        raise InvalidBlock
813
814
    if v == 27 or v == 28:
815
        public_key = secp256k1_recover(r, s, v - 27, signing_hash_pre155(tx))
816
    else:
817
        if v != 35 + chain_id * 2 and v != 36 + chain_id * 2:
818
            raise InvalidBlock
819
        public_key = secp256k1_recover(
820
            r, s, v - 35 - chain_id * 2, signing_hash_155(tx, chain_id)
821
        )
822
    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:
826
    """
827
    Compute the hash of a transaction used in a legacy (pre EIP 155) signature.
828
829
    Parameters
830
    ----------
831
    tx :
832
        Transaction of interest.
833
834
    Returns
835
    -------
836
    hash : `ethereum.crypto.hash.Hash32`
837
        Hash of the transaction.
838
    """
839
    return keccak256(
840
        rlp.encode(
841
            (
842
                tx.nonce,
843
                tx.gas_price,
844
                tx.gas,
845
                tx.to,
846
                tx.value,
847
                tx.data,
848
            )
849
        )
850
    )

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:
854
    """
855
    Compute the hash of a transaction used in a EIP 155 signature.
856
857
    Parameters
858
    ----------
859
    tx :
860
        Transaction of interest.
861
    chain_id :
862
        The id of the current chain.
863
864
    Returns
865
    -------
866
    hash : `ethereum.crypto.hash.Hash32`
867
        Hash of the transaction.
868
    """
869
    return keccak256(
870
        rlp.encode(
871
            (
872
                tx.nonce,
873
                tx.gas_price,
874
                tx.gas,
875
                tx.to,
876
                tx.value,
877
                tx.data,
878
                chain_id,
879
                Uint(0),
880
                Uint(0),
881
            )
882
        )
883
    )

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