ethereum.muir_glacier.forkethereum.berlin.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

59
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

60
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

61
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

62
MAX_OMMER_DEPTH = Uint(6)

BOMB_DELAY_BLOCKS

63
BOMB_DELAY_BLOCKS = 9000000

EMPTY_OMMER_HASH

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

BlockChain

History and current state of the block chain.

67
@dataclass
class BlockChain:

blocks

73
    blocks: List[Block]

state

74
    state: State

chain_id

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

InvalidBlock : If the transaction is not includable.

def check_transaction(block_env: ethereum.muir_glacier.vm.BlockEnvironmentethereum.berlin.vm.BlockEnvironment, ​​block_output: ethereum.muir_glacier.vm.BlockOutputethereum.berlin.vm.BlockOutput, ​​tx: Transaction) -> Address:
347
    """
348
    Check if the transaction is includable in the block.
349
350
    Parameters
351
    ----------
352
    block_env :
353
        The block scoped environment.
354
    block_output :
355
        The block output for the current block.
356
    tx :
357
        The transaction.
358
359
    Returns
360
    -------
361
    sender_address :
362
        The sender of the transaction.
363
364
    Raises
365
    ------
366
    InvalidBlock :
367
        If the transaction is not includable.
368
    """
369
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
370
    if tx.gas > gas_available:
371
        raise InvalidBlock
372
    sender_address = recover_sender(block_env.chain_id, tx)
373
    sender_account = get_account(block_env.state, sender_address)
374
375
    max_gas_fee = tx.gas * tx.gas_price
376
377
    if sender_account.nonce != tx.nonce:
378
        raise InvalidBlock
379
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
380
        raise InvalidBlock
381
    if sender_account.code:
382
        raise InvalidSenderError("not EOA")
383
384
    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, ...]) -> ReceiptUnion[Bytes, Receipt]:
393
    """
394
    Make the receipt for a transaction that was executed.
395
396
    Parameters
397
    ----------
398
    tx :
399
        The executed transaction.
400
    error :
401
        Error in the top level frame of the transaction, if any.
402
    cumulative_gas_used :
403
        The total gas used so far in the block after the transaction was
404
        executed.
405
    logs :
406
        The logs produced by the transaction.
407
408
    Returns
409
    -------
410
    receipt :
411
        The receipt for the transaction.
412
    """
413
    receipt = Receipt(
414
        succeeded=error is None,
415
        cumulative_gas_used=cumulative_gas_used,
416
        bloom=logs_bloom(logs),
417
        logs=logs,
418
    )
419
414
    return receipt
420
    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.muir_glacier.vm.BlockEnvironmentethereum.berlin.vm.BlockEnvironment, ​​transactions: Tuple[TransactionUnion[LegacyTransaction, Bytes], ...], ​​ommers: Tuple[Header, ...]) -> ethereum.muir_glacier.vm.BlockOutputethereum.berlin.vm.BlockOutput:
428
    """
429
    Executes a block.
430
431
    Many of the contents of a block are stored in data structures called
432
    tries. There is a transactions trie which is similar to a ledger of the
433
    transactions stored in the current block. There is also a receipts trie
434
    which stores the results of executing a transaction, like the post state
435
    and gas used. This function creates and executes the block that is to be
436
    added to the chain.
437
438
    Parameters
439
    ----------
440
    block_env :
441
        The block scoped environment.
442
    transactions :
443
        Transactions included in the block.
444
    ommers :
445
        Headers of ancestor blocks which are not direct parents (formerly
446
        uncles.)
447
448
    Returns
449
    -------
450
    block_output :
451
        The block output for the current block.
452
    """
453
    block_output = vm.BlockOutput()
454
449
    for i, tx in enumerate(transactions):
455
    for i, tx in enumerate(map(decode_transaction, transactions)):
456
        process_transaction(block_env, block_output, tx, Uint(i))
457
458
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
459
460
    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:
466
    """
467
    Validates the ommers mentioned in the block.
468
469
    An ommer block is a block that wasn't canonically added to the
470
    blockchain because it wasn't validated as fast as the canonical block
471
    but was mined at the same time.
472
473
    To be considered valid, the ommers must adhere to the rules defined in
474
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
475
    there cannot be duplicate ommers in a block. Many of the other ommer
476
    constraints are listed in the in-line comments of this function.
477
478
    Parameters
479
    ----------
480
    ommers :
481
        List of ommers mentioned in the current block.
482
    block_header:
483
        The header of current block.
484
    chain :
485
        History and current state.
486
    """
487
    block_hash = keccak256(rlp.encode(block_header))
488
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
489
        raise InvalidBlock
490
491
    if len(ommers) == 0:
492
        # Nothing to validate
493
        return
494
495
    # Check that each ommer satisfies the constraints of a header
496
    for ommer in ommers:
497
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
498
            raise InvalidBlock
499
        validate_header(chain, ommer)
