ethereum.frontier.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

48
BLOCK_REWARD = U256(5 * 10**18)

GAS_LIMIT_ADJUSTMENT_FACTOR

49
GAS_LIMIT_ADJUSTMENT_FACTOR = 1024

GAS_LIMIT_MINIMUM

50
GAS_LIMIT_MINIMUM = 5000

MINIMUM_DIFFICULTY

51
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

52
MAX_OMMER_DEPTH = 6

BlockChain

History and current state of the block chain.

55
@dataclass
class BlockChain:

blocks

61
    blocks: List[Block]

state

62
    state: State

chain_id

63
    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:
67
    """
68
    Transforms the state from the previous hard fork (`old`) into the block
69
    chain object for this hard fork and returns it.
70
71
    When forks need to implement an irregular state transition, this function
72
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
73
    an example.
74
75
    Parameters
76
    ----------
77
    old :
78
        Previous block chain object.
79
80
    Returns
81
    -------
82
    new : `BlockChain`
83
        Upgraded block chain object for this hard fork.
84
    """
85
    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]:
89
    """
90
    Obtain the list of hashes of the previous 256 blocks in order of
91
    increasing block number.
92
93
    This function will return less hashes for the first 256 blocks.
94
95
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
96
    therefore this function retrieves them.
97
98
    Parameters
99
    ----------
100
    chain :
101
        History and current state.
102
103
    Returns
104
    -------
105
    recent_block_hashes : `List[Hash32]`
106
        Hashes of the recent 256 blocks in order of increasing block number.
107
    """
108
    recent_blocks = chain.blocks[-255:]
109
    # TODO: This function has not been tested rigorously
110
    if len(recent_blocks) == 0:
111
        return []
112
113
    recent_block_hashes = []
114
115
    for block in recent_blocks:
116
        prev_block_hash = block.header.parent_hash
117
        recent_block_hashes.append(prev_block_hash)
118
119
    # We are computing the hash only for the most recent block and not for
120
    # the rest of the blocks as they have successors which have the hash of
121
    # the current block as parent hash.
122
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
123
    recent_block_hashes.append(most_recent_block_hash)
124
125
    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:
129
    """
130
    Attempts to apply a block to an existing block chain.
131
132
    All parts of the block's contents need to be verified before being added
133
    to the chain. Blocks are verified by ensuring that the contents of the
134
    block make logical sense with the contents of the parent block. The
135
    information in the block's header must also match the corresponding
136
    information in the block.
137
138
    To implement Ethereum, in theory clients are only required to store the
139
    most recent 255 blocks of the chain since as far as execution is
140
    concerned, only those blocks are accessed. Practically, however, clients
141
    should store more blocks to handle reorgs.
142
143
    Parameters
144
    ----------
145
    chain :
146
        History and current state.
147
    block :
148
        Block to apply to `chain`.
149
    """
150
    parent_header = chain.blocks[-1].header
151
    validate_header(block.header, parent_header)
152
    validate_ommers(block.ommers, block.header, chain)
153
    apply_body_output = apply_body(
154
        chain.state,
155
        get_last_256_block_hashes(chain),
156
        block.header.coinbase,
157
        block.header.number,
158
        block.header.gas_limit,
159
        block.header.timestamp,
160
        block.header.difficulty,
161
        block.transactions,
162
        block.ommers,
163
    )
164
    if apply_body_output.block_gas_used != block.header.gas_used:
165
        raise InvalidBlock
166
    if apply_body_output.transactions_root != block.header.transactions_root:
167
        raise InvalidBlock
168
    if apply_body_output.state_root != block.header.state_root:
169
        raise InvalidBlock
170
    if apply_body_output.receipt_root != block.header.receipt_root:
171
        raise InvalidBlock
172
    if apply_body_output.block_logs_bloom != block.header.bloom:
173
        raise InvalidBlock
174
175
    chain.blocks.append(block)
176
    if len(chain.blocks) > 255:
177
        # Real clients have to store more blocks to deal with reorgs, but the
178
        # protocol only requires the last 255
179
        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:
