ethereum.istanbul.forkethereum.muir_glacier.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

51
BLOCK_REWARD = U256(2 * 10**18)

GAS_LIMIT_ADJUSTMENT_FACTOR

52
GAS_LIMIT_ADJUSTMENT_FACTOR = 1024

GAS_LIMIT_MINIMUM

53
GAS_LIMIT_MINIMUM = 5000

MINIMUM_DIFFICULTY

54
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

55
MAX_OMMER_DEPTH = 6

BOMB_DELAY_BLOCKS

56
BOMB_DELAY_BLOCKS = 5000000
56
BOMB_DELAY_BLOCKS = 9000000

EMPTY_OMMER_HASH

57
EMPTY_OMMER_HASH = keccak256(rlp.encode([]))

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

make_receipt

Make the receipt for a transaction that was executed.

Parameters

tx : The executed transaction. error : Error in the top level frame of the transaction, if any. 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, ​​error: Optional[Exception], ​​cumulative_gas_used: Uint, ​​logs: Tuple[Log, ...]) -> Receipt:
343
    """
344
    Make the receipt for a transaction that was executed.
345
346
    Parameters
347
    ----------
348
    tx :
349
        The executed transaction.
350
    error :
351
        Error in the top level frame of the transaction, if any.
352
    cumulative_gas_used :
353
        The total gas used so far in the block after the transaction was
354
        executed.
355
    logs :
356
        The logs produced by the transaction.
357
358
    Returns
359
    -------
360
    receipt :
361
        The receipt for the transaction.
362
    """
363
    receipt = Receipt(
364
        succeeded=error is None,
365
        cumulative_gas_used=cumulative_gas_used,
366
        bloom=logs_bloom(logs),
367
        logs=logs,
368
    )
369
370
    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.

373
@dataclass
class ApplyBodyOutput:

block_gas_used

393
    block_gas_used: Uint

transactions_root

394
    transactions_root: Root

receipt_root

395
    receipt_root: Root

block_logs_bloom

396
    block_logs_bloom: Bloom

state_root

397
    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:
412
    """
413
    Executes a block.
414
415
    Many of the contents of a block are stored in data structures called
416
    tries. There is a transactions trie which is similar to a ledger of the
417
    transactions stored in the current block. There is also a receipts trie
418
    which stores the results of executing a transaction, like the post state
419
    and gas used. This function creates and executes the block that is to be
420
    added to the chain.
421
422
    Parameters
423
    ----------
424
    state :
425
        Current account state.
426
    block_hashes :
427
        List of hashes of the previous 256 blocks in the order of
428
        increasing block number.
429
    coinbase :
430
        Address of account which receives block reward and transaction fees.
431
    block_number :
432
        Position of the block within the chain.
433
    block_gas_limit :
434
        Initial amount of gas available for execution in this block.
435
    block_time :
436
        Time the block was produced, measured in seconds since the epoch.
437
    block_difficulty :
438
        Difficulty of the block.
439
    transactions :
440
        Transactions included in the block.
441
    ommers :
442
        Headers of ancestor blocks which are not direct parents (formerly
443
        uncles.)
444
    chain_id :
445
        ID of the executing chain.
446
447
    Returns
448
    -------
449
    apply_body_output : `ApplyBodyOutput`
450
        Output of applying the block body to the state.
451
    """
452
    gas_available = block_gas_limit
453
    transactions_trie: Trie[Bytes, Optional[Transaction]] = Trie(
454
        secured=False, default=None
455
    )
456
    receipts_trie: Trie[Bytes, Optional[Receipt]] = Trie(
457
        secured=False, default=None
458
    )
459
    block_logs: Tuple[Log, ...] = ()
460
461
    for i, tx in enumerate(transactions):
462
        trie_set(transactions_trie, rlp.encode(Uint(i)), tx)
463
464
        sender_address = check_transaction(tx, gas_available, chain_id)
465
466
        env = vm.Environment(
467
            caller=sender_address,
468
            origin=sender_address,
469
            block_hashes=block_hashes,
470
            coinbase=coinbase,
471
            number=block_number,
472
            gas_limit=block_gas_limit,
473
            gas_price=tx.gas_price,
474
            time=block_time,
475
            difficulty=block_difficulty,
476
            state=state,
477
            chain_id=chain_id,
478
            traces=[],
479
        )
