ethereum.tangerine_whistle.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

51
GAS_LIMIT_ADJUSTMENT_FACTOR = 1024

GAS_LIMIT_MINIMUM

52
GAS_LIMIT_MINIMUM = 5000

MINIMUM_DIFFICULTY

53
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

54
MAX_OMMER_DEPTH = 6

BlockChain

History and current state of the block chain.

57
@dataclass
class BlockChain:

blocks

63
    blocks: List[Block]

state

64
    state: State

chain_id

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

364
@dataclass
class ApplyBodyOutput:

block_gas_used

384
    block_gas_used: Uint

transactions_root

385
    transactions_root: Root

receipt_root

386
    receipt_root: Root

block_logs_bloom

387
    block_logs_bloom: Bloom

state_root

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

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

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