ethereum.berlin.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

61
BLOCK_REWARD = U256(2 * 10**18)

GAS_LIMIT_ADJUSTMENT_FACTOR

62
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

63
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

64
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

65
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

66
BOMB_DELAY_BLOCKS = 9000000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

70
@dataclass
class BlockChain:

blocks

76
    blocks: List[Block]

state

77
    state: State

chain_id

78
    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:
82
    """
83
    Transforms the state from the previous hard fork (`old`) into the block
84
    chain object for this hard fork and returns it.
85
86
    When forks need to implement an irregular state transition, this function
87
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
88
    an example.
89
90
    Parameters
91
    ----------
92
    old :
93
        Previous block chain object.
94
95
    Returns
96
    -------
97
    new : `BlockChain`
98
        Upgraded block chain object for this hard fork.
99
    """
100
    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]:
104
    """
105
    Obtain the list of hashes of the previous 256 blocks in order of
106
    increasing block number.
107
108
    This function will return less hashes for the first 256 blocks.
109
110
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
111
    therefore this function retrieves them.
112
113
    Parameters
114
    ----------
115
    chain :
116
        History and current state.
117
118
    Returns
119
    -------
120
    recent_block_hashes : `List[Hash32]`
121
        Hashes of the recent 256 blocks in order of increasing block number.
122
    """
123
    recent_blocks = chain.blocks[-255:]
124
    # TODO: This function has not been tested rigorously
125
    if len(recent_blocks) == 0:
126
        return []
127
128
    recent_block_hashes = []
129
130
    for block in recent_blocks:
131
        prev_block_hash = block.header.parent_hash
132
        recent_block_hashes.append(prev_block_hash)
133
134
    # We are computing the hash only for the most recent block and not for
135
    # the rest of the blocks as they have successors which have the hash of
136
    # the current block as parent hash.
137
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
138
    recent_block_hashes.append(most_recent_block_hash)
139
140
    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:
144
    """
145
    Attempts to apply a block to an existing block chain.
146
147
    All parts of the block's contents need to be verified before being added
148
    to the chain. Blocks are verified by ensuring that the contents of the
149
    block make logical sense with the contents of the parent block. The
150
    information in the block's header must also match the corresponding
151
    information in the block.
152
153
    To implement Ethereum, in theory clients are only required to store the
154
    most recent 255 blocks of the chain since as far as execution is
155
    concerned, only those blocks are accessed. Practically, however, clients
156
    should store more blocks to handle reorgs.
157
158
    Parameters
159
    ----------
160
    chain :
161
        History and current state.
162
    block :
163
        Block to apply to `chain`.
164
    """
165
    validate_header(chain, block.header)
166
    validate_ommers(block.ommers, block.header, chain)
167
168
    block_env = vm.BlockEnvironment(
169
        chain_id=chain.chain_id,
170
        state=chain.state,
171
        block_gas_limit=block.header.gas_limit,
172
        block_hashes=get_last_256_block_hashes(chain),
173
        coinbase=block.header.coinbase,
174
        number=block.header.number,
175
        time=block.header.timestamp,
176
        difficulty=block.header.difficulty,
177
    )
178
179
    block_output = apply_body(
180
        block_env=block_env,
181
        transactions=block.transactions,
182
        ommers=block.ommers,
183
    )
184
    block_state_root = state_root(block_env.state)
185
    transactions_root = root(block_output.transactions_trie)
186
    receipt_root = root(block_output.receipts_trie)
187
    block_logs_bloom = logs_bloom(block_output.block_logs)
188
189
    if block_output.block_gas_used != block.header.gas_used:
190
        raise InvalidBlock(
191
            f"{block_output.block_gas_used} != {block.header.gas_used}"
192
        )
193
    if transactions_root != block.header.transactions_root:
194
        raise InvalidBlock
195
    if block_state_root != block.header.state_root:
196
        raise InvalidBlock
197
    if receipt_root != block.header.receipt_root:
198
        raise InvalidBlock
199
    if block_logs_bloom != block.header.bloom:
200
        raise InvalidBlock
201
202
    chain.blocks.append(block)
203
    if len(chain.blocks) > 255:
204
        # Real clients have to store more blocks to deal with reorgs, but the
205
        # protocol only requires the last 255
206
        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

chain : History and current state. header : Header to check for correctness.

def validate_header(chain: BlockChain, ​​header: Header) -> None:
210
    """
211
    Verifies a block header.
212
213
    In order to consider a block's header valid, the logic for the
214
    quantities in the header should match the logic for the block itself.
215
    For example the header timestamp should be greater than the block's parent
216
    timestamp because the block was created *after* the parent block.
217
    Additionally, the block's number should be directly following the parent
218
    block's number since it is the next block in the sequence.
219
220
    Parameters
221
    ----------
222
    chain :
223
        History and current state.
224
    header :
225
        Header to check for correctness.
226
    """
227
    if header.number < Uint(1):
228
        raise InvalidBlock
229
    parent_header_number = header.number - Uint(1)
230
    first_block_number = chain.blocks[0].header.number
231
    last_block_number = chain.blocks[-1].header.number
232
233
    if (
234
        parent_header_number < first_block_number
235
        or parent_header_number > last_block_number
236
    ):
237
        raise InvalidBlock
238
239
    parent_header = chain.blocks[
240
        parent_header_number - first_block_number
241
    ].header
242
243
    if header.gas_used > header.gas_limit:
244
        raise InvalidBlock
245
246
    parent_has_ommers = parent_header.ommers_hash != EMPTY_OMMER_HASH
247
    if header.timestamp <= parent_header.timestamp:
248
        raise InvalidBlock
249
    if header.number != parent_header.number + Uint(1):
250
        raise InvalidBlock
251
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
252
        raise InvalidBlock
253
    if len(header.extra_data) > 32:
254
        raise InvalidBlock
255
256
    block_difficulty = calculate_block_difficulty(
257
        header.number,
258
        header.timestamp,
259
        parent_header.timestamp,
260
        parent_header.difficulty,
261
        parent_has_ommers,
262
    )
263
    if header.difficulty != block_difficulty:
264
        raise InvalidBlock
265
266
    block_parent_hash = keccak256(rlp.encode(parent_header))
267
    if header.parent_hash != block_parent_hash:
268
        raise InvalidBlock
269
270
    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:
274
    """
275
    Generate rlp hash of the header which is to be used for Proof-of-Work
276
    verification.
277
278
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
279
    while calculating this hash.
280
281
    A particular PoW is valid for a single hash, that hash is computed by
282
    this function. The `nonce` and `mix_digest` are omitted from this hash
283
    because they are being changed by miners in their search for a sufficient
284
    proof-of-work.
285
286
    Parameters
287
    ----------
288
    header :
289
        The header object for which the hash is to be generated.
290
291
    Returns
292
    -------
293
    hash : `Hash32`
294
        The PoW valid rlp hash of the passed in header.
295
    """
296
    header_data_without_pow_artefacts = (
297
        header.parent_hash,
298
        header.ommers_hash,
299
        header.coinbase,
300
        header.state_root,
301
        header.transactions_root,
302
        header.receipt_root,
303
        header.bloom,
304
        header.difficulty,
305
        header.number,
306
        header.gas_limit,
307
        header.gas_used,
308
        header.timestamp,
309
        header.extra_data,
310
    )
311
312
    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:
316
    """
317
    Validates the Proof of Work constraints.
318
319
    In order to verify that a miner's proof-of-work is valid for a block, a
320
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
321
    hash function. The mix digest is a hash of the header and the nonce that
322
    is passed through and it confirms whether or not proof-of-work was done
323
    on the correct block. The result is the actual hash value of the block.
324
325
    Parameters
326
    ----------
327
    header :
328
        Header of interest.
329
    """