480
481
        gas_used, logs, error = process_transaction(env, tx)
482
        gas_available -= gas_used
483
484
        receipt = make_receipt(
485
            tx, error, (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 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 + 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 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
    miner_reward = BLOCK_REWARD + (len(ommers) * (BLOCK_REWARD // 32))
620
    create_ether(state, coinbase, miner_reward)
621
622
    for ommer in ommers:
623
        # Ommer age with respect to the current block.
624
        ommer_age = U256(block_number - ommer.number)
625
        ommer_miner_reward = ((8 - ommer_age) * BLOCK_REWARD) // 8
626
        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.istanbul.vm.Environmentethereum.muir_glacier.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...], Optional[Exception]]:
632
    """
633
    Execute a transaction against the provided environment.
634
635
    This function processes the actions needed to execute a transaction.
636
    It decrements the sender's account after calculating the gas fee and
637
    refunds them the proper amount after execution. Calling contracts,
638
    deploying code, and incrementing nonces are all examples of actions that
639
    happen within this function or from a call made within this function.
640
641
    Accounts that are marked for deletion are processed and destroyed after
642
    execution.
643
644
    Parameters
645
    ----------
646
    env :
647
        Environment for the Ethereum Virtual Machine.
648
    tx :
649
        Transaction to execute.
650
651
    Returns
652
    -------
653
    gas_left : `ethereum.base_types.U256`
654
        Remaining gas after execution.
655
    logs : `Tuple[ethereum.blocks.Log, ...]`
656
        Logs generated during execution.
657
    """
658
    if not validate_transaction(tx):
659
        raise InvalidBlock
660
661
    sender = env.origin
662
    sender_account = get_account(env.state, sender)
663
    gas_fee = tx.gas * tx.gas_price
664
    if sender_account.nonce != tx.nonce:
665
        raise InvalidBlock
666
    if sender_account.balance < gas_fee + tx.value:
667
        raise InvalidBlock
668
    if sender_account.code != bytearray():
669
        raise InvalidBlock
670
671
    gas = tx.gas - calculate_intrinsic_cost(tx)
672
    increment_nonce(env.state, sender)
673
    sender_balance_after_gas_fee = sender_account.balance - gas_fee
674
    set_account_balance(env.state, sender, sender_balance_after_gas_fee)
675
676
    message = prepare_message(
677
        sender,
678
        tx.to,
679
        tx.value,
680
        tx.data,
681
        gas,
682
        env,
683
    )
684
685
    output = process_message_call(message, env)
686
687
    gas_used = tx.gas - output.gas_left
688
    gas_refund = min(gas_used // 2, output.refund_counter)
689
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
690
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
691
    total_gas_used = gas_used - gas_refund
692
693
    # refund gas
694
    sender_balance_after_refund = (
695
        get_account(env.state, sender).balance + gas_refund_amount
696
    )
697
    set_account_balance(env.state, sender, sender_balance_after_refund)
698
699
    # transfer miner fees
700
    coinbase_balance_after_mining_fee = (
701
        get_account(env.state, env.coinbase).balance + transaction_fee
702
    )
703
    if coinbase_balance_after_mining_fee != 0:
704
        set_account_balance(
705
            env.state, env.coinbase, coinbase_balance_after_mining_fee
706
        )
707
    elif account_exists_and_is_empty(env.state, env.coinbase):
708
        destroy_account(env.state, env.coinbase)
709
710
    for address in output.accounts_to_delete:
711
        destroy_account(env.state, address)
712
713
    for address in output.touched_accounts:
714
        if account_exists_and_is_empty(env.state, address):
715
            destroy_account(env.state, address)
716
717
    return total_gas_used, output.logs, output.error

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:
721
    """
722
    Verifies a transaction.
723
724
    The gas in a transaction gets used to pay for the intrinsic cost of
725
    operations, therefore if there is insufficient gas then it would not
726
    be possible to execute a transaction and it will be declared invalid.
727
728
    Additionally, the nonce of a transaction must not equal or exceed the
729
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
730
    In practice, defining the limit as ``2**64-1`` has no impact because
731
    sending ``2**64-1`` transactions is improbable. It's not strictly
732
    impossible though, ``2**64-1`` transactions is the entire capacity of the
733
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
734
735
    Parameters
736
    ----------
737
    tx :
738
        Transaction to validate.
739
740
    Returns
741
    -------
742
    verified : `bool`
743
        True if the transaction can be executed, or False otherwise.
744
    """
745
    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:
749
    """
750
    Calculates the gas that is charged before execution is started.
751
752
    The intrinsic cost of the transaction is charged before execution has
753
    begun. Functions/operations in the EVM cost money to execute so this
754
    intrinsic cost is for the operations that need to be paid for as part of
755
    the transaction. Data transfer, for example, is part of this intrinsic
756
    cost. It costs ether to send data over the wire and that ether is
757
    accounted for in the intrinsic cost calculated in this function. This
758
    intrinsic cost must be calculated and paid for before execution in order
759
    for all operations to be implemented.
760
761
    Parameters
762
    ----------
763
    tx :
764
        Transaction to compute the intrinsic cost of.
765
766
    Returns
767
    -------
768
    verified : `ethereum.base_types.Uint`
769
        The intrinsic cost of the transaction.
770
    """
771
    data_cost = 0
772
773
    for byte in tx.data:
774
        if byte == 0:
775
            data_cost += TX_DATA_COST_PER_ZERO
776
        else:
777
            data_cost += TX_DATA_COST_PER_NON_ZERO
778
779
    if tx.to == Bytes0(b""):
780
        create_cost = TX_CREATE_COST
781
    else:
782
        create_cost = 0
783
784
    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:
788
    """
789
    Extracts the sender address from a transaction.
790
791
    The v, r, and s values are the three parts that make up the signature
792
    of a transaction. In order to recover the sender of a transaction the two
793
    components needed are the signature (``v``, ``r``, and ``s``) and the
794
    signing hash of the transaction. The sender's public key can be obtained
795
    with these two values and therefore the sender address can be retrieved.
796
797
    Parameters
798
    ----------
799
    tx :
800
        Transaction of interest.
801
    chain_id :
802
        ID of the executing chain.
803
804
    Returns
805
    -------
806
    sender : `ethereum.fork_types.Address`
807
        The address of the account that signed the transaction.
808
    """
809
    v, r, s = tx.v, tx.r, tx.s
810
    if 0 >= r or r >= SECP256K1N:
811
        raise InvalidBlock
812
    if 0 >= s or s > SECP256K1N // 2:
813
        raise InvalidBlock
814
815
    if v == 27 or v == 28:
816
        public_key = secp256k1_recover(r, s, v - 27, signing_hash_pre155(tx))
817
    else:
818
        if v != 35 + chain_id * 2 and v != 36 + chain_id * 2:
819
            raise InvalidBlock
820
        public_key = secp256k1_recover(
821
            r, s, v - 35 - chain_id * 2, signing_hash_155(tx, chain_id)
822
        )
823
    return Address(keccak256(public_key)[12:32])

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:
827
    """
828
    Compute the hash of a transaction used in a legacy (pre EIP 155) signature.
829
830
    Parameters
831
    ----------
832
    tx :
833
        Transaction of interest.
834
835
    Returns
836
    -------
837
    hash : `ethereum.crypto.hash.Hash32`
838
        Hash of the transaction.
839
    """
840
    return keccak256(
841
        rlp.encode(
842
            (
843
                tx.nonce,
844
                tx.gas_price,
845
                tx.gas,
846
                tx.to,
847
                tx.value,
848
                tx.data,
849
            )
850
        )
851
    )

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:
855
    """
856
    Compute the hash of a transaction used in a EIP 155 signature.
857
858
    Parameters
859
    ----------
860
    tx :
861
        Transaction of interest.
862
    chain_id :
863
        The id of the current chain.
864
865
    Returns
866
    -------
867
    hash : `ethereum.crypto.hash.Hash32`
868
        Hash of the transaction.
869
    """
870
    return keccak256(
871
        rlp.encode(
872
            (
873
                tx.nonce,
874
                tx.gas_price,
875
                tx.gas,
876
                tx.to,
877
                tx.value,
878
                tx.data,
879
                chain_id,
880
                Uint(0),
881
                Uint(0),
882
            )
883
        )
884
    )

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:
888
    """
889
    Computes the hash of a block header.
890
891
    The header hash of a block is the canonical hash that is used to refer
892
    to a specific block and completely distinguishes a block from another.
893
894
    ``keccak256`` is a function that produces a 256 bit hash of any input.
895
    It also takes in any number of bytes as an input and produces a single
896
    hash for them. A hash is a completely unique output for a single input.
897
    So an input corresponds to one unique hash that can be used to identify
898
    the input exactly.
899
900
    Prior to using the ``keccak256`` hash function, the header must be
901
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
902
    RLP encoding the header converts it into a space-efficient format that
903
    allows for easy transfer of data between nodes. The purpose of RLP is to
904
    encode arbitrarily nested arrays of binary data, and RLP is the primary
905
    encoding method used to serialize objects in Ethereum's execution layer.
906
    The only purpose of RLP is to encode structure; encoding specific data
907
    types (e.g. strings, floats) is left up to higher-order protocols.
908
909
    Parameters
910
    ----------
911
    header :
912
        Header of interest.
913
914
    Returns
915
    -------
916
    hash : `ethereum.crypto.hash.Hash32`
917
        Hash of the header.
918
    """
919
    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:
923
    """
924
    Validates the gas limit for a block.
925
926
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
927
    quotient of the parent block's gas limit and the
928
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
929
    passed through as a parameter is greater than or equal to the *sum* of
930
    the parent's gas and the adjustment delta then the limit for gas is too
931
    high and fails this function's check. Similarly, if the limit is less
932
    than or equal to the *difference* of the parent's gas and the adjustment
933
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
934
    check fails because the gas limit doesn't allow for a sufficient or
935
    reasonable amount of gas to be used on a block.
936
937
    Parameters
938
    ----------
939
    gas_limit :
940
        Gas limit to validate.
941
942
    parent_gas_limit :
943
        Gas limit of the parent block.
944
945
    Returns
946
    -------
947
    check : `bool`
948
        True if gas limit constraints are satisfied, False otherwise.
949
    """
950
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
951
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
952
        return False
953
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
954
        return False
955
    if gas_limit < GAS_LIMIT_MINIMUM:
956
        return False
957
958
    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. parent_has_ommers: does the parent have ommers.

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, ​​parent_has_ommers: bool) -> Uint:
968
    """
969
    Computes difficulty of a block using its header and parent header.
970
971
    The difficulty is determined by the time the block was created after its
972
    parent. The ``offset`` is calculated using the parent block's difficulty,
973
    ``parent_difficulty``, and the timestamp between blocks. This offset is
974
    then added to the parent difficulty and is stored as the ``difficulty``
975
    variable. If the time between the block and its parent is too short, the
976
    offset will result in a positive number thus making the sum of
977
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
978
    avoid mass forking. But, if the time is long enough, then the offset
979
    results in a negative value making the block less difficult than
980
    its parent.
981
982
    The base standard for a block's difficulty is the predefined value
983
    set for the genesis block since it has no parent. So, a block
984
    can't be less difficult than the genesis block, therefore each block's
985
    difficulty is set to the maximum value between the calculated
986
    difficulty and the ``GENESIS_DIFFICULTY``.
987
988
    Parameters
989
    ----------
990
    block_number :
991
        Block number of the block.
992
    block_timestamp :
993
        Timestamp of the block.
994
    parent_timestamp :
995
        Timestamp of the parent block.
996
    parent_difficulty :
997
        difficulty of the parent block.
998
    parent_has_ommers:
999
        does the parent have ommers.
1000
1001
    Returns
1002
    -------
1003
    difficulty : `ethereum.base_types.Uint`
1004
        Computed difficulty for a block.
1005
    """
1006
    offset = (
1007
        int(parent_difficulty)
1008
        // 2048
1009
        * max(
1010
            (2 if parent_has_ommers else 1)
1011
            - int(block_timestamp - parent_timestamp) // 9,
1012
            -99,
1013
        )
1014
    )
1015
    difficulty = int(parent_difficulty) + offset
1016
    # Historical Note: The difficulty bomb was not present in Ethereum at the
1017
    # start of Frontier, but was added shortly after launch. However since the
1018
    # bomb has no effect prior to block 200000 we pretend it existed from
1019
    # genesis.
1020
    # See https://github.com/ethereum/go-ethereum/pull/1588
1021
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
1022
    if num_bomb_periods >= 0:
1023
        difficulty += 2**num_bomb_periods
1024
1025
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
1026
    # the bomb. This bug does not matter because the difficulty is always much
1027
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
1028
    return Uint(max(difficulty, MINIMUM_DIFFICULTY))