ethereum.homestead.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

50
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

51
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

52
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

53
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

56
@dataclass
class BlockChain:

blocks

62
    blocks: List[Block]

state

63
    state: State

chain_id

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

367
@dataclass
class ApplyBodyOutput:

block_gas_used

387
    block_gas_used: Uint

transactions_root

388
    transactions_root: Root

receipt_root

389
    receipt_root: Root

block_logs_bloom

390
    block_logs_bloom: Bloom

state_root

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

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

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:
705
    """
706
    Computes the hash of a block header.
707
708
    The header hash of a block is the canonical hash that is used to refer
709
    to a specific block and completely distinguishes a block from another.
710
711
    ``keccak256`` is a function that produces a 256 bit hash of any input.
712
    It also takes in any number of bytes as an input and produces a single
713
    hash for them. A hash is a completely unique output for a single input.
714
    So an input corresponds to one unique hash that can be used to identify
715
    the input exactly.
716
717
    Prior to using the ``keccak256`` hash function, the header must be
718
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
719
    RLP encoding the header converts it into a space-efficient format that
720
    allows for easy transfer of data between nodes. The purpose of RLP is to
721
    encode arbitrarily nested arrays of binary data, and RLP is the primary
722
    encoding method used to serialize objects in Ethereum's execution layer.
723
    The only purpose of RLP is to encode structure; encoding specific data
724
    types (e.g. strings, floats) is left up to higher-order protocols.
725
726
    Parameters
727
    ----------
728
    header :
729
        Header of interest.
730
731
    Returns
732
    -------
733
    hash : `ethereum.crypto.hash.Hash32`
734
        Hash of the header.
735
    """
736
    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:
740
    """
741
    Validates the gas limit for a block.
742
743
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
744
    quotient of the parent block's gas limit and the
745
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
746
    passed through as a parameter is greater than or equal to the *sum* of
747
    the parent's gas and the adjustment delta then the limit for gas is too
748
    high and fails this function's check. Similarly, if the limit is less
749
    than or equal to the *difference* of the parent's gas and the adjustment
750
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
751
    check fails because the gas limit doesn't allow for a sufficient or
752
    reasonable amount of gas to be used on a block.
753
754
    Parameters
755
    ----------
756
    gas_limit :
757
        Gas limit to validate.
758
759
    parent_gas_limit :
760
        Gas limit of the parent block.
761
762
    Returns
763
    -------
764
    check : `bool`
765
        True if gas limit constraints are satisfied, False otherwise.
766
    """
767
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
768
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
769
        return False
770
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
771
        return False
772
    if gas_limit < GAS_LIMIT_MINIMUM:
773
        return False
774
775
    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.

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:
784
    """
785
    Computes difficulty of a block using its header and parent header.
786
787
    The difficulty is determined by the time the block was created after its
788
    parent. The ``offset`` is calculated using the parent block's difficulty,
789
    ``parent_difficulty``, and the timestamp between blocks. This offset is
790
    then added to the parent difficulty and is stored as the ``difficulty``
791
    variable. If the time between the block and its parent is too short, the
792
    offset will result in a positive number thus making the sum of
793
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
794
    avoid mass forking. But, if the time is long enough, then the offset
795
    results in a negative value making the block less difficult than
796
    its parent.
797
798
    The base standard for a block's difficulty is the predefined value
799
    set for the genesis block since it has no parent. So, a block
800
    can't be less difficult than the genesis block, therefore each block's
801
    difficulty is set to the maximum value between the calculated
802
    difficulty and the ``GENESIS_DIFFICULTY``.
803
804
    Parameters
805
    ----------
806
    block_number :
807
        Block number of the block.
808
    block_timestamp :
809
        Timestamp of the block.
810
    parent_timestamp :
811
        Timestamp of the parent block.
812
    parent_difficulty :
813
        difficulty of the parent block.
814
815
    Returns
816
    -------
817
    difficulty : `ethereum.base_types.Uint`
818
        Computed difficulty for a block.
819
    """
820
    offset = (
821
        int(parent_difficulty)
822
        // 2048
823
        * max(1 - int(block_timestamp - parent_timestamp) // 10, -99)
824
    )
825
    difficulty = int(parent_difficulty) + offset
826
    # Historical Note: The difficulty bomb was not present in Ethereum at the
827
    # start of Frontier, but was added shortly after launch. However since the
828
    # bomb has no effect prior to block 200000 we pretend it existed from
829
    # genesis.
830
    # See https://github.com/ethereum/go-ethereum/pull/1588
831
    num_bomb_periods = (int(block_number) // 100000) - 2
832
    if num_bomb_periods >= 0:
833
        difficulty += 2**num_bomb_periods
834
835
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
836
    # the bomb. This bug does not matter because the difficulty is always much
837
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
838
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))