ethereum.homestead.forkethereum.dao_fork.fork

.. _dao-fork:

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

55
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

56
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

57
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

58
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

61
@dataclass
class BlockChain:

blocks

67
    blocks: List[Block]

state

68
    state: State

chain_id

69
    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.is used to handle the irregularity.

The DAO-Fork occurred as a result of the 2016 DAO Hacks <https://www.gemini.com/cryptopedia/the-dao-hack-makerdao>_ in which an unknown entity managed to drain more than 3.6 million ether causing the price of ether to drop by nearly 35%. This fork was the solution to the hacks and manually reset the affected parties' accounts to their state prior to the attack. This fork essentially rewrote the history of the Ethereum network.

Parameters

old : Previous block chain object.

Returns

new : BlockChain Upgraded block chain object for this hard fork.

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

387
@dataclass
class ApplyBodyOutput:

block_gas_used

407
    block_gas_used: Uint

transactions_root

408
    transactions_root: Root

receipt_root

409
    receipt_root: Root

block_logs_bloom

410
    block_logs_bloom: Bloom

state_root

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

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:
524
    """
525
    Validates the ommers mentioned in the block.
526
527
    An ommer block is a block that wasn't canonically added to the
528
    blockchain because it wasn't validated as fast as the canonical block
529
    but was mined at the same time.
530
531
    To be considered valid, the ommers must adhere to the rules defined in
532
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
533
    there cannot be duplicate ommers in a block. Many of the other ommer
534
    constraints are listed in the in-line comments of this function.
535
536
    Parameters
537
    ----------
538
    ommers :
539
        List of ommers mentioned in the current block.
540
    block_header:
541
        The header of current block.
542
    chain :
543
        History and current state.
544
    """
545
    block_hash = rlp.rlp_hash(block_header)
546
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
547
        raise InvalidBlock
548
549
    if len(ommers) == 0:
550
        # Nothing to validate
551
        return
552
553
    # Check that each ommer satisfies the constraints of a header
554
    for ommer in ommers:
555
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
556
            raise InvalidBlock
557
        ommer_parent_header = chain.blocks[
558
            -(block_header.number - ommer.number) - 1
559
        ].header
560
        validate_header(ommer, ommer_parent_header)
561
    if len(ommers) > 2:
562
        raise InvalidBlock
563
564
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
565
    if len(ommers_hashes) != len(set(ommers_hashes)):
566
        raise InvalidBlock
567
568
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
569
    recent_canonical_block_hashes = {
570
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
571
    }
572
    recent_ommers_hashes: Set[Hash32] = set()
573
    for block in recent_canonical_blocks:
574
        recent_ommers_hashes = recent_ommers_hashes.union(
575
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
576
        )
577
578
    for ommer_index, ommer in enumerate(ommers):
579
        ommer_hash = ommers_hashes[ommer_index]
580
        if ommer_hash == block_hash:
581
            raise InvalidBlock
582
        if ommer_hash in recent_canonical_block_hashes:
583
            raise InvalidBlock
584
        if ommer_hash in recent_ommers_hashes:
585
            raise InvalidBlock
586
587
        # Ommer age with respect to the current block. For example, an age of
588
        # 1 indicates that the ommer is a sibling of previous block.
589
        ommer_age = block_header.number - ommer.number
590
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
591
            raise InvalidBlock
592
        if ommer.parent_hash not in recent_canonical_block_hashes:
593
            raise InvalidBlock
594
        if ommer.parent_hash == block_header.parent_hash:
595
            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:
604
    """
605
    Pay rewards to the block miner as well as the ommers miners.
606
607
    The miner of the canonical block is rewarded with the predetermined
608
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
609
    number of ommer blocks that were mined around the same time, and included
610
    in the canonical block's header. An ommer block is a block that wasn't
611
    added to the canonical blockchain because it wasn't validated as fast as
612
    the accepted block but was mined at the same time. Although not all blocks
613
    that are mined are added to the canonical chain, miners are still paid a
614
    reward for their efforts. This reward is called an ommer reward and is
615
    calculated based on the number associated with the ommer block that they
616
    mined.
617
618
    Parameters
619
    ----------
620
    state :
621
        Current account state.
622
    block_number :
623
        Position of the block within the chain.
624
    coinbase :
625
        Address of account which receives block reward and transaction fees.
626
    ommers :
627
        List of ommers mentioned in the current block.
628
    """
