ethereum.tangerine_whistle.forkethereum.spurious_dragon.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.

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

Returns

sender_address : The sender of the transaction.

Raises

InvalidBlock : If the transaction is not includable.

def check_transaction(tx: Transaction, ​​gas_available: Uint, ​​chain_id: U64) -> Address:
309
    """
310
    Check if the transaction is includable in the block.
311
312
    Parameters
313
    ----------
314
    tx :
315
        The transaction.
316
    gas_available :
317
        The gas remaining in the block.
318
    chain_id :
319
        The ID of the current chain.
320
321
    Returns
322
    -------
323
    sender_address :
324
        The sender of the transaction.
325
326
    Raises
327
    ------
328
    InvalidBlock :
329
        If the transaction is not includable.
330
    """
331
    if tx.gas > gas_available:
332
        raise InvalidBlock
328
    sender_address = recover_sender(tx)
333
    sender_address = recover_sender(chain_id, tx)
334
335
    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:
344
    """
345
    Make the receipt for a transaction that was executed.
346
347
    Parameters
348
    ----------
349
    tx :
350
        The executed transaction.
351
    post_state :
352
        The state root immediately after this transaction.
353
    cumulative_gas_used :
354
        The total gas used so far in the block after the transaction was
355
        executed.
356
    logs :
357
        The logs produced by the transaction.
358
359
    Returns
360
    -------
361
    receipt :
362
        The receipt for the transaction.
363
    """
364
    receipt = Receipt(
365
        post_state=post_state,
366
        cumulative_gas_used=cumulative_gas_used,
367
        bloom=logs_bloom(logs),
368
        logs=logs,
369
    )
370
371
    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.

374
@dataclass
class ApplyBodyOutput:

block_gas_used

394
    block_gas_used: Uint

transactions_root

395
    transactions_root: Root

receipt_root

396
    receipt_root: Root

block_logs_bloom

397
    block_logs_bloom: Bloom

state_root

398
    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.) chain_id : ID of the executing chain.

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

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

Returns

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

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

signing_hash_pre155

Compute the hash of a transaction used in a legacy (pre EIP 155) signature.

Parameters

tx : Transaction of interest.

Returns

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

def signing_hash_pre155(tx: Transaction) -> Hash32:
835
    """
836
    Compute the hash of a transaction used in a legacy (pre EIP 155) signature.
837
838
    Parameters
839
    ----------
840
    tx :
841
        Transaction of interest.
842
843
    Returns
844
    -------
845
    hash : `ethereum.crypto.hash.Hash32`
846
        Hash of the transaction.
847
    """
848
    return keccak256(
849
        rlp.encode(
850
            (
851
                tx.nonce,
852
                tx.gas_price,
853
                tx.gas,
854
                tx.to,
855
                tx.value,
856
                tx.data,
857
            )
858
        )
859
    )

signing_hash_155

Compute the hash of a transaction used in a EIP 155 signature.

Parameters

tx : Transaction of interest. chain_id : The id of the current chain.

Returns

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

def signing_hash_155(tx: Transaction, ​​chain_id: U64) -> Hash32:
863
    """
864
    Compute the hash of a transaction used in a EIP 155 signature.
865
866
    Parameters
867
    ----------
868
    tx :
869
        Transaction of interest.
870
    chain_id :
871
        The id of the current chain.
872
873
    Returns
874
    -------
875
    hash : `ethereum.crypto.hash.Hash32`
876
        Hash of the transaction.
877
    """
878
    return keccak256(
879
        rlp.encode(
880
            (
881
                tx.nonce,
882
                tx.gas_price,
883
                tx.gas,
884
                tx.to,
885
                tx.value,
886
                tx.data,
887
                chain_id,
888
                Uint(0),
889
                Uint(0),
890
            )
891
        )
892
    )

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