330
    header_hash = generate_header_hash_for_pow(header)
331
    # TODO: Memoize this somewhere and read from that data instead of
332
    # calculating cache for every block validation.
333
    cache = generate_cache(header.number)
334
    mix_digest, result = hashimoto_light(
335
        header_hash, header.nonce, cache, dataset_size(header.number)
336
    )
337
    if mix_digest != header.mix_digest:
338
        raise InvalidBlock
339
340
    limit = Uint(U256.MAX_VALUE) + Uint(1)
341
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
342
        raise InvalidBlock

check_transaction

Check if the transaction is includable in the block.

Parameters

block_env : The block scoped environment. block_output : The block output for the current block. tx : The transaction.

Returns

sender_address : The sender of the transaction.

Raises

GasUsedExceedsLimitError : If the gas used by the transaction exceeds the block's gas limit. NonceMismatchError : If the nonce of the transaction is not equal to the sender's nonce. InsufficientBalanceError : If the sender's balance is not enough to pay for the transaction. InvalidSenderError : If the transaction is from an address that does not exist anymore.

def check_transaction(block_env: ethereum.berlin.vm.BlockEnvironment, ​​block_output: ethereum.berlin.vm.BlockOutput, ​​tx: Transaction) -> Address:
350
    """
351
    Check if the transaction is includable in the block.
352
353
    Parameters
354
    ----------
355
    block_env :
356
        The block scoped environment.
357
    block_output :
358
        The block output for the current block.
359
    tx :
360
        The transaction.
361
362
    Returns
363
    -------
364
    sender_address :
365
        The sender of the transaction.
366
367
    Raises
368
    ------
369
    GasUsedExceedsLimitError :
370
        If the gas used by the transaction exceeds the block's gas limit.
371
    NonceMismatchError :
372
        If the nonce of the transaction is not equal to the sender's nonce.
373
    InsufficientBalanceError :
374
        If the sender's balance is not enough to pay for the transaction.
375
    InvalidSenderError :
376
        If the transaction is from an address that does not exist anymore.
377
    """
378
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
379
    if tx.gas > gas_available:
380
        raise GasUsedExceedsLimitError("gas used exceeds limit")
381
    sender_address = recover_sender(block_env.chain_id, tx)
382
    sender_account = get_account(block_env.state, sender_address)
383
384
    max_gas_fee = tx.gas * tx.gas_price
385
386
    if sender_account.nonce > Uint(tx.nonce):
387
        raise NonceMismatchError("nonce too low")
388
    elif sender_account.nonce < Uint(tx.nonce):
389
        raise NonceMismatchError("nonce too high")
390
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
391
        raise InsufficientBalanceError("insufficient sender balance")
392
    if sender_account.code:
393
        raise InvalidSenderError("not EOA")
394
395
    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[EthereumException], ​​cumulative_gas_used: Uint, ​​logs: Tuple[Log, ...]) -> Bytes | Receipt:
404
    """
405
    Make the receipt for a transaction that was executed.
406
407
    Parameters
408
    ----------
409
    tx :
410
        The executed transaction.
411
    error :
412
        Error in the top level frame of the transaction, if any.
413
    cumulative_gas_used :
414
        The total gas used so far in the block after the transaction was
415
        executed.
416
    logs :
417
        The logs produced by the transaction.
418
419
    Returns
420
    -------
421
    receipt :
422
        The receipt for the transaction.
423
    """
424
    receipt = Receipt(
425
        succeeded=error is None,
426
        cumulative_gas_used=cumulative_gas_used,
427
        bloom=logs_bloom(logs),
428
        logs=logs,
429
    )
430
431
    return encode_receipt(tx, receipt)

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

block_env : The block scoped environment. transactions : Transactions included in the block. ommers : Headers of ancestor blocks which are not direct parents (formerly uncles.)

Returns

block_output : The block output for the current block.

