ethereum.tangerine_whistle.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

52
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

53
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

54
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

55
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

58
@dataclass
class BlockChain:

blocks

64
    blocks: List[Block]

state

65
    state: State

chain_id

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

check_transaction

Check if the transaction is includable in the block.

Parameters

tx : The transaction. gas_available : The gas remaining in the block.

Returns

sender_address : The sender of the transaction.

Raises

InvalidBlock : If the transaction is not includable.

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

369
@dataclass
class ApplyBodyOutput:

block_gas_used

389
    block_gas_used: Uint

transactions_root

390
    transactions_root: Root

receipt_root

391
    receipt_root: Root

block_logs_bloom

392
    block_logs_bloom: Bloom

state_root

393
    state_root: Root

apply_body

Executes a block.

Many of the contents of a block are stored in data structures called tries. There is a transactions trie which is similar to a ledger of the transactions stored in the current block. There is also a receipts trie which stores the results of executing a transaction, like the post state and gas used. This function creates and executes the block that is to be added to the chain.

Parameters

state : Current account state. block_hashes : List of hashes of the previous 256 blocks in the order of increasing block number. coinbase : Address of account which receives block reward and transaction fees. block_number : Position of the block within the chain. block_gas_limit : Initial amount of gas available for execution in this block. block_time : Time the block was produced, measured in seconds since the epoch. block_difficulty : Difficulty of the block. transactions : Transactions included in the block. ommers : Headers of ancestor blocks which are not direct parents (formerly uncles.)

Returns

apply_body_output : ApplyBodyOutput Output of applying the block body to the state.

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

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

recover_sender

Extracts the sender address from a transaction.

The v, r, and s values are the three parts that make up the signature of a transaction. In order to recover the sender of a transaction the two components needed are the signature (v, r, and s) and the signing hash of the transaction. The sender's public key can be obtained with these two values and therefore the sender address can be retrieved.

Parameters

tx : Transaction of interest.

Returns

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

def recover_sender(tx: Transaction) -> Address:
778
    """
779
    Extracts the sender address from a transaction.
780
781
    The v, r, and s values are the three parts that make up the signature
782
    of a transaction. In order to recover the sender of a transaction the two
783
    components needed are the signature (``v``, ``r``, and ``s``) and the
784
    signing hash of the transaction. The sender's public key can be obtained
785
    with these two values and therefore the sender address can be retrieved.
786
787
    Parameters
788
    ----------
789
    tx :
790
        Transaction of interest.
791
792
    Returns
793
    -------
794
    sender : `ethereum.fork_types.Address`
795
        The address of the account that signed the transaction.
796
    """
797
    v, r, s = tx.v, tx.r, tx.s
798
    if v != 27 and v != 28:
799
        raise InvalidBlock
800
    if U256(0) >= r or r >= SECP256K1N:
801
        raise InvalidBlock
802
    if U256(0) >= s or s > SECP256K1N // U256(2):
803
        raise InvalidBlock
804
805
    public_key = secp256k1_recover(r, s, v - U256(27), signing_hash(tx))
806
    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
    )

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