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

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

GAS_LIMIT_ADJUSTMENT_FACTOR

53
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

54
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

55
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

56
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

59
@dataclass
class BlockChain:

blocks

65
    blocks: List[Block]

state

66
    state: State

chain_id

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

385
@dataclass
class ApplyBodyOutput:

block_gas_used

405
    block_gas_used: Uint

transactions_root

406
    transactions_root: Root

receipt_root

407
    receipt_root: Root

block_logs_bloom

408
    block_logs_bloom: Bloom

state_root

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

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:
522
    """
523
    Validates the ommers mentioned in the block.
524
525
    An ommer block is a block that wasn't canonically added to the
526
    blockchain because it wasn't validated as fast as the canonical block
527
    but was mined at the same time.
528
529
    To be considered valid, the ommers must adhere to the rules defined in
530
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
531
    there cannot be duplicate ommers in a block. Many of the other ommer
532
    constraints are listed in the in-line comments of this function.
533
534
    Parameters
535
    ----------
536
    ommers :
537
        List of ommers mentioned in the current block.
538
    block_header:
539
        The header of current block.
540
    chain :
541
        History and current state.
542
    """
543
    block_hash = rlp.rlp_hash(block_header)
544
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
545
        raise InvalidBlock
546
547
    if len(ommers) == 0:
548
        # Nothing to validate
549
        return
550
551
    # Check that each ommer satisfies the constraints of a header
552
    for ommer in ommers:
553
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
554
            raise InvalidBlock
555
        ommer_parent_header = chain.blocks[
556
            -(block_header.number - ommer.number) - 1
557
        ].header
558
        validate_header(ommer, ommer_parent_header)
559
    if len(ommers) > 2:
560
        raise InvalidBlock
561
562
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
563
    if len(ommers_hashes) != len(set(ommers_hashes)):
564
        raise InvalidBlock
565
566
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
567
    recent_canonical_block_hashes = {
568
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
569
    }
570
    recent_ommers_hashes: Set[Hash32] = set()
571
    for block in recent_canonical_blocks:
572
        recent_ommers_hashes = recent_ommers_hashes.union(
573
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
574
        )
575
576
    for ommer_index, ommer in enumerate(ommers):
577
        ommer_hash = ommers_hashes[ommer_index]
578
        if ommer_hash == block_hash:
579
            raise InvalidBlock
580
        if ommer_hash in recent_canonical_block_hashes:
581
            raise InvalidBlock
582
        if ommer_hash in recent_ommers_hashes:
583
            raise InvalidBlock
584
585
        # Ommer age with respect to the current block. For example, an age of
586
        # 1 indicates that the ommer is a sibling of previous block.
587
        ommer_age = block_header.number - ommer.number
588
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
589
            raise InvalidBlock
590
        if ommer.parent_hash not in recent_canonical_block_hashes:
591
            raise InvalidBlock
592
        if ommer.parent_hash == block_header.parent_hash:
593
            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:
602
    """
603
    Pay rewards to the block miner as well as the ommers miners.
604
605
    The miner of the canonical block is rewarded with the predetermined
606
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
607
    number of ommer blocks that were mined around the same time, and included
608
    in the canonical block's header. An ommer block is a block that wasn't
609
    added to the canonical blockchain because it wasn't validated as fast as
610
    the accepted block but was mined at the same time. Although not all blocks
611
    that are mined are added to the canonical chain, miners are still paid a
612
    reward for their efforts. This reward is called an ommer reward and is
613
    calculated based on the number associated with the ommer block that they
614
    mined.
615
616
    Parameters
617
    ----------
618
    state :
619
        Current account state.
620
    block_number :
621
        Position of the block within the chain.
622
    coinbase :
623
        Address of account which receives block reward and transaction fees.
624
    ommers :
625
        List of ommers mentioned in the current block.
626
    """
627
    ommer_count = U256(len(ommers))
628
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
629
    create_ether(state, coinbase, miner_reward)
630
631
    for ommer in ommers:
632
        # Ommer age with respect to the current block.
633
        ommer_age = U256(block_number - ommer.number)
634
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
635
        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, ...]]:
641
    """
642
    Execute a transaction against the provided environment.
643
644
    This function processes the actions needed to execute a transaction.
645
    It decrements the sender's account after calculating the gas fee and
646
    refunds them the proper amount after execution. Calling contracts,
647
    deploying code, and incrementing nonces are all examples of actions that
648
    happen within this function or from a call made within this function.
649
650
    Accounts that are marked for deletion are processed and destroyed after
651
    execution.
652
653
    Parameters
654
    ----------
655
    env :
656
        Environment for the Ethereum Virtual Machine.
657
    tx :
658
        Transaction to execute.
659
660
    Returns
661
    -------
662
    gas_left : `ethereum.base_types.U256`
663
        Remaining gas after execution.
664
    logs : `Tuple[ethereum.blocks.Log, ...]`
665
        Logs generated during execution.
666
    """
667
    if not validate_transaction(tx):
668
        raise InvalidBlock
669
670
    sender = env.origin
671
    sender_account = get_account(env.state, sender)
672
    gas_fee = tx.gas * tx.gas_price
673
    if sender_account.nonce != tx.nonce:
674
        raise InvalidBlock
675
    if Uint(sender_account.balance) < gas_fee + Uint(tx.value):
676
        raise InvalidBlock
677
    if sender_account.code != bytearray():
678
        raise InvalidSenderError("not EOA")