183
    """
184
    Verifies a block header.
185
186
    In order to consider a block's header valid, the logic for the
187
    quantities in the header should match the logic for the block itself.
188
    For example the header timestamp should be greater than the block's parent
189
    timestamp because the block was created *after* the parent block.
190
    Additionally, the block's number should be directly following the parent
191
    block's number since it is the next block in the sequence.
192
193
    Parameters
194
    ----------
195
    header :
196
        Header to check for correctness.
197
    parent_header :
198
        Parent Header of the header to check for correctness
199
    """
200
    if header.timestamp <= parent_header.timestamp:
201
        raise InvalidBlock
202
    if header.number != parent_header.number + 1:
203
        raise InvalidBlock
204
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
205
        raise InvalidBlock
206
    if len(header.extra_data) > 32:
207
        raise InvalidBlock
208
209
    block_difficulty = calculate_block_difficulty(
210
        header.number,
211
        header.timestamp,
212
        parent_header.timestamp,
213
        parent_header.difficulty,
214
    )
215
    if header.difficulty != block_difficulty:
216
        raise InvalidBlock
217
218
    block_parent_hash = keccak256(rlp.encode(parent_header))
219
    if header.parent_hash != block_parent_hash:
220
        raise InvalidBlock
221
222
    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:
226
    """
227
    Generate rlp hash of the header which is to be used for Proof-of-Work
228
    verification.
229
230
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
231
    while calculating this hash.
232
233
    A particular PoW is valid for a single hash, that hash is computed by
234
    this function. The `nonce` and `mix_digest` are omitted from this hash
235
    because they are being changed by miners in their search for a sufficient
236
    proof-of-work.
237
238
    Parameters
239
    ----------
240
    header :
241
        The header object for which the hash is to be generated.
242
243
    Returns
244
    -------
245
    hash : `Hash32`
246
        The PoW valid rlp hash of the passed in header.
247
    """
248
    header_data_without_pow_artefacts = (
249
        header.parent_hash,
250
        header.ommers_hash,
251
        header.coinbase,
252
        header.state_root,
253
        header.transactions_root,
254
        header.receipt_root,
255
        header.bloom,
256
        header.difficulty,
257
        header.number,
258
        header.gas_limit,
259
        header.gas_used,
260
        header.timestamp,
261
        header.extra_data,
262
    )
263
264
    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:
268
    """
269
    Validates the Proof of Work constraints.
270
271
    In order to verify that a miner's proof-of-work is valid for a block, a
272
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
273
    hash function. The mix digest is a hash of the header and the nonce that
274
    is passed through and it confirms whether or not proof-of-work was done
275
    on the correct block. The result is the actual hash value of the block.
276
277
    Parameters
278
    ----------
279
    header :
280
        Header of interest.
281
    """
282
    header_hash = generate_header_hash_for_pow(header)
283
    # TODO: Memoize this somewhere and read from that data instead of
284
    # calculating cache for every block validation.
285
    cache = generate_cache(header.number)
286
    mix_digest, result = hashimoto_light(
287
        header_hash, header.nonce, cache, dataset_size(header.number)
288
    )
289
    if mix_digest != header.mix_digest:
290
        raise InvalidBlock
291
    if Uint.from_be_bytes(result) > (U256_CEIL_VALUE // header.difficulty):
292
        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.

Returns

sender_address : The sender of the transaction.

Raises

InvalidBlock : If the transaction is not includable.

def check_transaction(tx: Transaction, ​​gas_available: Uint) -> Address:
299
    """
300
    Check if the transaction is includable in the block.
301
302
    Parameters
303
    ----------
304
    tx :
305
        The transaction.
306
    gas_available :
307
        The gas remaining in the block.
308
309
    Returns
310
    -------
311
    sender_address :
312
        The sender of the transaction.
313
314
    Raises
315
    ------
316
    InvalidBlock :
317
        If the transaction is not includable.
318
    """
319
    if tx.gas > gas_available:
320
        raise InvalidBlock
321
    sender_address = recover_sender(tx)
322
323
    return sender_address

make_receipt

Make the receipt for a transaction that was executed.

Parameters

tx : The executed transaction. post_state : The state root immediately after this transaction. 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, ​​post_state: Bytes32, ​​cumulative_gas_used: Uint, ​​logs: Tuple[Log, ...]) -> Receipt:
332
    """
333
    Make the receipt for a transaction that was executed.
334
335
    Parameters
336
    ----------
337
    tx :
338
        The executed transaction.
339
    post_state :
340
        The state root immediately after this transaction.
341
    cumulative_gas_used :
342
        The total gas used so far in the block after the transaction was
343
        executed.
344
    logs :
345
        The logs produced by the transaction.
346
347
    Returns
348
    -------
349
    receipt :
350
        The receipt for the transaction.
351
    """