629
    ommer_count = U256(len(ommers))
630
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
631
    create_ether(state, coinbase, miner_reward)
632
633
    for ommer in ommers:
634
        # Ommer age with respect to the current block.
635
        ommer_age = U256(block_number - ommer.number)
636
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
637
        create_ether(state, ommer.coinbase, ommer_miner_reward)

process_transaction

Execute a transaction against the provided environment.

This function processes the actions needed to execute a transaction. It decrements the sender's account after calculating the gas fee and refunds them the proper amount after execution. Calling contracts, deploying code, and incrementing nonces are all examples of actions that happen within this function or from a call made within this function.

Accounts that are marked for deletion are processed and destroyed after execution.

Parameters

env : Environment for the Ethereum Virtual Machine. tx : Transaction to execute.

Returns

gas_left : ethereum.base_types.U256 Remaining gas after execution. logs : Tuple[ethereum.blocks.Log, ...] Logs generated during execution.

def process_transaction(env: ethereum.homestead.vm.Environmentethereum.dao_fork.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...]]:
643
    """
644
    Execute a transaction against the provided environment.
645
646
    This function processes the actions needed to execute a transaction.
647
    It decrements the sender's account after calculating the gas fee and
648
    refunds them the proper amount after execution. Calling contracts,
649
    deploying code, and incrementing nonces are all examples of actions that
650
    happen within this function or from a call made within this function.
651
652
    Accounts that are marked for deletion are processed and destroyed after
653
    execution.
654
655
    Parameters
656
    ----------
657
    env :
658
        Environment for the Ethereum Virtual Machine.
659
    tx :
660
        Transaction to execute.
661
662
    Returns
663
    -------
664
    gas_left : `ethereum.base_types.U256`
665
        Remaining gas after execution.
666
    logs : `Tuple[ethereum.blocks.Log, ...]`
667
        Logs generated during execution.
668
    """
669
    if not validate_transaction(tx):
670
        raise InvalidBlock
671
672
    sender = env.origin
673
    sender_account = get_account(env.state, sender)
674
    gas_fee = tx.gas * tx.gas_price
675
    if sender_account.nonce != tx.nonce:
676
        raise InvalidBlock
677
    if Uint(sender_account.balance) < gas_fee + Uint(tx.value):
678
        raise InvalidBlock
679
    if sender_account.code != bytearray():
680
        raise InvalidSenderError("not EOA")
681
682
    gas = tx.gas - calculate_intrinsic_cost(tx)
683
    increment_nonce(env.state, sender)
684
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
685
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
686
687
    message = prepare_message(
688
        sender,
689
        tx.to,
690
        tx.value,
691
        tx.data,
692
        gas,
693
        env,
694
    )
695
696
    output = process_message_call(message, env)
697
698
    gas_used = tx.gas - output.gas_left