679
680
    gas = tx.gas - calculate_intrinsic_cost(tx)
681
    increment_nonce(env.state, sender)
682
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
683
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
684
685
    message = prepare_message(
686
        sender,
687
        tx.to,
688
        tx.value,
689
        tx.data,
690
        gas,
691
        env,
692
    )
693
694
    output = process_message_call(message, env)
695
696
    gas_used = tx.gas - output.gas_left
697
    gas_refund = min(gas_used // Uint(2), Uint(output.refund_counter))
698
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
699
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
700
    total_gas_used = gas_used - gas_refund
701
702
    # refund gas
703
    sender_balance_after_refund = get_account(
704
        env.state, sender
705
    ).balance + U256(gas_refund_amount)
706
    set_account_balance(env.state, sender, sender_balance_after_refund)
707
708
    # transfer miner fees
709
    coinbase_balance_after_mining_fee = get_account(
710
        env.state, env.coinbase
711
    ).balance + U256(transaction_fee)
712
    set_account_balance(
713
        env.state, env.coinbase, coinbase_balance_after_mining_fee
714
    )
715
716
    for address in output.accounts_to_delete:
717
        destroy_account(env.state, address)
718
719
    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:
723
    """
724
    Computes the hash of a block header.
725
726
    The header hash of a block is the canonical hash that is used to refer
727
    to a specific block and completely distinguishes a block from another.
728
729
    ``keccak256`` is a function that produces a 256 bit hash of any input.
730
    It also takes in any number of bytes as an input and produces a single
731
    hash for them. A hash is a completely unique output for a single input.
732
    So an input corresponds to one unique hash that can be used to identify
733
    the input exactly.
734
735
    Prior to using the ``keccak256`` hash function, the header must be
736
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
737
    RLP encoding the header converts it into a space-efficient format that
738
    allows for easy transfer of data between nodes. The purpose of RLP is to
739
    encode arbitrarily nested arrays of binary data, and RLP is the primary
740
    encoding method used to serialize objects in Ethereum's execution layer.
741
    The only purpose of RLP is to encode structure; encoding specific data
742
    types (e.g. strings, floats) is left up to higher-order protocols.
743
744
    Parameters
745
    ----------
746
    header :
747
        Header of interest.
748
749
    Returns
750
    -------
751
    hash : `ethereum.crypto.hash.Hash32`
752
        Hash of the header.
753
    """
754
    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:
758
    """
759
    Validates the gas limit for a block.
760
761
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
762
    quotient of the parent block's gas limit and the
763
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
764
    passed through as a parameter is greater than or equal to the *sum* of
765
    the parent's gas and the adjustment delta then the limit for gas is too
766
    high and fails this function's check. Similarly, if the limit is less
767
    than or equal to the *difference* of the parent's gas and the adjustment
768
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
769
    check fails because the gas limit doesn't allow for a sufficient or
770
    reasonable amount of gas to be used on a block.
771
772
    Parameters
773
    ----------
774
    gas_limit :
775
        Gas limit to validate.
776
777
    parent_gas_limit :
778
        Gas limit of the parent block.
779
780
    Returns
781
    -------
782
    check : `bool`
783
        True if gas limit constraints are satisfied, False otherwise.
784
    """
785
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
786
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
787
        return False
788
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
789
        return False
790
    if gas_limit < GAS_LIMIT_MINIMUM:
791
        return False
792
793
    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:
802
    """
803
    Computes difficulty of a block using its header and parent header.
804
805
    The difficulty is determined by the time the block was created after its
806
    parent. The ``offset`` is calculated using the parent block's difficulty,
807
    ``parent_difficulty``, and the timestamp between blocks. This offset is
808
    then added to the parent difficulty and is stored as the ``difficulty``
809
    variable. If the time between the block and its parent is too short, the
810
    offset will result in a positive number thus making the sum of
811
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
812
    avoid mass forking. But, if the time is long enough, then the offset
813
    results in a negative value making the block less difficult than
814
    its parent.
815
816
    The base standard for a block's difficulty is the predefined value
817
    set for the genesis block since it has no parent. So, a block
818
    can't be less difficult than the genesis block, therefore each block's
819
    difficulty is set to the maximum value between the calculated
820
    difficulty and the ``GENESIS_DIFFICULTY``.
821
822
    Parameters
823
    ----------
824
    block_number :
825
        Block number of the block.
826
    block_timestamp :
827
        Timestamp of the block.
828
    parent_timestamp :
829
        Timestamp of the parent block.
830
    parent_difficulty :
831
        difficulty of the parent block.
832
833
    Returns
834
    -------
835
    difficulty : `ethereum.base_types.Uint`
836
        Computed difficulty for a block.
837
    """
838
    offset = (
839
        int(parent_difficulty)
840
        // 2048
841
        * max(1 - int(block_timestamp - parent_timestamp) // 10, -99)
842
    )
843
    difficulty = int(parent_difficulty) + offset
844
    # Historical Note: The difficulty bomb was not present in Ethereum at the
845
    # start of Frontier, but was added shortly after launch. However since the
846
    # bomb has no effect prior to block 200000 we pretend it existed from
847
    # genesis.
848
    # See https://github.com/ethereum/go-ethereum/pull/1588
849
    num_bomb_periods = (int(block_number) // 100000) - 2
850
    if num_bomb_periods >= 0:
851
        difficulty += 2**num_bomb_periods
852
853
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
854
    # the bomb. This bug does not matter because the difficulty is always much
855
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
856
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))