352
    receipt = Receipt(
353
        post_state=post_state,
354
        cumulative_gas_used=cumulative_gas_used,
355
        bloom=logs_bloom(logs),
356
        logs=logs,
357
    )
358
359
    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.

362
@dataclass
class ApplyBodyOutput:

block_gas_used

382
    block_gas_used: Uint

transactions_root

383
    transactions_root: Root

receipt_root

384
    receipt_root: Root

block_logs_bloom

385
    block_logs_bloom: Bloom

state_root

386
    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.)

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

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:
499
    """
500
    Validates the ommers mentioned in the block.
501
502
    An ommer block is a block that wasn't canonically added to the
503
    blockchain because it wasn't validated as fast as the canonical block
504
    but was mined at the same time.
505
506
    To be considered valid, the ommers must adhere to the rules defined in
507
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
508
    there cannot be duplicate ommers in a block. Many of the other ommer
509
    constraints are listed in the in-line comments of this function.
510
511
    Parameters
512
    ----------
513
    ommers :
514
        List of ommers mentioned in the current block.
515
    block_header:
516
        The header of current block.
517
    chain :
518
        History and current state.
519
    """
520
    block_hash = rlp.rlp_hash(block_header)
521
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
522
        raise InvalidBlock
523
524
    if len(ommers) == 0:
525
        # Nothing to validate
526
        return
527
528
    # Check that each ommer satisfies the constraints of a header
529
    for ommer in ommers:
530
        if 1 > ommer.number or ommer.number >= block_header.number:
531
            raise InvalidBlock
532
        ommer_parent_header = chain.blocks[
533
            -(block_header.number - ommer.number) - 1
534
        ].header
535
        validate_header(ommer, ommer_parent_header)
536
    if len(ommers) > 2:
537
        raise InvalidBlock
538
539
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
540
    if len(ommers_hashes) != len(set(ommers_hashes)):
541
        raise InvalidBlock
542
543
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + 1) :]
544
    recent_canonical_block_hashes = {
545
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
546
    }
547
    recent_ommers_hashes: Set[Hash32] = set()
548
    for block in recent_canonical_blocks:
549
        recent_ommers_hashes = recent_ommers_hashes.union(
550
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
551
        )
552
553
    for ommer_index, ommer in enumerate(ommers):
554
        ommer_hash = ommers_hashes[ommer_index]
555
        if ommer_hash == block_hash:
556
            raise InvalidBlock
557
        if ommer_hash in recent_canonical_block_hashes:
558
            raise InvalidBlock
559
        if ommer_hash in recent_ommers_hashes:
560
            raise InvalidBlock
561
562
        # Ommer age with respect to the current block. For example, an age of
563
        # 1 indicates that the ommer is a sibling of previous block.
564
        ommer_age = block_header.number - ommer.number
565
        if 1 > ommer_age or ommer_age > MAX_OMMER_DEPTH:
566
            raise InvalidBlock
567
        if ommer.parent_hash not in recent_canonical_block_hashes:
568
            raise InvalidBlock
569
        if ommer.parent_hash == block_header.parent_hash:
570
            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:
