ethereum.tangerine_whistle.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

50
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

51
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

52
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

53
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

56
@dataclass
class BlockChain:

blocks

62
    blocks: List[Block]

state

63
    state: State

chain_id

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

367
@dataclass
class ApplyBodyOutput:

block_gas_used

387
    block_gas_used: Uint

transactions_root

388
    transactions_root: Root

receipt_root

389
    receipt_root: Root

block_logs_bloom

390
    block_logs_bloom: Bloom

state_root

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

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:
504
    """
505
    Validates the ommers mentioned in the block.
506
507
    An ommer block is a block that wasn't canonically added to the
508
    blockchain because it wasn't validated as fast as the canonical block
509
    but was mined at the same time.
510
511
    To be considered valid, the ommers must adhere to the rules defined in
512
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
513
    there cannot be duplicate ommers in a block. Many of the other ommer
514
    constraints are listed in the in-line comments of this function.
515
516
    Parameters
517
    ----------
518
    ommers :
519
        List of ommers mentioned in the current block.
520
    block_header:
521
        The header of current block.
522
    chain :
523
        History and current state.
524
    """
525
    block_hash = keccak256(rlp.encode(block_header))
526
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
527
        raise InvalidBlock
528
529
    if len(ommers) == 0:
530
        # Nothing to validate
531
        return
532
533
    # Check that each ommer satisfies the constraints of a header
534
    for ommer in ommers:
535
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
536
            raise InvalidBlock
537
        ommer_parent_header = chain.blocks[
538
            -(block_header.number - ommer.number) - 1
539
        ].header
540
        validate_header(ommer, ommer_parent_header)
541
    if len(ommers) > 2:
542
        raise InvalidBlock
543
544
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
545
    if len(ommers_hashes) != len(set(ommers_hashes)):
546
        raise InvalidBlock
547
548
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
549
    recent_canonical_block_hashes = {
550
        keccak256(rlp.encode(block.header))
551
        for block in recent_canonical_blocks
552
    }
553
    recent_ommers_hashes: Set[Hash32] = set()
554
    for block in recent_canonical_blocks:
555
        recent_ommers_hashes = recent_ommers_hashes.union(
556
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
557
        )
558
559
    for ommer_index, ommer in enumerate(ommers):
560
        ommer_hash = ommers_hashes[ommer_index]
561
        if ommer_hash == block_hash:
562
            raise InvalidBlock
563
        if ommer_hash in recent_canonical_block_hashes:
564
            raise InvalidBlock
565
        if ommer_hash in recent_ommers_hashes:
566
            raise InvalidBlock
567
568
        # Ommer age with respect to the current block. For example, an age of
569
        # 1 indicates that the ommer is a sibling of previous block.
570
        ommer_age = block_header.number - ommer.number
571
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
572
            raise InvalidBlock
573
        if ommer.parent_hash not in recent_canonical_block_hashes:
574
            raise InvalidBlock
575
        if ommer.parent_hash == block_header.parent_hash:
576
            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:
585
    """
586
    Pay rewards to the block miner as well as the ommers miners.
587
588
    The miner of the canonical block is rewarded with the predetermined
589
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
590
    number of ommer blocks that were mined around the same time, and included
591
    in the canonical block's header. An ommer block is a block that wasn't
592
    added to the canonical blockchain because it wasn't validated as fast as
593
    the accepted block but was mined at the same time. Although not all blocks
594
    that are mined are added to the canonical chain, miners are still paid a
595
    reward for their efforts. This reward is called an ommer reward and is
596
    calculated based on the number associated with the ommer block that they
597
    mined.
598
599
    Parameters
600
    ----------
601
    state :
602
        Current account state.
603
    block_number :
604
        Position of the block within the chain.
605
    coinbase :
606
        Address of account which receives block reward and transaction fees.
607
    ommers :
608
        List of ommers mentioned in the current block.
609
    """
610
    ommer_count = U256(len(ommers))
611
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
612
    create_ether(state, coinbase, miner_reward)
613
614
    for ommer in ommers:
615
        # Ommer age with respect to the current block.
616
        ommer_age = U256(block_number - ommer.number)
617
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
618
        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, ...]]:
624
    """
625
    Execute a transaction against the provided environment.
626
627
    This function processes the actions needed to execute a transaction.
628
    It decrements the sender's account after calculating the gas fee and
629
    refunds them the proper amount after execution. Calling contracts,
630
    deploying code, and incrementing nonces are all examples of actions that
631
    happen within this function or from a call made within this function.
632
633
    Accounts that are marked for deletion are processed and destroyed after
634
    execution.
635
636
    Parameters
637
    ----------
638
    env :
639
        Environment for the Ethereum Virtual Machine.
640
    tx :
641
        Transaction to execute.
642
643
    Returns
644
    -------
645
    gas_left : `ethereum.base_types.U256`
646
        Remaining gas after execution.
647
    logs : `Tuple[ethereum.blocks.Log, ...]`
648
        Logs generated during execution.
649
    """
650
    if not validate_transaction(tx):
651
        raise InvalidBlock
652
653
    sender = env.origin
654
    sender_account = get_account(env.state, sender)
655
    gas_fee = tx.gas * tx.gas_price
656
    if sender_account.nonce != tx.nonce:
657
        raise InvalidBlock
658
    if Uint(sender_account.balance) < gas_fee + Uint(tx.value):
659
        raise InvalidBlock
660
    if sender_account.code != bytearray():
661
        raise InvalidSenderError("not EOA")
