ethereum.constantinople.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

50
BLOCK_REWARD = U256(2 * 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)

BOMB_DELAY_BLOCKS

55
BOMB_DELAY_BLOCKS = 5000000

EMPTY_OMMER_HASH

56
EMPTY_OMMER_HASH = keccak256(rlp.encode([]))

BlockChain

History and current state of the block chain.

59
@dataclass
class BlockChain:

blocks

65
    blocks: List[Block]

state

66
    state: State

chain_id

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

make_receipt

Make the receipt for a transaction that was executed.

Parameters

tx : The executed transaction. error : Error in the top level frame of the transaction, if any. 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, ​​error: Optional[Exception], ​​cumulative_gas_used: Uint, ​​logs: Tuple[Log, ...]) -> Receipt:
346
    """
347
    Make the receipt for a transaction that was executed.
348
349
    Parameters
350
    ----------
351
    tx :
352
        The executed transaction.
353
    error :
354
        Error in the top level frame of the transaction, if any.
355
    cumulative_gas_used :
356
        The total gas used so far in the block after the transaction was
357
        executed.
358
    logs :
359
        The logs produced by the transaction.
360
361
    Returns
362
    -------
363
    receipt :
364
        The receipt for the transaction.
365
    """
366
    receipt = Receipt(
367
        succeeded=error is None,
368
        cumulative_gas_used=cumulative_gas_used,
369
        bloom=logs_bloom(logs),
370
        logs=logs,
371
    )
372
373
    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.

376
@dataclass
class ApplyBodyOutput:

block_gas_used

396
    block_gas_used: Uint

transactions_root

397
    transactions_root: Root

receipt_root

398
    receipt_root: Root

block_logs_bloom

399
    block_logs_bloom: Bloom

state_root

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

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

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:
724
    """
725
    Computes the hash of a block header.
726
727
    The header hash of a block is the canonical hash that is used to refer
728
    to a specific block and completely distinguishes a block from another.
729
730
    ``keccak256`` is a function that produces a 256 bit hash of any input.
731
    It also takes in any number of bytes as an input and produces a single
732
    hash for them. A hash is a completely unique output for a single input.
733
    So an input corresponds to one unique hash that can be used to identify
734
    the input exactly.
735
736
    Prior to using the ``keccak256`` hash function, the header must be
737
    encoded using the Recursive-Length Prefix. See :ref:`rlp`.
738
    RLP encoding the header converts it into a space-efficient format that
739
    allows for easy transfer of data between nodes. The purpose of RLP is to
740
    encode arbitrarily nested arrays of binary data, and RLP is the primary
741
    encoding method used to serialize objects in Ethereum's execution layer.
742
    The only purpose of RLP is to encode structure; encoding specific data
743
    types (e.g. strings, floats) is left up to higher-order protocols.
744
745
    Parameters
746
    ----------
747
    header :
748
        Header of interest.
749
750
    Returns
751
    -------
752
    hash : `ethereum.crypto.hash.Hash32`
753
        Hash of the header.
754
    """
755
    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:
759
    """
760
    Validates the gas limit for a block.
761
762
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
763
    quotient of the parent block's gas limit and the
764
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
765
    passed through as a parameter is greater than or equal to the *sum* of
766
    the parent's gas and the adjustment delta then the limit for gas is too
767
    high and fails this function's check. Similarly, if the limit is less
768
    than or equal to the *difference* of the parent's gas and the adjustment
769
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
770
    check fails because the gas limit doesn't allow for a sufficient or
771
    reasonable amount of gas to be used on a block.
772
773
    Parameters
774
    ----------
775
    gas_limit :
776
        Gas limit to validate.
777
778
    parent_gas_limit :
779
        Gas limit of the parent block.
780
781
    Returns
782
    -------
783
    check : `bool`
784
        True if gas limit constraints are satisfied, False otherwise.
785
    """
786
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
787
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
788
        return False
789
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
790
        return False
791
    if gas_limit < GAS_LIMIT_MINIMUM:
792
        return False
793
794
    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. parent_has_ommers: does the parent have ommers.

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, ​​parent_has_ommers: bool) -> Uint:
804
    """
805
    Computes difficulty of a block using its header and parent header.
806
807
    The difficulty is determined by the time the block was created after its
808
    parent. The ``offset`` is calculated using the parent block's difficulty,
809
    ``parent_difficulty``, and the timestamp between blocks. This offset is
810
    then added to the parent difficulty and is stored as the ``difficulty``
811
    variable. If the time between the block and its parent is too short, the
812
    offset will result in a positive number thus making the sum of
813
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
814
    avoid mass forking. But, if the time is long enough, then the offset
815
    results in a negative value making the block less difficult than
816
    its parent.
817
818
    The base standard for a block's difficulty is the predefined value
819
    set for the genesis block since it has no parent. So, a block
820
    can't be less difficult than the genesis block, therefore each block's
821
    difficulty is set to the maximum value between the calculated
822
    difficulty and the ``GENESIS_DIFFICULTY``.
823
824
    Parameters
825
    ----------
826
    block_number :
827
        Block number of the block.
828
    block_timestamp :
829
        Timestamp of the block.
830
    parent_timestamp :
831
        Timestamp of the parent block.
832
    parent_difficulty :
833
        difficulty of the parent block.
834
    parent_has_ommers:
835
        does the parent have ommers.
836
837
    Returns
838
    -------
839
    difficulty : `ethereum.base_types.Uint`
840
        Computed difficulty for a block.
841
    """
842
    offset = (
843
        int(parent_difficulty)
844
        // 2048
845
        * max(
846
            (2 if parent_has_ommers else 1)
847
            - int(block_timestamp - parent_timestamp) // 9,
848
            -99,
849
        )
850
    )
851
    difficulty = int(parent_difficulty) + offset
852
    # Historical Note: The difficulty bomb was not present in Ethereum at the
853
    # start of Frontier, but was added shortly after launch. However since the
854
    # bomb has no effect prior to block 200000 we pretend it existed from
855
    # genesis.
856
    # See https://github.com/ethereum/go-ethereum/pull/1588
857
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
858
    if num_bomb_periods >= 0:
859
        difficulty += 2**num_bomb_periods
860
861
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
862
    # the bomb. This bug does not matter because the difficulty is always much
863
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
864
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))