579
    """
580
    Pay rewards to the block miner as well as the ommers miners.
581
582
    The miner of the canonical block is rewarded with the predetermined
583
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
584
    number of ommer blocks that were mined around the same time, and included
585
    in the canonical block's header. An ommer block is a block that wasn't
586
    added to the canonical blockchain because it wasn't validated as fast as
587
    the accepted block but was mined at the same time. Although not all blocks
588
    that are mined are added to the canonical chain, miners are still paid a
589
    reward for their efforts. This reward is called an ommer reward and is
590
    calculated based on the number associated with the ommer block that they
591
    mined.
592
593
    Parameters
594
    ----------
595
    state :
596
        Current account state.
597
    block_number :
598
        Position of the block within the chain.
599
    coinbase :
600
        Address of account which receives block reward and transaction fees.
601
    ommers :
602
        List of ommers mentioned in the current block.
603
    """
604
    miner_reward = BLOCK_REWARD + (len(ommers) * (BLOCK_REWARD // 32))
605
    create_ether(state, coinbase, miner_reward)
606
607
    for ommer in ommers:
608
        # Ommer age with respect to the current block.
609
        ommer_age = U256(block_number - ommer.number)
610
        ommer_miner_reward = ((8 - ommer_age) * BLOCK_REWARD) // 8
611
        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.frontier.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...]]:
617
    """
618
    Execute a transaction against the provided environment.
619
620
    This function processes the actions needed to execute a transaction.
621
    It decrements the sender's account after calculating the gas fee and
622
    refunds them the proper amount after execution. Calling contracts,
623
    deploying code, and incrementing nonces are all examples of actions that
624
    happen within this function or from a call made within this function.
625
626
    Accounts that are marked for deletion are processed and destroyed after
627
    execution.
628
629
    Parameters
630
    ----------
631
    env :
632
        Environment for the Ethereum Virtual Machine.
633
    tx :
634
        Transaction to execute.
635
636
    Returns
637
    -------
638
    gas_left : `ethereum.base_types.U256`
639
        Remaining gas after execution.
640
    logs : `Tuple[ethereum.blocks.Log, ...]`
641
        Logs generated during execution.
642
    """
643
    if not validate_transaction(tx):
644
        raise InvalidBlock
645
646
    sender = env.origin
647
    sender_account = get_account(env.state, sender)
648
    gas_fee = tx.gas * tx.gas_price
649
    if sender_account.nonce != tx.nonce:
650
        raise InvalidBlock
651
    if sender_account.balance < gas_fee + tx.value:
652
        raise InvalidBlock
653
    if sender_account.code != bytearray():
654
        raise InvalidBlock
655
656
    gas = tx.gas - calculate_intrinsic_cost(tx)
657
    increment_nonce(env.state, sender)
658
    sender_balance_after_gas_fee = sender_account.balance - gas_fee
659
    set_account_balance(env.state, sender, sender_balance_after_gas_fee)
660
661
    message = prepare_message(
662
        sender,
663
        tx.to,
664
        tx.value,
665
        tx.data,
666
        gas,
667
        env,
668
    )
669
670
    output = process_message_call(message, env)
671
672
    gas_used = tx.gas - output.gas_left
