ethereum.tangerine_whistle.forkethereum.spurious_dragon.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

51
BLOCK_REWARD = U256(5 * 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

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
        chain.chain_id,
167
    )
168
    if apply_body_output.block_gas_used != block.header.gas_used:
169
        raise InvalidBlock
170
    if apply_body_output.transactions_root != block.header.transactions_root:
171
        raise InvalidBlock
172
    if apply_body_output.state_root != block.header.state_root:
173
        raise InvalidBlock
174
    if apply_body_output.receipt_root != block.header.receipt_root:
175
        raise InvalidBlock
176
    if apply_body_output.block_logs_bloom != block.header.bloom:
177
        raise InvalidBlock
178
179
    chain.blocks.append(block)
180
    if len(chain.blocks) > 255:
181
        # Real clients have to store more blocks to deal with reorgs, but the
182
        # protocol only requires the last 255
183
        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:
187
    """
188
    Verifies a block header.
189
190
    In order to consider a block's header valid, the logic for the
191
    quantities in the header should match the logic for the block itself.
192
    For example the header timestamp should be greater than the block's parent
193
    timestamp because the block was created *after* the parent block.
194
    Additionally, the block's number should be directly following the parent
195
    block's number since it is the next block in the sequence.
196
197
    Parameters
198
    ----------
199
    header :
200
        Header to check for correctness.
201
    parent_header :
202
        Parent Header of the header to check for correctness
203
    """
204
    if header.timestamp <= parent_header.timestamp:
205
        raise InvalidBlock
206
    if header.number != parent_header.number + 1:
207
        raise InvalidBlock
208
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
209
        raise InvalidBlock
210
    if len(header.extra_data) > 32:
211
        raise InvalidBlock
212
213
    block_difficulty = calculate_block_difficulty(
214
        header.number,
215
        header.timestamp,
216
        parent_header.timestamp,
217
        parent_header.difficulty,
218
    )
219
    if header.difficulty != block_difficulty:
220
        raise InvalidBlock
221
222
    block_parent_hash = keccak256(rlp.encode(parent_header))
223
    if header.parent_hash != block_parent_hash:
224
        raise InvalidBlock
225
226
    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:
230
    """
231
    Generate rlp hash of the header which is to be used for Proof-of-Work
232
    verification.
233
234
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
235
    while calculating this hash.
236
237
    A particular PoW is valid for a single hash, that hash is computed by
238
    this function. The `nonce` and `mix_digest` are omitted from this hash
239
    because they are being changed by miners in their search for a sufficient
240
    proof-of-work.
241
242
    Parameters
243
    ----------
244
    header :
245
        The header object for which the hash is to be generated.
246
247
    Returns
248
    -------
249
    hash : `Hash32`
250
        The PoW valid rlp hash of the passed in header.
251
    """
252
    header_data_without_pow_artefacts = (
253
        header.parent_hash,
254
        header.ommers_hash,
255
        header.coinbase,
256
        header.state_root,
257
        header.transactions_root,
258
        header.receipt_root,
259
        header.bloom,
260
        header.difficulty,
261
        header.number,
262
        header.gas_limit,
263
        header.gas_used,
264
        header.timestamp,
265
        header.extra_data,
266
    )
267
268
    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:
272
    """
273
    Validates the Proof of Work constraints.
274
275
    In order to verify that a miner's proof-of-work is valid for a block, a
276
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
277
    hash function. The mix digest is a hash of the header and the nonce that
278
    is passed through and it confirms whether or not proof-of-work was done
279
    on the correct block. The result is the actual hash value of the block.
280
281
    Parameters
282
    ----------
283
    header :
284
        Header of interest.
285
    """
286
    header_hash = generate_header_hash_for_pow(header)
287
    # TODO: Memoize this somewhere and read from that data instead of
288
    # calculating cache for every block validation.
289
    cache = generate_cache(header.number)
290
    mix_digest, result = hashimoto_light(
291
        header_hash, header.nonce, cache, dataset_size(header.number)
292
    )
