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

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

GAS_LIMIT_ADJUSTMENT_FACTOR

51
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

52
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

53
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

54
MAX_OMMER_DEPTH = Uint(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
        chain.chain_id,
166
    )
167
    if apply_body_output.block_gas_used != block.header.gas_used:
168
        raise InvalidBlock(
169
            f"{apply_body_output.block_gas_used} != {block.header.gas_used}"
170
        )
171
    if apply_body_output.transactions_root != block.header.transactions_root:
172
        raise InvalidBlock
173
    if apply_body_output.state_root != block.header.state_root:
174
        raise InvalidBlock
175
    if apply_body_output.receipt_root != block.header.receipt_root:
176
        raise InvalidBlock
177
    if apply_body_output.block_logs_bloom != block.header.bloom:
178
        raise InvalidBlock
179
180
    chain.blocks.append(block)
181
    if len(chain.blocks) > 255:
182
        # Real clients have to store more blocks to deal with reorgs, but the
183
        # protocol only requires the last 255
184
        chain.blocks = chain.blocks[-255:]

validate_header

Verifies a block header.

In order to consider a block's header valid, the logic for the quantities in the header should match the logic for the block itself. For example the header timestamp should be greater than the block's parent timestamp because the block was created after the parent block. Additionally, the block's number should be directly following the parent block's number since it is the next block in the sequence.

Parameters

header : Header to check for correctness. parent_header : Parent Header of the header to check for correctness

def validate_header(header: Header, ​​parent_header: Header) -> None:
188
    """
189
    Verifies a block header.
190
191
    In order to consider a block's header valid, the logic for the
192
    quantities in the header should match the logic for the block itself.
193
    For example the header timestamp should be greater than the block's parent
194
    timestamp because the block was created *after* the parent block.
195
    Additionally, the block's number should be directly following the parent
196
    block's number since it is the next block in the sequence.
197
198
    Parameters
199
    ----------
200
    header :
201
        Header to check for correctness.
202
    parent_header :
203
        Parent Header of the header to check for correctness
204
    """
205
    if header.timestamp <= parent_header.timestamp:
206
        raise InvalidBlock
207
    if header.number != parent_header.number + Uint(1):
208
        raise InvalidBlock
209
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
210
        raise InvalidBlock
211
    if len(header.extra_data) > 32:
212
        raise InvalidBlock
213
214
    block_difficulty = calculate_block_difficulty(
215
        header.number,
216
        header.timestamp,
217
        parent_header.timestamp,
218
        parent_header.difficulty,
219
    )
220
    if header.difficulty != block_difficulty:
221
        raise InvalidBlock
222
223
    block_parent_hash = keccak256(rlp.encode(parent_header))
224
    if header.parent_hash != block_parent_hash:
225
        raise InvalidBlock
226
227
    validate_proof_of_work(header)

generate_header_hash_for_pow

Generate rlp hash of the header which is to be used for Proof-of-Work verification.

In other words, the PoW artefacts mix_digest and nonce are ignored while calculating this hash.

A particular PoW is valid for a single hash, that hash is computed by this function. The nonce and mix_digest are omitted from this hash because they are being changed by miners in their search for a sufficient proof-of-work.

Parameters

header : The header object for which the hash is to be generated.

Returns

hash : Hash32 The PoW valid rlp hash of the passed in header.

def generate_header_hash_for_pow(header: Header) -> Hash32:
231
    """
232
    Generate rlp hash of the header which is to be used for Proof-of-Work
233
    verification.
234
235
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
236
    while calculating this hash.
237
238
    A particular PoW is valid for a single hash, that hash is computed by
239
    this function. The `nonce` and `mix_digest` are omitted from this hash
240
    because they are being changed by miners in their search for a sufficient
241
    proof-of-work.
242
243
    Parameters
244
    ----------
245
    header :
246
        The header object for which the hash is to be generated.
247
248
    Returns
249
    -------
250
    hash : `Hash32`
251
        The PoW valid rlp hash of the passed in header.
252
    """
253
    header_data_without_pow_artefacts = (
254
        header.parent_hash,
255
        header.ommers_hash,
256
        header.coinbase,
257
        header.state_root,
258
        header.transactions_root,
259
        header.receipt_root,
260
        header.bloom,
261
        header.difficulty,
262
        header.number,
263
        header.gas_limit,
264
        header.gas_used,
265
        header.timestamp,
266
        header.extra_data,
267
    )
268
269
    return 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:
273
    """
274
    Validates the Proof of Work constraints.
275
276
    In order to verify that a miner's proof-of-work is valid for a block, a
277
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
278
    hash function. The mix digest is a hash of the header and the nonce that
279
    is passed through and it confirms whether or not proof-of-work was done
280
    on the correct block. The result is the actual hash value of the block.
281
282
    Parameters
283
    ----------
284
    header :
285
        Header of interest.
286
    """