673
    gas_refund = min(gas_used // 2, output.refund_counter)
674
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
675
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
676
    total_gas_used = gas_used - gas_refund
677
678
    # refund gas
679
    sender_balance_after_refund = (
680
        get_account(env.state, sender).balance + gas_refund_amount
681
    )
682
    set_account_balance(env.state, sender, sender_balance_after_refund)
683
684
    # transfer miner fees
685
    coinbase_balance_after_mining_fee = (
686
        get_account(env.state, env.coinbase).balance + transaction_fee
687
    )
688
    set_account_balance(
689
        env.state, env.coinbase, coinbase_balance_after_mining_fee
690
    )
691
692
    for address in output.accounts_to_delete:
693
        destroy_account(env.state, address)
694
695
    return total_gas_used, output.logs

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:
699
    """
700
    Verifies a transaction.
701
702
    The gas in a transaction gets used to pay for the intrinsic cost of
703
    operations, therefore if there is insufficient gas then it would not
704
    be possible to execute a transaction and it will be declared invalid.
705
706
    Additionally, the nonce of a transaction must not equal or exceed the
707
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
708
    In practice, defining the limit as ``2**64-1`` has no impact because
709
    sending ``2**64-1`` transactions is improbable. It's not strictly
710
    impossible though, ``2**64-1`` transactions is the entire capacity of the
711
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
712
713
    Parameters
714
    ----------
715
    tx :
716
        Transaction to validate.
717
718
    Returns
719
    -------
720
    verified : `bool`
721
        True if the transaction can be executed, or False otherwise.
722
    """
723
    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:
727
    """
728
    Calculates the gas that is charged before execution is started.
729
730
    The intrinsic cost of the transaction is charged before execution has
731
    begun. Functions/operations in the EVM cost money to execute so this
732
    intrinsic cost is for the operations that need to be paid for as part of
733
    the transaction. Data transfer, for example, is part of this intrinsic
734
    cost. It costs ether to send data over the wire and that ether is
735
    accounted for in the intrinsic cost calculated in this function. This
736
    intrinsic cost must be calculated and paid for before execution in order
737
    for all operations to be implemented.
738
739
    Parameters
740
    ----------
741
    tx :
742
        Transaction to compute the intrinsic cost of.
743
744
    Returns
745
    -------
746
    verified : `ethereum.base_types.Uint`
747
        The intrinsic cost of the transaction.
748
    """
749
    data_cost = 0
750
751
    for byte in tx.data:
752
        if byte == 0:
753
            data_cost += TX_DATA_COST_PER_ZERO
754
        else:
755
            data_cost += TX_DATA_COST_PER_NON_ZERO
756
757
    return Uint(TX_BASE_COST + data_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.

Returns

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

def recover_sender(tx: Transaction) -> Address:
761
    """
762
    Extracts the sender address from a transaction.
763
764
    The v, r, and s values are the three parts that make up the signature
765
    of a transaction. In order to recover the sender of a transaction the two
766
    components needed are the signature (``v``, ``r``, and ``s``) and the
767
    signing hash of the transaction. The sender's public key can be obtained
768
    with these two values and therefore the sender address can be retrieved.
769
770
    Parameters
771
    ----------
772
    tx :
773
        Transaction of interest.
774
775
    Returns
776
    -------
777
    sender : `ethereum.fork_types.Address`
778
        The address of the account that signed the transaction.
779
    """
780
    v, r, s = tx.v, tx.r, tx.s
781
    if v != 27 and v != 28:
782
        raise InvalidBlock
783
    if 0 >= r or r >= SECP256K1N:
784
        raise InvalidBlock
785
    if 0 >= s or s >= SECP256K1N:
786
        raise InvalidBlock
787
788
    public_key = secp256k1_recover(r, s, v - 27, signing_hash(tx))
789
    return Address(keccak256(public_key)[12:32])

signing_hash

Compute the hash of a transaction used in the signature.

The values that are used to compute the signing hash set the rules for a transaction. For example, signing over the gas sets a limit for the amount of money that is allowed to be pulled out of the sender's account.

Parameters

tx : Transaction of interest.

Returns

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

def signing_hash(tx: Transaction) -> Hash32:
793
    """
794
    Compute the hash of a transaction used in the signature.
795
796
    The values that are used to compute the signing hash set the rules for a
797
    transaction. For example, signing over the gas sets a limit for the
798
    amount of money that is allowed to be pulled out of the sender's account.
799
800
    Parameters
801
    ----------
802
    tx :
803
        Transaction of interest.
804
805
    Returns
806
    -------
807
    hash : `ethereum.crypto.hash.Hash32`
808
        Hash of the transaction.
809
    """
810
    return keccak256(
811
        rlp.encode(
812
            (
813
                tx.nonce,
814
                tx.gas_price,
815
                tx.gas,
816
                tx.to,
817
                tx.value,
818
                tx.data,
819
            )
820
        )
821
    )

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:
825
    """
826
    Computes the hash of a block header.
827
828
    The header hash of a block is the canonical hash that is used to refer
829
    to a specific block and completely distinguishes a block from another.
830
831
    ``keccak256`` is a function that produces a 256 bit hash of any input.
832
    It also takes in any number of bytes as an input and produces a single
833
    hash for them. A hash is a completely unique output for a single input.
834
    So an input corresponds to one unique hash that can be used to identify
835
    the input exactly.
836
837
    Prior to using the ``keccak256`` hash function, the header must be
838
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
839
    RLP encoding the header converts it into a space-efficient format that
840
    allows for easy transfer of data between nodes. The purpose of RLP is to
841
    encode arbitrarily nested arrays of binary data, and RLP is the primary
842
    encoding method used to serialize objects in Ethereum's execution layer.
843
    The only purpose of RLP is to encode structure; encoding specific data
844
    types (e.g. strings, floats) is left up to higher-order protocols.
845
846
    Parameters
847
    ----------
848
    header :
849
        Header of interest.
850
851
    Returns
852
    -------
853
    hash : `ethereum.crypto.hash.Hash32`
854
        Hash of the header.
855
    """
856
    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:
860
    """
861
    Validates the gas limit for a block.
862
863
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
864
    quotient of the parent block's gas limit and the
865
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
866
    passed through as a parameter is greater than or equal to the *sum* of
867
    the parent's gas and the adjustment delta then the limit for gas is too
868
    high and fails this function's check. Similarly, if the limit is less
869
    than or equal to the *difference* of the parent's gas and the adjustment
870
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
871
    check fails because the gas limit doesn't allow for a sufficient or
872
    reasonable amount of gas to be used on a block.
873
874
    Parameters
875
    ----------
876
    gas_limit :
877
        Gas limit to validate.
878
879
    parent_gas_limit :
880
        Gas limit of the parent block.
881
882
    Returns
883
    -------
884
    check : `bool`
885
        True if gas limit constraints are satisfied, False otherwise.
886
    """
887
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
888
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
889
        return False
890
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
891
        return False
892
    if gas_limit < GAS_LIMIT_MINIMUM:
893
        return False
894
895
    return True

calculate_block_difficulty

Computes difficulty of a block using its header and parent header.

The difficulty of a block is determined by the time the block was created after its parent. If a block's timestamp is more than 13 seconds after its parent block then its difficulty is set as the difference between the parent's difficulty and the max_adjustment_delta. Otherwise, if the time between parent and child blocks is too small (under 13 seconds) then, to avoid mass forking, the block's difficulty is set to the sum of the delta and the parent's 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.

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) -> Uint:
904
    """
905
    Computes difficulty of a block using its header and
906
    parent header.
907
908
    The difficulty of a block is determined by the time the block was
909
    created after its parent. If a block's timestamp is more than 13
910
    seconds after its parent block then its difficulty is set as the
911
    difference between the parent's difficulty and the
912
    ``max_adjustment_delta``. Otherwise, if the time between parent and
913
    child blocks is too small (under 13 seconds) then, to avoid mass
914
    forking, the block's difficulty is set to the sum of the delta and
915
    the parent's difficulty.
916
917
    Parameters
918
    ----------
919
    block_number :
920
        Block number of the block.
921
    block_timestamp :
922
        Timestamp of the block.
923
    parent_timestamp :
924
        Timestamp of the parent block.
925
    parent_difficulty :
926
        difficulty of the parent block.
927
928
    Returns
929
    -------
930
    difficulty : `ethereum.base_types.Uint`
931
        Computed difficulty for a block.
932
    """
933
    max_adjustment_delta = parent_difficulty // Uint(2048)
934
    if block_timestamp < parent_timestamp + 13:
935
        difficulty = parent_difficulty + max_adjustment_delta
936
    else:  # block_timestamp >= parent_timestamp + 13
937
        difficulty = parent_difficulty - max_adjustment_delta
938
939
    # Historical Note: The difficulty bomb was not present in Ethereum at the
940
    # start of Frontier, but was added shortly after launch. However since the
941
    # bomb has no effect prior to block 200000 we pretend it existed from
942
    # genesis.
943
    # See https://github.com/ethereum/go-ethereum/pull/1588
944
    num_bomb_periods = (int(block_number) // 100000) - 2
945
    if num_bomb_periods >= 0:
946
        difficulty += 2**num_bomb_periods
947
948
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
949
    # the bomb. This bug does not matter because the difficulty is always much
950
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
951
    return max(difficulty, MINIMUM_DIFFICULTY)