500
    if len(ommers) > 2:
501
        raise InvalidBlock
502
503
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
504
    if len(ommers_hashes) != len(set(ommers_hashes)):
505
        raise InvalidBlock
506
507
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
508
    recent_canonical_block_hashes = {
509
        keccak256(rlp.encode(block.header))
510
        for block in recent_canonical_blocks
511
    }
512
    recent_ommers_hashes: Set[Hash32] = set()
513
    for block in recent_canonical_blocks:
514
        recent_ommers_hashes = recent_ommers_hashes.union(
515
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
516
        )
517
518
    for ommer_index, ommer in enumerate(ommers):
519
        ommer_hash = ommers_hashes[ommer_index]
520
        if ommer_hash == block_hash:
521
            raise InvalidBlock
522
        if ommer_hash in recent_canonical_block_hashes:
523
            raise InvalidBlock
524
        if ommer_hash in recent_ommers_hashes:
525
            raise InvalidBlock
526
527
        # Ommer age with respect to the current block. For example, an age of
528
        # 1 indicates that the ommer is a sibling of previous block.
529
        ommer_age = block_header.number - ommer.number
530
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
531
            raise InvalidBlock
532
        if ommer.parent_hash not in recent_canonical_block_hashes:
533
            raise InvalidBlock
534
        if ommer.parent_hash == block_header.parent_hash:
535
            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:
544
    """
545
    Pay rewards to the block miner as well as the ommers miners.
546
547
    The miner of the canonical block is rewarded with the predetermined
548
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
549
    number of ommer blocks that were mined around the same time, and included
550
    in the canonical block's header. An ommer block is a block that wasn't
551
    added to the canonical blockchain because it wasn't validated as fast as
552
    the accepted block but was mined at the same time. Although not all blocks
553
    that are mined are added to the canonical chain, miners are still paid a
554
    reward for their efforts. This reward is called an ommer reward and is
555
    calculated based on the number associated with the ommer block that they
556
    mined.
557
558
    Parameters
559
    ----------
560
    state :
561
        Current account state.
562
    block_number :
563
        Position of the block within the chain.
564
    coinbase :
565
        Address of account which receives block reward and transaction fees.
566
    ommers :
567
        List of ommers mentioned in the current block.
568
    """
569
    ommer_count = U256(len(ommers))
570
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
571
    create_ether(state, coinbase, miner_reward)
572
573
    for ommer in ommers:
574
        # Ommer age with respect to the current block.
575
        ommer_age = U256(block_number - ommer.number)
576
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
577
        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.muir_glacier.vm.BlockEnvironmentethereum.berlin.vm.BlockEnvironment, ​​block_output: ethereum.muir_glacier.vm.BlockOutputethereum.berlin.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
586
    """
587
    Execute a transaction against the provided environment.
588
589
    This function processes the actions needed to execute a transaction.
590
    It decrements the sender's account after calculating the gas fee and
591
    refunds them the proper amount after execution. Calling contracts,
592
    deploying code, and incrementing nonces are all examples of actions that
593
    happen within this function or from a call made within this function.
594
595
    Accounts that are marked for deletion are processed and destroyed after
596
    execution.
597
598
    Parameters
599
    ----------
600
    block_env :
601
        Environment for the Ethereum Virtual Machine.
602
    block_output :
603
        The block output for the current block.
604
    tx :
605
        Transaction to execute.
606
    index:
607
        Index of the transaction in the block.
608
    """
603
    trie_set(block_output.transactions_trie, rlp.encode(Uint(index)), tx)
609
    trie_set(
610
        block_output.transactions_trie,
611
        rlp.encode(index),
612
        encode_transaction(tx),
613
    )
614
615
    intrinsic_gas = validate_transaction(tx)
616
617
    sender = check_transaction(
618
        block_env=block_env,
619
        block_output=block_output,
620
        tx=tx,
621
    )
622
623
    sender_account = get_account(block_env.state, sender)
624
625
    gas = tx.gas - intrinsic_gas
626
    increment_nonce(block_env.state, sender)
627
628
    gas_fee = tx.gas * tx.gas_price
629
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
630
    set_account_balance(
631
        block_env.state, sender, U256(sender_balance_after_gas_fee)
632
    )
633
634
    access_list_addresses = set()
635
    access_list_storage_keys = set()
636
    if isinstance(tx, AccessListTransaction):
637
        for access in tx.access_list:
638
            access_list_addresses.add(access.account)
639
            for slot in access.slots:
640
                access_list_storage_keys.add((access.account, slot))
641
642
    tx_env = vm.TransactionEnvironment(
643
        origin=sender,
644
        gas_price=tx.gas_price,
645
        gas=gas,
646
        access_list_addresses=access_list_addresses,
647
        access_list_storage_keys=access_list_storage_keys,
648
        index_in_block=index,
628
        tx_hash=get_transaction_hash(tx),
649
        tx_hash=get_transaction_hash(encode_transaction(tx)),
650
        traces=[],
651
    )
