ethereum.dao_fork.fork

.. _dao-fork:

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

54
GAS_LIMIT_ADJUSTMENT_FACTOR = 1024

GAS_LIMIT_MINIMUM

55
GAS_LIMIT_MINIMUM = 5000

MINIMUM_DIFFICULTY

56
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

57
MAX_OMMER_DEPTH = 6

BlockChain

History and current state of the block chain.

60
@dataclass
class BlockChain:

blocks

66
    blocks: List[Block]

state

67
    state: State

chain_id

68
    chain_id: U64

apply_fork

Transforms the state from the previous hard fork (old) into the block chain object for this hard fork and returns it.

When forks need to implement an irregular state transition, this function is used to handle the irregularity.

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

382
@dataclass
class ApplyBodyOutput:

block_gas_used

402
    block_gas_used: Uint

transactions_root

403
    transactions_root: Root

receipt_root

404
    receipt_root: Root

block_logs_bloom

405
    block_logs_bloom: Bloom

state_root

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

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:
519
    """
520
    Validates the ommers mentioned in the block.
521
522
    An ommer block is a block that wasn't canonically added to the
523
    blockchain because it wasn't validated as fast as the canonical block
524
    but was mined at the same time.
525
526
    To be considered valid, the ommers must adhere to the rules defined in
527
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
528
    there cannot be duplicate ommers in a block. Many of the other ommer
529
    constraints are listed in the in-line comments of this function.
530
531
    Parameters
532
    ----------
533
    ommers :
534
        List of ommers mentioned in the current block.
535
    block_header:
536
        The header of current block.
537
    chain :
538
        History and current state.
539
    """
540
    block_hash = rlp.rlp_hash(block_header)
541
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
542
        raise InvalidBlock
543
544
    if len(ommers) == 0:
545
        # Nothing to validate
546
        return
547
548
    # Check that each ommer satisfies the constraints of a header
549
    for ommer in ommers:
550
        if 1 > ommer.number or ommer.number >= block_header.number:
551
            raise InvalidBlock
552
        ommer_parent_header = chain.blocks[
553
            -(block_header.number - ommer.number) - 1
554
        ].header
555
        validate_header(ommer, ommer_parent_header)
556
    if len(ommers) > 2:
557
        raise InvalidBlock
558
559
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
560
    if len(ommers_hashes) != len(set(ommers_hashes)):
561
        raise InvalidBlock
562
563
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + 1) :]
564
    recent_canonical_block_hashes = {
565
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
566
    }
567
    recent_ommers_hashes: Set[Hash32] = set()
568
    for block in recent_canonical_blocks:
569
        recent_ommers_hashes = recent_ommers_hashes.union(
570
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
571
        )
572
573
    for ommer_index, ommer in enumerate(ommers):
574
        ommer_hash = ommers_hashes[ommer_index]
575
        if ommer_hash == block_hash:
576
            raise InvalidBlock
577
        if ommer_hash in recent_canonical_block_hashes:
578
            raise InvalidBlock
579
        if ommer_hash in recent_ommers_hashes:
580
            raise InvalidBlock
581
582
        # Ommer age with respect to the current block. For example, an age of
583
        # 1 indicates that the ommer is a sibling of previous block.
584
        ommer_age = block_header.number - ommer.number
585
        if 1 > ommer_age or ommer_age > MAX_OMMER_DEPTH:
586
            raise InvalidBlock
587
        if ommer.parent_hash not in recent_canonical_block_hashes:
588
            raise InvalidBlock
589
        if ommer.parent_hash == block_header.parent_hash:
590
            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:
599
    """
600
    Pay rewards to the block miner as well as the ommers miners.
601
602
    The miner of the canonical block is rewarded with the predetermined
603
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
604
    number of ommer blocks that were mined around the same time, and included
605
    in the canonical block's header. An ommer block is a block that wasn't
606
    added to the canonical blockchain because it wasn't validated as fast as
607
    the accepted block but was mined at the same time. Although not all blocks
608
    that are mined are added to the canonical chain, miners are still paid a
609
    reward for their efforts. This reward is called an ommer reward and is
610
    calculated based on the number associated with the ommer block that they
611
    mined.
612
613
    Parameters
614
    ----------
615
    state :
616
        Current account state.
617
    block_number :
618
        Position of the block within the chain.
619
    coinbase :
620
        Address of account which receives block reward and transaction fees.
621
    ommers :
622
        List of ommers mentioned in the current block.
623
    """