662
663
    gas = tx.gas - calculate_intrinsic_cost(tx)
664
    increment_nonce(env.state, sender)
665
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
666
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
667
668
    message = prepare_message(
669
        sender,
670
        tx.to,
671
        tx.value,
672
        tx.data,
673
        gas,
674
        env,
675
    )
676
677
    output = process_message_call(message, env)
678
679
    gas_used = tx.gas - output.gas_left
680
    gas_refund = min(gas_used // Uint(2), Uint(output.refund_counter))
681
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
682
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
683
    total_gas_used = gas_used - gas_refund
684
685
    # refund gas
686
    sender_balance_after_refund = get_account(
687
        env.state, sender
688
    ).balance + U256(gas_refund_amount)
689
    set_account_balance(env.state, sender, sender_balance_after_refund)
690
691
    # transfer miner fees
692
    coinbase_balance_after_mining_fee = get_account(
693
        env.state, env.coinbase
694
    ).balance + U256(transaction_fee)
695
    set_account_balance(
696
        env.state, env.coinbase, coinbase_balance_after_mining_fee
697
    )
698
699
    for address in output.accounts_to_delete:
700
        destroy_account(env.state, address)
701
702
    return total_gas_used, output.logs

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:
706
    """
707
    Computes the hash of a block header.
708
709
    The header hash of a block is the canonical hash that is used to refer
710
    to a specific block and completely distinguishes a block from another.
711
712
    ``keccak256`` is a function that produces a 256 bit hash of any input.
713
    It also takes in any number of bytes as an input and produces a single
714
    hash for them. A hash is a completely unique output for a single input.
715
    So an input corresponds to one unique hash that can be used to identify
716
    the input exactly.
717
718
    Prior to using the ``keccak256`` hash function, the header must be
719
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
720
    RLP encoding the header converts it into a space-efficient format that
721
    allows for easy transfer of data between nodes. The purpose of RLP is to
722
    encode arbitrarily nested arrays of binary data, and RLP is the primary
723
    encoding method used to serialize objects in Ethereum's execution layer.
724
    The only purpose of RLP is to encode structure; encoding specific data
725
    types (e.g. strings, floats) is left up to higher-order protocols.
726
727
    Parameters
728
    ----------
729
    header :
730
        Header of interest.
731
732
    Returns
733
    -------
734
    hash : `ethereum.crypto.hash.Hash32`
735
        Hash of the header.
736
    """
737
    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:
741
    """
742
    Validates the gas limit for a block.
743
744
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
745
    quotient of the parent block's gas limit and the
746
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
747
    passed through as a parameter is greater than or equal to the *sum* of
748
    the parent's gas and the adjustment delta then the limit for gas is too
749
    high and fails this function's check. Similarly, if the limit is less
750
    than or equal to the *difference* of the parent's gas and the adjustment
751
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
752
    check fails because the gas limit doesn't allow for a sufficient or
753
    reasonable amount of gas to be used on a block.
754
755
    Parameters
756
    ----------
757
    gas_limit :
758
        Gas limit to validate.
759
760
    parent_gas_limit :
761
        Gas limit of the parent block.
762
763
    Returns
764
    -------
765
    check : `bool`
766
        True if gas limit constraints are satisfied, False otherwise.
767
    """
768
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
769
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
770
        return False
771
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
772
        return False
773
    if gas_limit < GAS_LIMIT_MINIMUM:
774
        return False
775
776
    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:
785
    """
786
    Computes difficulty of a block using its header and parent header.
787
788
    The difficulty is determined by the time the block was created after its
789
    parent. The ``offset`` is calculated using the parent block's difficulty,
790
    ``parent_difficulty``, and the timestamp between blocks. This offset is
791
    then added to the parent difficulty and is stored as the ``difficulty``
792
    variable. If the time between the block and its parent is too short, the
793
    offset will result in a positive number thus making the sum of
794
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
795
    avoid mass forking. But, if the time is long enough, then the offset
796
    results in a negative value making the block less difficult than
797
    its parent.
798
799
    The base standard for a block's difficulty is the predefined value
800
    set for the genesis block since it has no parent. So, a block
801
    can't be less difficult than the genesis block, therefore each block's
802
    difficulty is set to the maximum value between the calculated
803
    difficulty and the ``GENESIS_DIFFICULTY``.
804
805
    Parameters
806
    ----------
807
    block_number :
808
        Block number of the block.
809
    block_timestamp :
810
        Timestamp of the block.
811
    parent_timestamp :
812
        Timestamp of the parent block.
813
    parent_difficulty :
814
        difficulty of the parent block.
815
816
    Returns
817
    -------
818
    difficulty : `ethereum.base_types.Uint`
819
        Computed difficulty for a block.
820
    """
821
    offset = (
822
        int(parent_difficulty)
823
        // 2048
824
        * max(1 - int(block_timestamp - parent_timestamp) // 10, -99)
825
    )
826
    difficulty = int(parent_difficulty) + offset
827
    # Historical Note: The difficulty bomb was not present in Ethereum at the
828
    # start of Frontier, but was added shortly after launch. However since the
829
    # bomb has no effect prior to block 200000 we pretend it existed from
830
    # genesis.
831
    # See https://github.com/ethereum/go-ethereum/pull/1588
832
    num_bomb_periods = (int(block_number) // 100000) - 2
833
    if num_bomb_periods >= 0:
834
        difficulty += 2**num_bomb_periods
835
836
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
837
    # the bomb. This bug does not matter because the difficulty is always much
838
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
839
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))