287
    header_hash = generate_header_hash_for_pow(header)
288
    # TODO: Memoize this somewhere and read from that data instead of
289
    # calculating cache for every block validation.
290
    cache = generate_cache(header.number)
291
    mix_digest, result = hashimoto_light(
292
        header_hash, header.nonce, cache, dataset_size(header.number)
293
    )
294
    if mix_digest != header.mix_digest:
295
        raise InvalidBlock
296
297
    limit = Uint(U256.MAX_VALUE) + Uint(1)
298
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
299
        raise InvalidBlock

check_transaction

Check if the transaction is includable in the block.

Parameters

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

372
@dataclass
class ApplyBodyOutput:

block_gas_used

392
    block_gas_used: Uint

transactions_root

393
    transactions_root: Root

receipt_root

394
    receipt_root: Root

block_logs_bloom

395
    block_logs_bloom: Bloom

state_root

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

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

process_transaction

Execute a transaction against the provided environment.

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

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

Parameters

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

Returns

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

def process_transaction(env: ethereum.tangerine_whistle.vm.Environmentethereum.spurious_dragon.vm.Environment, ​​tx: Transaction) -> Tuple[Uint, Tuple[Log, ...]]:
632
    """
633
    Execute a transaction against the provided environment.
634
635
    This function processes the actions needed to execute a transaction.
636
    It decrements the sender's account after calculating the gas fee and
637
    refunds them the proper amount after execution. Calling contracts,
638
    deploying code, and incrementing nonces are all examples of actions that
639
    happen within this function or from a call made within this function.
640
641
    Accounts that are marked for deletion are processed and destroyed after
642
    execution.
643
644
    Parameters
645
    ----------
646
    env :
647
        Environment for the Ethereum Virtual Machine.
648
    tx :
649
        Transaction to execute.
650
651
    Returns
652
    -------
653
    gas_left : `ethereum.base_types.U256`
654
        Remaining gas after execution.
655
    logs : `Tuple[ethereum.blocks.Log, ...]`
656
        Logs generated during execution.
657
    """
658
    if not validate_transaction(tx):
659
        raise InvalidBlock
660
661
    sender = env.origin
662
    sender_account = get_account(env.state, sender)
663
    gas_fee = tx.gas * tx.gas_price
664
    if sender_account.nonce != tx.nonce:
665
        raise InvalidBlock
666
    if Uint(sender_account.balance) < gas_fee + Uint(tx.value):
667
        raise InvalidBlock
668
    if sender_account.code != bytearray():
669
        raise InvalidSenderError("not EOA")
670
671
    gas = tx.gas - calculate_intrinsic_cost(tx)
672
    increment_nonce(env.state, sender)
673
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
674
    set_account_balance(env.state, sender, U256(sender_balance_after_gas_fee))
675
676
    message = prepare_message(
677
        sender,
678
        tx.to,
679
        tx.value,
680
        tx.data,
681
        gas,
682
        env,
683
    )
684
685
    output = process_message_call(message, env)
686
687
    gas_used = tx.gas - output.gas_left
688
    gas_refund = min(gas_used // Uint(2), Uint(output.refund_counter))
689
    gas_refund_amount = (output.gas_left + gas_refund) * tx.gas_price
690
    transaction_fee = (tx.gas - output.gas_left - gas_refund) * tx.gas_price
691
    total_gas_used = gas_used - gas_refund
692
693
    # refund gas
694
    sender_balance_after_refund = get_account(
695
        env.state, sender
696
    ).balance + U256(gas_refund_amount)
697
    set_account_balance(env.state, sender, sender_balance_after_refund)
698
699
    # transfer miner fees
700
    coinbase_balance_after_mining_fee = get_account(
701
        env.state, env.coinbase
702
    ).balance + U256(transaction_fee)
695
    set_account_balance(
696
        env.state, env.coinbase, coinbase_balance_after_mining_fee
697
    )
703
    if coinbase_balance_after_mining_fee != 0:
704
        set_account_balance(
705
            env.state, env.coinbase, coinbase_balance_after_mining_fee
706
        )
707
    elif account_exists_and_is_empty(env.state, env.coinbase):
708
        destroy_account(env.state, env.coinbase)
709
710
    for address in output.accounts_to_delete:
711
        destroy_account(env.state, address)
712
713
    for address in output.touched_accounts:
714
        if account_exists_and_is_empty(env.state, address):
715
            destroy_account(env.state, address)
716
717
    return total_gas_used, output.logs

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