652
653
    message = prepare_message(block_env, tx_env, tx)
654
655
    tx_output = process_message_call(message)
656
657
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
658
    tx_gas_refund = min(
659
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
660
    )
661
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
662
    tx_gas_left = tx.gas - tx_gas_used_after_refund
663
    gas_refund_amount = tx_gas_left * tx.gas_price
664
665
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
666
667
    # refund gas
668
    sender_balance_after_refund = get_account(
669
        block_env.state, sender
670
    ).balance + U256(gas_refund_amount)
671
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
672
673
    # transfer miner fees
674
    coinbase_balance_after_mining_fee = get_account(
675
        block_env.state, block_env.coinbase
676
    ).balance + U256(transaction_fee)
677
    if coinbase_balance_after_mining_fee != 0:
678
        set_account_balance(
679
            block_env.state,
680
            block_env.coinbase,
681
            coinbase_balance_after_mining_fee,
682
        )
683
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
684
        destroy_account(block_env.state, block_env.coinbase)
685
686
    for address in tx_output.accounts_to_delete:
687
        destroy_account(block_env.state, address)
688
689
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
690
691
    block_output.block_gas_used += tx_gas_used_after_refund
692
693
    receipt = make_receipt(
673
        tx_output.error, block_output.block_gas_used, tx_output.logs
694
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
695
    )
696
697
    receipt_key = rlp.encode(Uint(index))
698
    block_output.receipt_keys += (receipt_key,)
699
700
    trie_set(
701
        block_output.receipts_trie,
702
        receipt_key,
703
        receipt,
704
    )
705
706
    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:
710
    """
711
    Validates the gas limit for a block.
712
713
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
714
    quotient of the parent block's gas limit and the
715
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
716
    passed through as a parameter is greater than or equal to the *sum* of
717
    the parent's gas and the adjustment delta then the limit for gas is too
718
    high and fails this function's check. Similarly, if the limit is less
719
    than or equal to the *difference* of the parent's gas and the adjustment
720
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
721
    check fails because the gas limit doesn't allow for a sufficient or
722
    reasonable amount of gas to be used on a block.
723
724
    Parameters
725
    ----------
726
    gas_limit :
727
        Gas limit to validate.
728
729
    parent_gas_limit :
730
        Gas limit of the parent block.
731
732
    Returns
733
    -------
734
    check : `bool`
735
        True if gas limit constraints are satisfied, False otherwise.
736
    """
737
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
738
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
739
        return False
740
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
741
        return False
742
    if gas_limit < GAS_LIMIT_MINIMUM:
743
        return False
744
745
    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:
755
    """
756
    Computes difficulty of a block using its header and parent header.
757
758
    The difficulty is determined by the time the block was created after its
759
    parent. The ``offset`` is calculated using the parent block's difficulty,
760
    ``parent_difficulty``, and the timestamp between blocks. This offset is
761
    then added to the parent difficulty and is stored as the ``difficulty``
762
    variable. If the time between the block and its parent is too short, the
763
    offset will result in a positive number thus making the sum of
764
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
765
    avoid mass forking. But, if the time is long enough, then the offset
766
    results in a negative value making the block less difficult than
767
    its parent.
768
769
    The base standard for a block's difficulty is the predefined value
770
    set for the genesis block since it has no parent. So, a block
771
    can't be less difficult than the genesis block, therefore each block's
772
    difficulty is set to the maximum value between the calculated
773
    difficulty and the ``GENESIS_DIFFICULTY``.
774
775
    Parameters
776
    ----------
777
    block_number :
778
        Block number of the block.
779
    block_timestamp :
780
        Timestamp of the block.
781
    parent_timestamp :
782
        Timestamp of the parent block.
783
    parent_difficulty :
784
        difficulty of the parent block.
785
    parent_has_ommers:
786
        does the parent have ommers.
787
788
    Returns
789
    -------
790
    difficulty : `ethereum.base_types.Uint`
791
        Computed difficulty for a block.
792
    """
793
    offset = (
794
        int(parent_difficulty)
795
        // 2048
796
        * max(
797
            (2 if parent_has_ommers else 1)
798
            - int(block_timestamp - parent_timestamp) // 9,
799
            -99,
800
        )
801
    )
802
    difficulty = int(parent_difficulty) + offset
803
    # Historical Note: The difficulty bomb was not present in Ethereum at the
804
    # start of Frontier, but was added shortly after launch. However since the
805
    # bomb has no effect prior to block 200000 we pretend it existed from
806
    # genesis.
807
    # See https://github.com/ethereum/go-ethereum/pull/1588
808
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
809
    if num_bomb_periods >= 0:
810
        difficulty += 2**num_bomb_periods
811
812
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
813
    # the bomb. This bug does not matter because the difficulty is always much
814
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
815
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))