624
    miner_reward = BLOCK_REWARD + (len(ommers) * (BLOCK_REWARD // 32))
625
    create_ether(state, coinbase, miner_reward)
626
627
    for ommer in ommers:
628
        # Ommer age with respect to the current block.
629
        ommer_age = U256(block_number - ommer.number)
630
        ommer_miner_reward = ((8 - ommer_age) * BLOCK_REWARD) // 8
631
        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.dao_fork.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...]]:
637
    """
638
    Execute a transaction against the provided environment.
639
640
    This function processes the actions needed to execute a transaction.
641
    It decrements the sender's account after calculating the gas fee and
642
    refunds them the proper amount after execution. Calling contracts,
643
    deploying code, and incrementing nonces are all examples of actions that
644
    happen within this function or from a call made within this function.
645
646
    Accounts that are marked for deletion are processed and destroyed after
647
    execution.
648
649
    Parameters
650
    ----------
651
    env :
652
        Environment for the Ethereum Virtual Machine.
653
    tx :
654
        Transaction to execute.
655
656
    Returns
657
    -------
658
    gas_left : `ethereum.base_types.U256`
659
        Remaining gas after execution.
660
    logs : `Tuple[ethereum.blocks.Log, ...]`
661
        Logs generated during execution.
662
    """
663
    if not validate_transaction(tx):
664
        raise InvalidBlock
665
666
    sender = env.origin
667
    sender_account = get_account(env.state, sender)
668
    gas_fee = tx.gas * tx.gas_price
669
    if sender_account.nonce != tx.nonce:
670
        raise InvalidBlock
671
    if sender_account.balance < gas_fee + tx.value:
672
        raise InvalidBlock
673
    if sender_account.code != bytearray():
674
        raise InvalidBlock
675
676
    gas = tx.gas - calculate_intrinsic_cost(tx)
677
    increment_nonce(env.state, sender)
678
    sender_balance_after_gas_fee = sender_account.balance - gas_fee
679
    set_account_balance(env.state, sender, sender_balance_after_gas_fee)
680
681
    message = prepare_message(
682
        sender,
683
        tx.to,
684
        tx.value,
685
        tx.data,
686
        gas,
687
        env,
688
    )
689
690
    output = process_message_call(message, env)
691
692
    gas_used = tx.gas - output.gas_left