def apply_body(block_env: ethereum.berlin.vm.BlockEnvironment, ​​transactions: Tuple[LegacyTransaction | Bytes, ...], ​​ommers: Tuple[Header, ...]) -> ethereum.berlin.vm.BlockOutput:
439
    """
440
    Executes a block.
441
442
    Many of the contents of a block are stored in data structures called
443
    tries. There is a transactions trie which is similar to a ledger of the
444
    transactions stored in the current block. There is also a receipts trie
445
    which stores the results of executing a transaction, like the post state
446
    and gas used. This function creates and executes the block that is to be
447
    added to the chain.
448
449
    Parameters
450
    ----------
451
    block_env :
452
        The block scoped environment.
453
    transactions :
454
        Transactions included in the block.
455
    ommers :
456
        Headers of ancestor blocks which are not direct parents (formerly
457
        uncles.)
458
459
    Returns
460
    -------
461
    block_output :
462
        The block output for the current block.
463
    """
464
    block_output = vm.BlockOutput()
465
466
    for i, tx in enumerate(map(decode_transaction, transactions)):
467
        process_transaction(block_env, block_output, tx, Uint(i))
468
469
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
470
471
    return block_output

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:
477
    """
478
    Validates the ommers mentioned in the block.
479
480
    An ommer block is a block that wasn't canonically added to the
481
    blockchain because it wasn't validated as fast as the canonical block
482
    but was mined at the same time.
483
484
    To be considered valid, the ommers must adhere to the rules defined in
485
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
486
    there cannot be duplicate ommers in a block. Many of the other ommer
487
    constraints are listed in the in-line comments of this function.
488
489
    Parameters
490
    ----------
491
    ommers :
492
        List of ommers mentioned in the current block.
493
    block_header:
494
        The header of current block.
495
    chain :
496
        History and current state.
497
    """
498
    block_hash = keccak256(rlp.encode(block_header))
499
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
500
        raise InvalidBlock
501
502
    if len(ommers) == 0:
503
        # Nothing to validate
504
        return
505
506
    # Check that each ommer satisfies the constraints of a header
507
    for ommer in ommers:
508
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
509
            raise InvalidBlock
510
        validate_header(chain, ommer)
511
    if len(ommers) > 2:
512
        raise InvalidBlock
513
514
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
515
    if len(ommers_hashes) != len(set(ommers_hashes)):
516
        raise InvalidBlock
517
518
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
519
    recent_canonical_block_hashes = {
520
        keccak256(rlp.encode(block.header))
521
        for block in recent_canonical_blocks
522
    }
523
    recent_ommers_hashes: Set[Hash32] = set()
524
    for block in recent_canonical_blocks:
525
        recent_ommers_hashes = recent_ommers_hashes.union(
526
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
527
        )
528
529
    for ommer_index, ommer in enumerate(ommers):
530
        ommer_hash = ommers_hashes[ommer_index]
531
        if ommer_hash == block_hash:
532
            raise InvalidBlock
533
        if ommer_hash in recent_canonical_block_hashes:
534
            raise InvalidBlock
535
        if ommer_hash in recent_ommers_hashes:
536
            raise InvalidBlock
537
538
        # Ommer age with respect to the current block. For example, an age of
539
        # 1 indicates that the ommer is a sibling of previous block.
540
        ommer_age = block_header.number - ommer.number
541
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
542
            raise InvalidBlock
543
        if ommer.parent_hash not in recent_canonical_block_hashes:
544
            raise InvalidBlock
545
        if ommer.parent_hash == block_header.parent_hash:
546
            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:
555
    """
556
    Pay rewards to the block miner as well as the ommers miners.
557
558
    The miner of the canonical block is rewarded with the predetermined
559
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
560
    number of ommer blocks that were mined around the same time, and included
561
    in the canonical block's header. An ommer block is a block that wasn't
562
    added to the canonical blockchain because it wasn't validated as fast as
563
    the accepted block but was mined at the same time. Although not all blocks
564
    that are mined are added to the canonical chain, miners are still paid a
565
    reward for their efforts. This reward is called an ommer reward and is
566
    calculated based on the number associated with the ommer block that they
567
    mined.
568
569
    Parameters
570
    ----------
571
    state :
572
        Current account state.
573
    block_number :
574
        Position of the block within the chain.
575
    coinbase :
576
        Address of account which receives block reward and transaction fees.
577
    ommers :
578
        List of ommers mentioned in the current block.
579
    """