699
    gas_refund = min(gas_used // Uint(2), Uint(output.refund_counter))
700
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
701
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
702
    total_gas_used = gas_used - gas_refund
703
704
    # refund gas
705
    sender_balance_after_refund = get_account(
706
        env.state, sender
707
    ).balance + U256(gas_refund_amount)
708
    set_account_balance(env.state, sender, sender_balance_after_refund)
709
710
    # transfer miner fees
711
    coinbase_balance_after_mining_fee = get_account(
712
        env.state, env.coinbase
713
    ).balance + U256(transaction_fee)
714
    set_account_balance(
715
        env.state, env.coinbase, coinbase_balance_after_mining_fee
716
    )
717
718
    for address in output.accounts_to_delete:
719
        destroy_account(env.state, address)
720
721
    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:
725
    """
726
    Verifies a transaction.
727
728
    The gas in a transaction gets used to pay for the intrinsic cost of
729
    operations, therefore if there is insufficient gas then it would not
730
    be possible to execute a transaction and it will be declared invalid.
731
732
    Additionally, the nonce of a transaction must not equal or exceed the
733
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
734
    In practice, defining the limit as ``2**64-1`` has no impact because
735
    sending ``2**64-1`` transactions is improbable. It's not strictly
736
    impossible though, ``2**64-1`` transactions is the entire capacity of the
737
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
738
739
    Parameters
740
    ----------
741
    tx :
742
        Transaction to validate.
743
744
    Returns
745
    -------
746
    verified : `bool`
747
        True if the transaction can be executed, or False otherwise.
748
    """
749
    if calculate_intrinsic_cost(tx) > Uint(tx.gas):
750
        return False
751
    if tx.nonce >= U256(U64.MAX_VALUE):
752
        return False
753
    return True

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:
757
    """
758
    Calculates the gas that is charged before execution is started.
759
760
    The intrinsic cost of the transaction is charged before execution has
761
    begun. Functions/operations in the EVM cost money to execute so this
762
    intrinsic cost is for the operations that need to be paid for as part of
763
    the transaction. Data transfer, for example, is part of this intrinsic
764
    cost. It costs ether to send data over the wire and that ether is
765
    accounted for in the intrinsic cost calculated in this function. This
766
    intrinsic cost must be calculated and paid for before execution in order
767
    for all operations to be implemented.
768
769
    Parameters
770
    ----------
771
    tx :
772
        Transaction to compute the intrinsic cost of.
773
774
    Returns
775
    -------
776
    verified : `ethereum.base_types.Uint`
777
        The intrinsic cost of the transaction.
778
    """
779
    data_cost = 0
780
781
    for byte in tx.data:
782
        if byte == 0:
783
            data_cost += TX_DATA_COST_PER_ZERO
784
        else:
785
            data_cost += TX_DATA_COST_PER_NON_ZERO
786
787
    if tx.to == Bytes0(b""):
788
        create_cost = TX_CREATE_COST
789
    else:
790
        create_cost = 0
791
792
    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.

Returns

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

def recover_sender(tx: Transaction) -> Address:
796
    """
797
    Extracts the sender address from a transaction.
798
799
    The v, r, and s values are the three parts that make up the signature
800
    of a transaction. In order to recover the sender of a transaction the two
801
    components needed are the signature (``v``, ``r``, and ``s``) and the
802
    signing hash of the transaction. The sender's public key can be obtained
803
    with these two values and therefore the sender address can be retrieved.
804
805
    Parameters
806
    ----------
807
    tx :
808
        Transaction of interest.
809
810
    Returns
811
    -------
812
    sender : `ethereum.fork_types.Address`
813
        The address of the account that signed the transaction.
814
    """
815
    v, r, s = tx.v, tx.r, tx.s
816
    if v != 27 and v != 28:
817
        raise InvalidBlock
818
    if U256(0) >= r or r >= SECP256K1N:
819
        raise InvalidBlock
820
    if U256(0) >= s or s > SECP256K1N // U256(2):
821
        raise InvalidBlock
822
823
    public_key = secp256k1_recover(r, s, v - U256(27), signing_hash(tx))
824
    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:
828
    """
829
    Compute the hash of a transaction used in the signature.
830
831
    The values that are used to compute the signing hash set the rules for a
832
    transaction. For example, signing over the gas sets a limit for the
833
    amount of money that is allowed to be pulled out of the sender's account.
834
835
    Parameters
836
    ----------
837
    tx :
838
        Transaction of interest.
839
840
    Returns
841
    -------
842
    hash : `ethereum.crypto.hash.Hash32`
843
        Hash of the transaction.
844
    """
845
    return keccak256(
846
        rlp.encode(
847
            (
848
                tx.nonce,
849
                tx.gas_price,
850
                tx.gas,
851
                tx.to,
852
                tx.value,
853
                tx.data,
854
            )
855
        )
856
    )

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:
860
    """
861
    Computes the hash of a block header.
862
863
    The header hash of a block is the canonical hash that is used to refer
864
    to a specific block and completely distinguishes a block from another.
865
866
    ``keccak256`` is a function that produces a 256 bit hash of any input.
867
    It also takes in any number of bytes as an input and produces a single
868
    hash for them. A hash is a completely unique output for a single input.
869
    So an input corresponds to one unique hash that can be used to identify
870
    the input exactly.
871
872
    Prior to using the ``keccak256`` hash function, the header must be
873
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
874
    RLP encoding the header converts it into a space-efficient format that
875
    allows for easy transfer of data between nodes. The purpose of RLP is to
876
    encode arbitrarily nested arrays of binary data, and RLP is the primary
877
    encoding method used to serialize objects in Ethereum's execution layer.
878
    The only purpose of RLP is to encode structure; encoding specific data
879
    types (e.g. strings, floats) is left up to higher-order protocols.
880
881
    Parameters
882
    ----------
883
    header :
884
        Header of interest.
885
886
    Returns
887
    -------
888
    hash : `ethereum.crypto.hash.Hash32`
889
        Hash of the header.
890
    """
891
    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:
895
    """
896
    Validates the gas limit for a block.
897
898
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
899
    quotient of the parent block's gas limit and the
900
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
901
    passed through as a parameter is greater than or equal to the *sum* of
902
    the parent's gas and the adjustment delta then the limit for gas is too
903
    high and fails this function's check. Similarly, if the limit is less
904
    than or equal to the *difference* of the parent's gas and the adjustment
905
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
906
    check fails because the gas limit doesn't allow for a sufficient or
907
    reasonable amount of gas to be used on a block.
908
909
    Parameters
910
    ----------
911
    gas_limit :
912
        Gas limit to validate.
913
914
    parent_gas_limit :
915
        Gas limit of the parent block.
916
917
    Returns
918
    -------
919
    check : `bool`
920
        True if gas limit constraints are satisfied, False otherwise.
921
    """
922
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
923
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
924
        return False
925
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
926
        return False
927
    if gas_limit < GAS_LIMIT_MINIMUM:
928
        return False
929
930
    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:
939
    """
940
    Computes difficulty of a block using its header and parent header.
941
942
    The difficulty is determined by the time the block was created after its
943
    parent. The ``offset`` is calculated using the parent block's difficulty,
944
    ``parent_difficulty``, and the timestamp between blocks. This offset is
945
    then added to the parent difficulty and is stored as the ``difficulty``
946
    variable. If the time between the block and its parent is too short, the
947
    offset will result in a positive number thus making the sum of
948
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
949
    avoid mass forking. But, if the time is long enough, then the offset
950
    results in a negative value making the block less difficult than
951
    its parent.
952
953
    The base standard for a block's difficulty is the predefined value
954
    set for the genesis block since it has no parent. So, a block
955
    can't be less difficult than the genesis block, therefore each block's
956
    difficulty is set to the maximum value between the calculated
957
    difficulty and the ``GENESIS_DIFFICULTY``.
958
959
    Parameters
960
    ----------
961
    block_number :
962
        Block number of the block.
963
    block_timestamp :
964
        Timestamp of the block.
965
    parent_timestamp :
966
        Timestamp of the parent block.
967
    parent_difficulty :
968
        difficulty of the parent block.
969
970
    Returns
971
    -------
972
    difficulty : `ethereum.base_types.Uint`
973
        Computed difficulty for a block.
974
    """
975
    offset = (
976
        int(parent_difficulty)
977
        // 2048
978
        * max(1 - int(block_timestamp - parent_timestamp) // 10, -99)
979
    )
980
    difficulty = int(parent_difficulty) + offset
981
    # Historical Note: The difficulty bomb was not present in Ethereum at the
982
    # start of Frontier, but was added shortly after launch. However since the
983
    # bomb has no effect prior to block 200000 we pretend it existed from
984
    # genesis.
985
    # See https://github.com/ethereum/go-ethereum/pull/1588
986
    num_bomb_periods = (int(block_number) // 100000) - 2
987
    if num_bomb_periods >= 0:
988
        difficulty += 2**num_bomb_periods
989
990
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
991
    # the bomb. This bug does not matter because the difficulty is always much
992
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
993
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))