693
    gas_refund = min(gas_used // 2, output.refund_counter)
694
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
695
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
696
    total_gas_used = gas_used - gas_refund
697
698
    # refund gas
699
    sender_balance_after_refund = (
700
        get_account(env.state, sender).balance + gas_refund_amount
701
    )
702
    set_account_balance(env.state, sender, sender_balance_after_refund)
703
704
    # transfer miner fees
705
    coinbase_balance_after_mining_fee = (
706
        get_account(env.state, env.coinbase).balance + transaction_fee
707
    )
708
    set_account_balance(
709
        env.state, env.coinbase, coinbase_balance_after_mining_fee
710
    )
711
712
    for address in output.accounts_to_delete:
713
        destroy_account(env.state, address)
714
715
    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:
719
    """
720
    Verifies a transaction.
721
722
    The gas in a transaction gets used to pay for the intrinsic cost of
723
    operations, therefore if there is insufficient gas then it would not
724
    be possible to execute a transaction and it will be declared invalid.
725
726
    Additionally, the nonce of a transaction must not equal or exceed the
727
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
728
    In practice, defining the limit as ``2**64-1`` has no impact because
729
    sending ``2**64-1`` transactions is improbable. It's not strictly
730
    impossible though, ``2**64-1`` transactions is the entire capacity of the
731
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
732
733
    Parameters
734
    ----------
735
    tx :
736
        Transaction to validate.
737
738
    Returns
739
    -------
740
    verified : `bool`
741
        True if the transaction can be executed, or False otherwise.
742
    """
743
    return calculate_intrinsic_cost(tx) <= tx.gas and tx.nonce < 2**64 - 1

calculate_intrinsic_cost

Calculates the gas that is charged before execution is started.

The intrinsic cost of the transaction is charged before execution has begun. Functions/operations in the EVM cost money to execute so this intrinsic cost is for the operations that need to be paid for as part of the transaction. Data transfer, for example, is part of this intrinsic cost. It costs ether to send data over the wire and that ether is accounted for in the intrinsic cost calculated in this function. This intrinsic cost must be calculated and paid for before execution in order for all operations to be implemented.

Parameters

tx : Transaction to compute the intrinsic cost of.

Returns

verified : ethereum.base_types.Uint The intrinsic cost of the transaction.

def calculate_intrinsic_cost(tx: Transaction) -> Uint:
747
    """
748
    Calculates the gas that is charged before execution is started.
749
750
    The intrinsic cost of the transaction is charged before execution has
751
    begun. Functions/operations in the EVM cost money to execute so this
752
    intrinsic cost is for the operations that need to be paid for as part of
753
    the transaction. Data transfer, for example, is part of this intrinsic
754
    cost. It costs ether to send data over the wire and that ether is
755
    accounted for in the intrinsic cost calculated in this function. This
756
    intrinsic cost must be calculated and paid for before execution in order
757
    for all operations to be implemented.
758
759
    Parameters
760
    ----------
761
    tx :
762
        Transaction to compute the intrinsic cost of.
763
764
    Returns
765
    -------
766
    verified : `ethereum.base_types.Uint`
767
        The intrinsic cost of the transaction.
768
    """
769
    data_cost = 0
770
771
    for byte in tx.data:
772
        if byte == 0:
773
            data_cost += TX_DATA_COST_PER_ZERO
774
        else:
775
            data_cost += TX_DATA_COST_PER_NON_ZERO
776
777
    if tx.to == Bytes0(b""):
778
        create_cost = TX_CREATE_COST
779
    else:
780
        create_cost = 0
781
782
    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:
786
    """
787
    Extracts the sender address from a transaction.
788
789
    The v, r, and s values are the three parts that make up the signature
790
    of a transaction. In order to recover the sender of a transaction the two
791
    components needed are the signature (``v``, ``r``, and ``s``) and the
792
    signing hash of the transaction. The sender's public key can be obtained
793
    with these two values and therefore the sender address can be retrieved.
794
795
    Parameters
796
    ----------
797
    tx :
798
        Transaction of interest.
799
800
    Returns
801
    -------
802
    sender : `ethereum.fork_types.Address`
803
        The address of the account that signed the transaction.
804
    """
805
    v, r, s = tx.v, tx.r, tx.s
806
    if v != 27 and v != 28:
807
        raise InvalidBlock
808
    if 0 >= r or r >= SECP256K1N:
809
        raise InvalidBlock
810
    if 0 >= s or s > SECP256K1N // 2:
811
        raise InvalidBlock
812
813
    public_key = secp256k1_recover(r, s, v - 27, signing_hash(tx))
814
    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:
818
    """
819
    Compute the hash of a transaction used in the signature.
820
821
    The values that are used to compute the signing hash set the rules for a
822
    transaction. For example, signing over the gas sets a limit for the
823
    amount of money that is allowed to be pulled out of the sender's account.
824
825
    Parameters
826
    ----------
827
    tx :
828
        Transaction of interest.
829
830
    Returns
831
    -------
832
    hash : `ethereum.crypto.hash.Hash32`
833
        Hash of the transaction.
834
    """
835
    return keccak256(
836
        rlp.encode(
837
            (
838
                tx.nonce,
839
                tx.gas_price,
840
                tx.gas,
841
                tx.to,
842
                tx.value,
843
                tx.data,
844
            )
845
        )
846
    )

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