580
    ommer_count = U256(len(ommers))
581
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
582
    create_ether(state, coinbase, miner_reward)
583
584
    for ommer in ommers:
585
        # Ommer age with respect to the current block.
586
        ommer_age = U256(block_number - ommer.number)
587
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
588
        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

block_env : Environment for the Ethereum Virtual Machine. block_output : The block output for the current block. tx : Transaction to execute. index: Index of the transaction in the block.

def process_transaction(block_env: ethereum.berlin.vm.BlockEnvironment, ​​block_output: ethereum.berlin.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
597
    """
598
    Execute a transaction against the provided environment.
599
600
    This function processes the actions needed to execute a transaction.
601
    It decrements the sender's account after calculating the gas fee and
602
    refunds them the proper amount after execution. Calling contracts,
603
    deploying code, and incrementing nonces are all examples of actions that
604
    happen within this function or from a call made within this function.
605
606
    Accounts that are marked for deletion are processed and destroyed after
607
    execution.
608
609
    Parameters
610
    ----------
611
    block_env :
612
        Environment for the Ethereum Virtual Machine.
613
    block_output :
614
        The block output for the current block.
615
    tx :
616
        Transaction to execute.
617
    index:
618
        Index of the transaction in the block.
619
    """
620
    trie_set(
621
        block_output.transactions_trie,
622
        rlp.encode(index),
623
        encode_transaction(tx),
624
    )
625
626
    intrinsic_gas = validate_transaction(tx)
627
628
    sender = check_transaction(
629
        block_env=block_env,
630
        block_output=block_output,
631
        tx=tx,
632
    )
633
634
    sender_account = get_account(block_env.state, sender)
635
636
    gas = tx.gas - intrinsic_gas
637
    increment_nonce(block_env.state, sender)
638
639
    gas_fee = tx.gas * tx.gas_price
640
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
641
    set_account_balance(
642
        block_env.state, sender, U256(sender_balance_after_gas_fee)
643
    )
644
645
    access_list_addresses = set()
646
    access_list_storage_keys = set()
647
    if isinstance(tx, AccessListTransaction):
648
        for access in tx.access_list:
649
            access_list_addresses.add(access.account)
650
            for slot in access.slots:
651
                access_list_storage_keys.add((access.account, slot))
652
653
    tx_env = vm.TransactionEnvironment(
654
        origin=sender,
655
        gas_price=tx.gas_price,
656
        gas=gas,
657
        access_list_addresses=access_list_addresses,
658
        access_list_storage_keys=access_list_storage_keys,
659
        index_in_block=index,
660
        tx_hash=get_transaction_hash(encode_transaction(tx)),
661
        traces=[],
662
    )
663
664
    message = prepare_message(block_env, tx_env, tx)
665
666
    tx_output = process_message_call(message)
667
668
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
669
    tx_gas_refund = min(
670
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
671
    )
672
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
673
    tx_gas_left = tx.gas - tx_gas_used_after_refund
674
    gas_refund_amount = tx_gas_left * tx.gas_price
675
676
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
677
678
    # refund gas
679
    sender_balance_after_refund = get_account(
680
        block_env.state, sender
681
    ).balance + U256(gas_refund_amount)
682
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
683
684
    # transfer miner fees
685
    coinbase_balance_after_mining_fee = get_account(
686
        block_env.state, block_env.coinbase
687
    ).balance + U256(transaction_fee)
688
    if coinbase_balance_after_mining_fee != 0:
689
        set_account_balance(
690
            block_env.state,
691
            block_env.coinbase,
692
            coinbase_balance_after_mining_fee,
693
        )
694
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
695
        destroy_account(block_env.state, block_env.coinbase)
696
697
    for address in tx_output.accounts_to_delete:
698
        destroy_account(block_env.state, address)
699
700
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
701
702
    block_output.block_gas_used += tx_gas_used_after_refund
703
704
    receipt = make_receipt(
705
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
706
    )
707
708
    receipt_key = rlp.encode(Uint(index))
709
    block_output.receipt_keys += (receipt_key,)
710
711
    trie_set(
712
        block_output.receipts_trie,
713
        receipt_key,
714
        receipt,
715
    )
716
717
    block_output.block_logs += tx_output.logs

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:
721
    """
722
    Validates the gas limit for a block.
723
724
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
725
    quotient of the parent block's gas limit and the
726
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
727
    passed through as a parameter is greater than or equal to the *sum* of
728
    the parent's gas and the adjustment delta then the limit for gas is too
729
    high and fails this function's check. Similarly, if the limit is less
730
    than or equal to the *difference* of the parent's gas and the adjustment
731
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
732
    check fails because the gas limit doesn't allow for a sufficient or
733
    reasonable amount of gas to be used on a block.
734
735
    Parameters
736
    ----------
737
    gas_limit :
738
        Gas limit to validate.
739
740
    parent_gas_limit :
741
        Gas limit of the parent block.
742
743
    Returns
744
    -------
745
    check : `bool`
746
        True if gas limit constraints are satisfied, False otherwise.
747
    """
748
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
749
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
750
        return False
751
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
752
        return False
753
    if gas_limit < GAS_LIMIT_MINIMUM:
754
        return False
755
756
    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:
766
    """
767
    Computes difficulty of a block using its header and parent header.
768
769
    The difficulty is determined by the time the block was created after its
770
    parent. The ``offset`` is calculated using the parent block's difficulty,
771
    ``parent_difficulty``, and the timestamp between blocks. This offset is
772
    then added to the parent difficulty and is stored as the ``difficulty``
773
    variable. If the time between the block and its parent is too short, the
774
    offset will result in a positive number thus making the sum of
775
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
776
    avoid mass forking. But, if the time is long enough, then the offset
777
    results in a negative value making the block less difficult than
778
    its parent.
779
780
    The base standard for a block's difficulty is the predefined value
781
    set for the genesis block since it has no parent. So, a block
782
    can't be less difficult than the genesis block, therefore each block's
783
    difficulty is set to the maximum value between the calculated
784
    difficulty and the ``GENESIS_DIFFICULTY``.
785
786
    Parameters
787
    ----------
788
    block_number :
789
        Block number of the block.
790
    block_timestamp :
791
        Timestamp of the block.
792
    parent_timestamp :
793
        Timestamp of the parent block.
794
    parent_difficulty :
795
        difficulty of the parent block.
796
    parent_has_ommers:
797
        does the parent have ommers.
798
799
    Returns
800
    -------
801
    difficulty : `ethereum.base_types.Uint`
802
        Computed difficulty for a block.
803
    """
804
    offset = (
805
        int(parent_difficulty)
806
        // 2048
807
        * max(
808
            (2 if parent_has_ommers else 1)
809
            - int(block_timestamp - parent_timestamp) // 9,
810
            -99,
811
        )
812
    )
813
    difficulty = int(parent_difficulty) + offset
814
    # Historical Note: The difficulty bomb was not present in Ethereum at the
815
    # start of Frontier, but was added shortly after launch. However since the
816
    # bomb has no effect prior to block 200000 we pretend it existed from
817
    # genesis.
818
    # See https://github.com/ethereum/go-ethereum/pull/1588
819
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
820
    if num_bomb_periods >= 0:
821
        difficulty += 2**num_bomb_periods
822
823
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
824
    # the bomb. This bug does not matter because the difficulty is always much
825
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
826
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))