293
    if mix_digest != header.mix_digest:
294
        raise InvalidBlock
295
    if Uint.from_be_bytes(result) > (U256_CEIL_VALUE // header.difficulty):
296
        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:
304
    """
305
    Check if the transaction is includable in the block.
306
307
    Parameters
308
    ----------
309
    tx :
310
        The transaction.
311
    gas_available :
312
        The gas remaining in the block.
313
    chain_id :
314
        The ID of the current chain.
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
323
    sender_address = recover_sender(tx)
328
    sender_address = recover_sender(chain_id, 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.) 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:
408
    """
409
    Executes a block.
410
411
    Many of the contents of a block are stored in data structures called
412
    tries. There is a transactions trie which is similar to a ledger of the
413
    transactions stored in the current block. There is also a receipts trie
414
    which stores the results of executing a transaction, like the post state
415
    and gas used. This function creates and executes the block that is to be
416
    added to the chain.
417
418
    Parameters
419
    ----------
420
    state :
421
        Current account state.
422
    block_hashes :
423
        List of hashes of the previous 256 blocks in the order of
424
        increasing block number.
425
    coinbase :
426
        Address of account which receives block reward and transaction fees.
427
    block_number :
428
        Position of the block within the chain.
429
    block_gas_limit :
430
        Initial amount of gas available for execution in this block.
431
    block_time :
432
        Time the block was produced, measured in seconds since the epoch.
433
    block_difficulty :
434
        Difficulty of the block.
435
    transactions :
436
        Transactions included in the block.
437
    ommers :
438
        Headers of ancestor blocks which are not direct parents (formerly
439
        uncles.)
440
    chain_id :
441
        ID of the executing chain.
442
443
    Returns
444
    -------
445
    apply_body_output : `ApplyBodyOutput`
446
        Output of applying the block body to the state.
447
    """
448
    gas_available = block_gas_limit
449
    transactions_trie: Trie[Bytes, Optional[Transaction]] = Trie(
450
        secured=False, default=None
451
    )
452
    receipts_trie: Trie[Bytes, Optional[Receipt]] = Trie(
453
        secured=False, default=None
454
    )
455
    block_logs: Tuple[Log, ...] = ()
456
457
    for i, tx in enumerate(transactions):
458
        trie_set(transactions_trie, rlp.encode(Uint(i)), tx)
459
452
        sender_address = check_transaction(tx, gas_available)
460
        sender_address = check_transaction(tx, gas_available, chain_id)
461
462
        env = vm.Environment(
463
            caller=sender_address,
464
            origin=sender_address,
465
            block_hashes=block_hashes,
466
            coinbase=coinbase,
467
            number=block_number,
468
            gas_limit=block_gas_limit,
469
            gas_price=tx.gas_price,
470
            time=block_time,
471
            difficulty=block_difficulty,
472
            state=state,
473
            traces=[],
474
        )
475
476
        gas_used, logs = process_transaction(env, tx)
477
        gas_available -= gas_used
478
479
        receipt = make_receipt(
480
            tx, state_root(state), (block_gas_limit - gas_available), logs
481
        )
482
483
        trie_set(
484
            receipts_trie,
485
            rlp.encode(Uint(i)),
486
            receipt,
487
        )
488
489
        block_logs += logs
490
491
    pay_rewards(state, block_number, coinbase, ommers)
492
493
    block_gas_used = block_gas_limit - gas_available
494
495
    block_logs_bloom = logs_bloom(block_logs)
496
497
    return ApplyBodyOutput(
498
        block_gas_used,
499
        root(transactions_trie),
500
        root(receipts_trie),
501
        block_logs_bloom,
502
        state_root(state),
503
    )

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:
509
    """
510
    Validates the ommers mentioned in the block.
511
512
    An ommer block is a block that wasn't canonically added to the
513
    blockchain because it wasn't validated as fast as the canonical block
514
    but was mined at the same time.
515
516
    To be considered valid, the ommers must adhere to the rules defined in
517
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
518
    there cannot be duplicate ommers in a block. Many of the other ommer
519
    constraints are listed in the in-line comments of this function.
520
521
    Parameters
522
    ----------
523
    ommers :
524
        List of ommers mentioned in the current block.
525
    block_header:
526
        The header of current block.
527
    chain :
528
        History and current state.
529
    """
530
    block_hash = rlp.rlp_hash(block_header)
531
    if rlp.rlp_hash(ommers) != block_header.ommers_hash:
532
        raise InvalidBlock
533
534
    if len(ommers) == 0:
535
        # Nothing to validate
536
        return
537
538
    # Check that each ommer satisfies the constraints of a header
539
    for ommer in ommers:
540
        if 1 > ommer.number or ommer.number >= block_header.number:
541
            raise InvalidBlock
542
        ommer_parent_header = chain.blocks[
543
            -(block_header.number - ommer.number) - 1
544
        ].header
545
        validate_header(ommer, ommer_parent_header)
546
    if len(ommers) > 2:
547
        raise InvalidBlock
548
549
    ommers_hashes = [rlp.rlp_hash(ommer) for ommer in ommers]
550
    if len(ommers_hashes) != len(set(ommers_hashes)):
551
        raise InvalidBlock
552
553
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + 1) :]
554
    recent_canonical_block_hashes = {
555
        rlp.rlp_hash(block.header) for block in recent_canonical_blocks
556
    }
557
    recent_ommers_hashes: Set[Hash32] = set()
558
    for block in recent_canonical_blocks:
559
        recent_ommers_hashes = recent_ommers_hashes.union(
560
            {rlp.rlp_hash(ommer) for ommer in block.ommers}
561
        )
562
563
    for ommer_index, ommer in enumerate(ommers):
564
        ommer_hash = ommers_hashes[ommer_index]
565
        if ommer_hash == block_hash:
566
            raise InvalidBlock
567
        if ommer_hash in recent_canonical_block_hashes:
568
            raise InvalidBlock
569
        if ommer_hash in recent_ommers_hashes:
570
            raise InvalidBlock
571
572
        # Ommer age with respect to the current block. For example, an age of
573
        # 1 indicates that the ommer is a sibling of previous block.
574
        ommer_age = block_header.number - ommer.number
575
        if 1 > ommer_age or ommer_age > MAX_OMMER_DEPTH:
576
            raise InvalidBlock
577
        if ommer.parent_hash not in recent_canonical_block_hashes:
578
            raise InvalidBlock
579
        if ommer.parent_hash == block_header.parent_hash:
580
            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:
589
    """
590
    Pay rewards to the block miner as well as the ommers miners.
591
592
    The miner of the canonical block is rewarded with the predetermined
593
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
594
    number of ommer blocks that were mined around the same time, and included
595
    in the canonical block's header. An ommer block is a block that wasn't
596
    added to the canonical blockchain because it wasn't validated as fast as
597
    the accepted block but was mined at the same time. Although not all blocks
598
    that are mined are added to the canonical chain, miners are still paid a
599
    reward for their efforts. This reward is called an ommer reward and is
600
    calculated based on the number associated with the ommer block that they
601
    mined.
602
603
    Parameters
604
    ----------
605
    state :
606
        Current account state.
607
    block_number :
608
        Position of the block within the chain.
609
    coinbase :
610
        Address of account which receives block reward and transaction fees.
611
    ommers :
612
        List of ommers mentioned in the current block.
613
    """
614
    miner_reward = BLOCK_REWARD + (len(ommers) * (BLOCK_REWARD // 32))
615
    create_ether(state, coinbase, miner_reward)
616
617
    for ommer in ommers:
618
        # Ommer age with respect to the current block.
619
        ommer_age = U256(block_number - ommer.number)
620
        ommer_miner_reward = ((8 - ommer_age) * BLOCK_REWARD) // 8
621
        create_ether(state, ommer.coinbase, ommer_miner_reward)

process_transaction

Execute a transaction against the provided environment.

This function processes the actions needed to execute a transaction. It decrements the sender's account after calculating the gas fee and refunds them the proper amount after execution. Calling contracts, deploying code, and incrementing nonces are all examples of actions that happen within this function or from a call made within this function.

Accounts that are marked for deletion are processed and destroyed after execution.

Parameters

env : Environment for the Ethereum Virtual Machine. tx : Transaction to execute.

Returns

gas_left : ethereum.base_types.U256 Remaining gas after execution. logs : Tuple[ethereum.blocks.Log, ...] Logs generated during execution.

def process_transaction(env: ethereum.tangerine_whistle.vm.Environmentethereum.spurious_dragon.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...]]:
627
    """
628
    Execute a transaction against the provided environment.
629
630
    This function processes the actions needed to execute a transaction.
631
    It decrements the sender's account after calculating the gas fee and
632
    refunds them the proper amount after execution. Calling contracts,
633
    deploying code, and incrementing nonces are all examples of actions that
634
    happen within this function or from a call made within this function.
635
636
    Accounts that are marked for deletion are processed and destroyed after
637
    execution.
638
639
    Parameters
640
    ----------
641
    env :
642
        Environment for the Ethereum Virtual Machine.
643
    tx :
644
        Transaction to execute.
645
646
    Returns
647
    -------
648
    gas_left : `ethereum.base_types.U256`
649
        Remaining gas after execution.
650
    logs : `Tuple[ethereum.blocks.Log, ...]`
651
        Logs generated during execution.
652
    """
653
    if not validate_transaction(tx):
654
        raise InvalidBlock
655
656
    sender = env.origin
657
    sender_account = get_account(env.state, sender)
658
    gas_fee = tx.gas * tx.gas_price
659
    if sender_account.nonce != tx.nonce:
660
        raise InvalidBlock
661
    if sender_account.balance < gas_fee + tx.value:
662
        raise InvalidBlock
663
    if sender_account.code != bytearray():
664
        raise InvalidBlock
665
666
    gas = tx.gas - calculate_intrinsic_cost(tx)
667
    increment_nonce(env.state, sender)
668
    sender_balance_after_gas_fee = sender_account.balance - gas_fee
669
    set_account_balance(env.state, sender, sender_balance_after_gas_fee)
670
671
    message = prepare_message(
672
        sender,
673
        tx.to,
674
        tx.value,
675
        tx.data,
676
        gas,
677
        env,
678
    )
679
680
    output = process_message_call(message, env)
681
682
    gas_used = tx.gas - output.gas_left
683
    gas_refund = min(gas_used // 2, output.refund_counter)
684
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
685
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
686
    total_gas_used = gas_used - gas_refund
687
688
    # refund gas
689
    sender_balance_after_refund = (
690
        get_account(env.state, sender).balance + gas_refund_amount
691
    )
692
    set_account_balance(env.state, sender, sender_balance_after_refund)
693
694
    # transfer miner fees
695
    coinbase_balance_after_mining_fee = (
696
        get_account(env.state, env.coinbase).balance + transaction_fee
697
    )
690
    set_account_balance(
691
        env.state, env.coinbase, coinbase_balance_after_mining_fee
692
    )
698
    if coinbase_balance_after_mining_fee != 0:
699
        set_account_balance(
700
            env.state, env.coinbase, coinbase_balance_after_mining_fee
701
        )
702
    elif account_exists_and_is_empty(env.state, env.coinbase):
703
        destroy_account(env.state, env.coinbase)
704
705
    for address in output.accounts_to_delete:
706
        destroy_account(env.state, address)
707
708
    for address in output.touched_accounts:
709
        if account_exists_and_is_empty(env.state, address):
710
            destroy_account(env.state, address)
711
712
    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:
716
    """
717
    Verifies a transaction.
718
719
    The gas in a transaction gets used to pay for the intrinsic cost of
720
    operations, therefore if there is insufficient gas then it would not
721
    be possible to execute a transaction and it will be declared invalid.
722
723
    Additionally, the nonce of a transaction must not equal or exceed the
724
    limit defined in `EIP-2681 <https://eips.ethereum.org/EIPS/eip-2681>`_.
725
    In practice, defining the limit as ``2**64-1`` has no impact because
726
    sending ``2**64-1`` transactions is improbable. It's not strictly
727
    impossible though, ``2**64-1`` transactions is the entire capacity of the
728
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
729
730
    Parameters
731
    ----------
732
    tx :
733
        Transaction to validate.
734
735
    Returns
736
    -------
737
    verified : `bool`
738
        True if the transaction can be executed, or False otherwise.
739
    """
740
    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:
744
    """
745
    Calculates the gas that is charged before execution is started.
746
747
    The intrinsic cost of the transaction is charged before execution has
748
    begun. Functions/operations in the EVM cost money to execute so this
749
    intrinsic cost is for the operations that need to be paid for as part of
750
    the transaction. Data transfer, for example, is part of this intrinsic
751
    cost. It costs ether to send data over the wire and that ether is
752
    accounted for in the intrinsic cost calculated in this function. This
753
    intrinsic cost must be calculated and paid for before execution in order
754
    for all operations to be implemented.
755
756
    Parameters
757
    ----------
758
    tx :
759
        Transaction to compute the intrinsic cost of.
760
761
    Returns
762
    -------
763
    verified : `ethereum.base_types.Uint`
764
        The intrinsic cost of the transaction.
765
    """
766
    data_cost = 0
767
768
    for byte in tx.data:
769
        if byte == 0:
770
            data_cost += TX_DATA_COST_PER_ZERO
771
        else:
772
            data_cost += TX_DATA_COST_PER_NON_ZERO
773
774
    if tx.to == Bytes0(b""):
775
        create_cost = TX_CREATE_COST
776
    else:
777
        create_cost = 0
778
779
    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:
783
    """
784
    Extracts the sender address from a transaction.
785
786
    The v, r, and s values are the three parts that make up the signature
787
    of a transaction. In order to recover the sender of a transaction the two
788
    components needed are the signature (``v``, ``r``, and ``s``) and the
789
    signing hash of the transaction. The sender's public key can be obtained
790
    with these two values and therefore the sender address can be retrieved.
791
792
    Parameters
793
    ----------
794
    tx :
795
        Transaction of interest.
796
    chain_id :
797
        ID of the executing chain.
798
799
    Returns
800
    -------
801
    sender : `ethereum.fork_types.Address`
802
        The address of the account that signed the transaction.
803
    """
804
    v, r, s = tx.v, tx.r, tx.s
788
    if v != 27 and v != 28:
789
        raise InvalidBlock
805
    if 0 >= r or r >= SECP256K1N:
806
        raise InvalidBlock
807
    if 0 >= s or s > SECP256K1N // 2:
808
        raise InvalidBlock
809
795
    public_key = secp256k1_recover(r, s, v - 27, signing_hash(tx))
810
    if v == 27 or v == 28:
811
        public_key = secp256k1_recover(r, s, v - 27, signing_hash_pre155(tx))
812
    else:
813
        if v != 35 + chain_id * 2 and v != 36 + chain_id * 2:
814
            raise InvalidBlock
815
        public_key = secp256k1_recover(
816
            r, s, v - 35 - chain_id * 2, signing_hash_155(tx, chain_id)
817
        )
818
    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:
800
    """
801
    Compute the hash of a transaction used in the signature.
802
803
    The values that are used to compute the signing hash set the rules for a
804
    transaction. For example, signing over the gas sets a limit for the
805
    amount of money that is allowed to be pulled out of the sender's account.
806
807
    Parameters
808
    ----------
809
    tx :
810
        Transaction of interest.
811
812
    Returns
813
    -------
814
    hash : `ethereum.crypto.hash.Hash32`
815
        Hash of the transaction.
816
    """
817
    return keccak256(
818
        rlp.encode(
819
            (
820
                tx.nonce,
821
                tx.gas_price,
822
                tx.gas,
823
                tx.to,
824
                tx.value,
825
                tx.data,
826
            )
827
        )
828
    )

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

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

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