ethereum.forks.muir_glacier.forkethereum.forks.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
    """
101
    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]:
105
    """
106
    Obtain the list of hashes of the previous 256 blocks in order of
107
    increasing block number.
108
109
    This function will return less hashes for the first 256 blocks.
110
111
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
112
    therefore this function retrieves them.
113
114
    Parameters
115
    ----------
116
    chain :
117
        History and current state.
118
119
    Returns
120
    -------
121
    recent_block_hashes : `List[Hash32]`
122
        Hashes of the recent 256 blocks in order of increasing block number.
123
124
    """
125
    recent_blocks = chain.blocks[-255:]
126
    # TODO: This function has not been tested rigorously
127
    if len(recent_blocks) == 0:
128
        return []
129
130
    recent_block_hashes = []
131
132
    for block in recent_blocks:
133
        prev_block_hash = block.header.parent_hash
134
        recent_block_hashes.append(prev_block_hash)
135
136
    # We are computing the hash only for the most recent block and not for
137
    # the rest of the blocks as they have successors which have the hash of
138
    # the current block as parent hash.
139
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
140
    recent_block_hashes.append(most_recent_block_hash)
141
142
    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:
146
    """
147
    Attempts to apply a block to an existing block chain.
148
149
    All parts of the block's contents need to be verified before being added
150
    to the chain. Blocks are verified by ensuring that the contents of the
151
    block make logical sense with the contents of the parent block. The
152
    information in the block's header must also match the corresponding
153
    information in the block.
154
155
    To implement Ethereum, in theory clients are only required to store the
156
    most recent 255 blocks of the chain since as far as execution is
157
    concerned, only those blocks are accessed. Practically, however, clients
158
    should store more blocks to handle reorgs.
159
160
    Parameters
161
    ----------
162
    chain :
163
        History and current state.
164
    block :
165
        Block to apply to `chain`.
166
167
    """
168
    validate_header(chain, block.header)
169
    validate_ommers(block.ommers, block.header, chain)
170
171
    block_env = vm.BlockEnvironment(
172
        chain_id=chain.chain_id,
173
        state=chain.state,
174
        block_gas_limit=block.header.gas_limit,
175
        block_hashes=get_last_256_block_hashes(chain),
176
        coinbase=block.header.coinbase,
177
        number=block.header.number,
178
        time=block.header.timestamp,
179
        difficulty=block.header.difficulty,
180
    )
181
182
    block_output = apply_body(
183
        block_env=block_env,
184
        transactions=block.transactions,
185
        ommers=block.ommers,
186
    )
187
    block_state_root = state_root(block_env.state)
188
    transactions_root = root(block_output.transactions_trie)
189
    receipt_root = root(block_output.receipts_trie)
190
    block_logs_bloom = logs_bloom(block_output.block_logs)
191
192
    if block_output.block_gas_used != block.header.gas_used:
193
        raise InvalidBlock(
194
            f"{block_output.block_gas_used} != {block.header.gas_used}"
195
        )
196
    if transactions_root != block.header.transactions_root:
197
        raise InvalidBlock
198
    if block_state_root != block.header.state_root:
199
        raise InvalidBlock
200
    if receipt_root != block.header.receipt_root:
201
        raise InvalidBlock
202
    if block_logs_bloom != block.header.bloom:
203
        raise InvalidBlock
204
205
    chain.blocks.append(block)
206
    if len(chain.blocks) > 255:
207
        # Real clients have to store more blocks to deal with reorgs, but the
208
        # protocol only requires the last 255
209
        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:
213
    """
214
    Verifies a block header.
215
216
    In order to consider a block's header valid, the logic for the
217
    quantities in the header should match the logic for the block itself.
218
    For example the header timestamp should be greater than the block's parent
219
    timestamp because the block was created *after* the parent block.
220
    Additionally, the block's number should be directly following the parent
221
    block's number since it is the next block in the sequence.
222
223
    Parameters
224
    ----------
225
    chain :
226
        History and current state.
227
    header :
228
        Header to check for correctness.
229
230
    """
231
    if header.number < Uint(1):
232
        raise InvalidBlock
233
    parent_header_number = header.number - Uint(1)
234
    first_block_number = chain.blocks[0].header.number
235
    last_block_number = chain.blocks[-1].header.number
236
237
    if (
238
        parent_header_number < first_block_number
239
        or parent_header_number > last_block_number
240
    ):
241
        raise InvalidBlock
242
243
    parent_header = chain.blocks[
244
        parent_header_number - first_block_number
245
    ].header
246
247
    if header.gas_used > header.gas_limit:
248
        raise InvalidBlock
249
250
    parent_has_ommers = parent_header.ommers_hash != EMPTY_OMMER_HASH
251
    if header.timestamp <= parent_header.timestamp:
252
        raise InvalidBlock
253
    if header.number != parent_header.number + Uint(1):
254
        raise InvalidBlock
255
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
256
        raise InvalidBlock
257
    if len(header.extra_data) > 32:
258
        raise InvalidBlock
259
260
    block_difficulty = calculate_block_difficulty(
261
        header.number,
262
        header.timestamp,
263
        parent_header.timestamp,
264
        parent_header.difficulty,
265
        parent_has_ommers,
266
    )
267
    if header.difficulty != block_difficulty:
268
        raise InvalidBlock
269
270
    block_parent_hash = keccak256(rlp.encode(parent_header))
271
    if header.parent_hash != block_parent_hash:
272
        raise InvalidBlock
273
274
    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:
278
    """
279
    Generate rlp hash of the header which is to be used for Proof-of-Work
280
    verification.
281
282
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
283
    while calculating this hash.
284
285
    A particular PoW is valid for a single hash, that hash is computed by
286
    this function. The `nonce` and `mix_digest` are omitted from this hash
287
    because they are being changed by miners in their search for a sufficient
288
    proof-of-work.
289
290
    Parameters
291
    ----------
292
    header :
293
        The header object for which the hash is to be generated.
294
295
    Returns
296
    -------
297
    hash : `Hash32`
298
        The PoW valid rlp hash of the passed in header.
299
300
    """
301
    header_data_without_pow_artefacts = (
302
        header.parent_hash,
303
        header.ommers_hash,
304
        header.coinbase,
305
        header.state_root,
306
        header.transactions_root,
307
        header.receipt_root,
308
        header.bloom,
309
        header.difficulty,
310
        header.number,
311
        header.gas_limit,
312
        header.gas_used,
313
        header.timestamp,
314
        header.extra_data,
315
    )
316
317
    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:
321
    """
322
    Validates the Proof of Work constraints.
323
324
    In order to verify that a miner's proof-of-work is valid for a block, a
325
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
326
    hash function. The mix digest is a hash of the header and the nonce that
327
    is passed through and it confirms whether or not proof-of-work was done
328
    on the correct block. The result is the actual hash value of the block.
329
330
    Parameters
331
    ----------
332
    header :
333
        Header of interest.
334
335
    """
336
    header_hash = generate_header_hash_for_pow(header)
337
    # TODO: Memoize this somewhere and read from that data instead of
338
    # calculating cache for every block validation.
339
    cache = generate_cache(header.number)
340
    mix_digest, result = hashimoto_light(
341
        header_hash, header.nonce, cache, dataset_size(header.number)
342
    )
343
    if mix_digest != header.mix_digest:
344
        raise InvalidBlock
345
346
    limit = Uint(U256.MAX_VALUE) + Uint(1)
347
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
348
        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.forks.muir_glacier.vm.BlockEnvironmentethereum.forks.berlin.vm.BlockEnvironment, ​​block_output: ethereum.forks.muir_glacier.vm.BlockOutputethereum.forks.berlin.vm.BlockOutput, ​​tx: Transaction) -> Address:
356
    """
357
    Check if the transaction is includable in the block.
358
359
    Parameters
360
    ----------
361
    block_env :
362
        The block scoped environment.
363
    block_output :
364
        The block output for the current block.
365
    tx :
366
        The transaction.
367
368
    Returns
369
    -------
370
    sender_address :
371
        The sender of the transaction.
372
373
    Raises
374
    ------
375
    GasUsedExceedsLimitError :
376
        If the gas used by the transaction exceeds the block's gas limit.
377
    NonceMismatchError :
378
        If the nonce of the transaction is not equal to the sender's nonce.
379
    InsufficientBalanceError :
380
        If the sender's balance is not enough to pay for the transaction.
381
    InvalidSenderError :
382
        If the transaction is from an address that does not exist anymore.
383
384
    """
385
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
386
    if tx.gas > gas_available:
387
        raise GasUsedExceedsLimitError("gas used exceeds limit")
388
    sender_address = recover_sender(block_env.chain_id, tx)
389
    sender_account = get_account(block_env.state, sender_address)
390
391
    max_gas_fee = tx.gas * tx.gas_price
392
393
    if sender_account.nonce > Uint(tx.nonce):
394
        raise NonceMismatchError("nonce too low")
395
    elif sender_account.nonce < Uint(tx.nonce):
396
        raise NonceMismatchError("nonce too high")
397
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
398
        raise InsufficientBalanceError("insufficient sender balance")
399
    if sender_account.code:
400
        raise InvalidSenderError("not EOA")
401
402
    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, ...]) -> ReceiptBytes | Receipt:
411
    """
412
    Make the receipt for a transaction that was executed.
413
414
    Parameters
415
    ----------
416
    tx :
417
        The executed transaction.
418
    error :
419
        Error in the top level frame of the transaction, if any.
420
    cumulative_gas_used :
421
        The total gas used so far in the block after the transaction was
422
        executed.
423
    logs :
424
        The logs produced by the transaction.
425
426
    Returns
427
    -------
428
    receipt :
429
        The receipt for the transaction.
430
431
    """
432
    receipt = Receipt(
433
        succeeded=error is None,
434
        cumulative_gas_used=cumulative_gas_used,
435
        bloom=logs_bloom(logs),
436
        logs=logs,
437
    )
438
433
    return receipt
439
    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.forks.muir_glacier.vm.BlockEnvironmentethereum.forks.berlin.vm.BlockEnvironment, ​​transactions: Tuple[TransactionLegacyTransaction | Bytes, ...], ​​ommers: Tuple[Header, ...]) -> ethereum.forks.muir_glacier.vm.BlockOutputethereum.forks.berlin.vm.BlockOutput:
447
    """
448
    Executes a block.
449
450
    Many of the contents of a block are stored in data structures called
451
    tries. There is a transactions trie which is similar to a ledger of the
452
    transactions stored in the current block. There is also a receipts trie
453
    which stores the results of executing a transaction, like the post state
454
    and gas used. This function creates and executes the block that is to be
455
    added to the chain.
456
457
    Parameters
458
    ----------
459
    block_env :
460
        The block scoped environment.
461
    transactions :
462
        Transactions included in the block.
463
    ommers :
464
        Headers of ancestor blocks which are not direct parents (formerly
465
        uncles.)
466
467
    Returns
468
    -------
469
    block_output :
470
        The block output for the current block.
471
472
    """
473
    block_output = vm.BlockOutput()
474
469
    for i, tx in enumerate(transactions):
475
    for i, tx in enumerate(map(decode_transaction, transactions)):
476
        process_transaction(block_env, block_output, tx, Uint(i))
477
478
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
479
480
    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:
486
    """
487
    Validates the ommers mentioned in the block.
488
489
    An ommer block is a block that wasn't canonically added to the
490
    blockchain because it wasn't validated as fast as the canonical block
491
    but was mined at the same time.
492
493
    To be considered valid, the ommers must adhere to the rules defined in
494
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
495
    there cannot be duplicate ommers in a block. Many of the other ommer
496
    constraints are listed in the in-line comments of this function.
497
498
    Parameters
499
    ----------
500
    ommers :
501
        List of ommers mentioned in the current block.
502
    block_header:
503
        The header of current block.
504
    chain :
505
        History and current state.
506
507
    """
508
    block_hash = keccak256(rlp.encode(block_header))
509
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
510
        raise InvalidBlock
511
512
    if len(ommers) == 0:
513
        # Nothing to validate
514
        return
515
516
    # Check that each ommer satisfies the constraints of a header
517
    for ommer in ommers:
518
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
519
            raise InvalidBlock
520
        validate_header(chain, ommer)
521
    if len(ommers) > 2:
522
        raise InvalidBlock
523
524
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
525
    if len(ommers_hashes) != len(set(ommers_hashes)):
526
        raise InvalidBlock
527
528
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
529
    recent_canonical_block_hashes = {
530
        keccak256(rlp.encode(block.header))
531
        for block in recent_canonical_blocks
532
    }
533
    recent_ommers_hashes: Set[Hash32] = set()
534
    for block in recent_canonical_blocks:
535
        recent_ommers_hashes = recent_ommers_hashes.union(
536
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
537
        )
538
539
    for ommer_index, ommer in enumerate(ommers):
540
        ommer_hash = ommers_hashes[ommer_index]
541
        if ommer_hash == block_hash:
542
            raise InvalidBlock
543
        if ommer_hash in recent_canonical_block_hashes:
544
            raise InvalidBlock
545
        if ommer_hash in recent_ommers_hashes:
546
            raise InvalidBlock
547
548
        # Ommer age with respect to the current block. For example, an age of
549
        # 1 indicates that the ommer is a sibling of previous block.
550
        ommer_age = block_header.number - ommer.number
551
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
552
            raise InvalidBlock
553
        if ommer.parent_hash not in recent_canonical_block_hashes:
554
            raise InvalidBlock
555
        if ommer.parent_hash == block_header.parent_hash:
556
            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:
565
    """
566
    Pay rewards to the block miner as well as the ommers miners.
567
568
    The miner of the canonical block is rewarded with the predetermined
569
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
570
    number of ommer blocks that were mined around the same time, and included
571
    in the canonical block's header. An ommer block is a block that wasn't
572
    added to the canonical blockchain because it wasn't validated as fast as
573
    the accepted block but was mined at the same time. Although not all blocks
574
    that are mined are added to the canonical chain, miners are still paid a
575
    reward for their efforts. This reward is called an ommer reward and is
576
    calculated based on the number associated with the ommer block that they
577
    mined.
578
579
    Parameters
580
    ----------
581
    state :
582
        Current account state.
583
    block_number :
584
        Position of the block within the chain.
585
    coinbase :
586
        Address of account which receives block reward and transaction fees.
587
    ommers :
588
        List of ommers mentioned in the current block.
589
590
    """
591
    ommer_count = U256(len(ommers))
592
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
593
    create_ether(state, coinbase, miner_reward)
594
595
    for ommer in ommers:
596
        # Ommer age with respect to the current block.
597
        ommer_age = U256(block_number - ommer.number)
598
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
599
        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 balance 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.forks.muir_glacier.vm.BlockEnvironmentethereum.forks.berlin.vm.BlockEnvironment, ​​block_output: ethereum.forks.muir_glacier.vm.BlockOutputethereum.forks.berlin.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
608
    """
609
    Execute a transaction against the provided environment.
610
611
    This function processes the actions needed to execute a transaction.
612
    It decrements the sender's account balance after calculating the gas fee
613
    and refunds them the proper amount after execution. Calling contracts,
614
    deploying code, and incrementing nonces are all examples of actions that
615
    happen within this function or from a call made within this function.
616
617
    Accounts that are marked for deletion are processed and destroyed after
618
    execution.
619
620
    Parameters
621
    ----------
622
    block_env :
623
        Environment for the Ethereum Virtual Machine.
624
    block_output :
625
        The block output for the current block.
626
    tx :
627
        Transaction to execute.
628
    index:
629
        Index of the transaction in the block.
630
631
    """
626
    trie_set(block_output.transactions_trie, rlp.encode(Uint(index)), tx)
632
    trie_set(
633
        block_output.transactions_trie,
634
        rlp.encode(index),
635
        encode_transaction(tx),
636
    )
637
638
    intrinsic_gas = validate_transaction(tx)
639
640
    sender = check_transaction(
641
        block_env=block_env,
642
        block_output=block_output,
643
        tx=tx,
644
    )
645
646
    sender_account = get_account(block_env.state, sender)
647
648
    gas = tx.gas - intrinsic_gas
649
    increment_nonce(block_env.state, sender)
650
651
    gas_fee = tx.gas * tx.gas_price
652
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
653
    set_account_balance(
654
        block_env.state, sender, U256(sender_balance_after_gas_fee)
655
    )
656
657
    access_list_addresses = set()
658
    access_list_storage_keys = set()
659
    if isinstance(tx, AccessListTransaction):
660
        for access in tx.access_list:
661
            access_list_addresses.add(access.account)
662
            for slot in access.slots:
663
                access_list_storage_keys.add((access.account, slot))
664
665
    tx_env = vm.TransactionEnvironment(
666
        origin=sender,
667
        gas_price=tx.gas_price,
668
        gas=gas,
669
        access_list_addresses=access_list_addresses,
670
        access_list_storage_keys=access_list_storage_keys,
671
        index_in_block=index,
651
        tx_hash=get_transaction_hash(tx),
672
        tx_hash=get_transaction_hash(encode_transaction(tx)),
673
    )
674
675
    message = prepare_message(block_env, tx_env, tx)
676
677
    tx_output = process_message_call(message)
678
679
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
680
    tx_gas_refund = min(
681
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
682
    )
683
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
684
    tx_gas_left = tx.gas - tx_gas_used_after_refund
685
    gas_refund_amount = tx_gas_left * tx.gas_price
686
687
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
688
689
    # refund gas
690
    sender_balance_after_refund = get_account(
691
        block_env.state, sender
692
    ).balance + U256(gas_refund_amount)
693
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
694
695
    # transfer miner fees
696
    coinbase_balance_after_mining_fee = get_account(
697
        block_env.state, block_env.coinbase
698
    ).balance + U256(transaction_fee)
699
    if coinbase_balance_after_mining_fee != 0:
700
        set_account_balance(
701
            block_env.state,
702
            block_env.coinbase,
703
            coinbase_balance_after_mining_fee,
704
        )
705
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
706
        destroy_account(block_env.state, block_env.coinbase)
707
708
    for address in tx_output.accounts_to_delete:
709
        destroy_account(block_env.state, address)
710
711
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
712
713
    block_output.block_gas_used += tx_gas_used_after_refund
714
715
    receipt = make_receipt(
695
        tx_output.error, block_output.block_gas_used, tx_output.logs
716
        tx, tx_output.error, block_output.block_gas_used, tx_output.logs
717
    )
718
719
    receipt_key = rlp.encode(Uint(index))
720
    block_output.receipt_keys += (receipt_key,)
721
722
    trie_set(
723
        block_output.receipts_trie,
724
        receipt_key,
725
        receipt,
726
    )
727
728
    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:
732
    """
733
    Validates the gas limit for a block.
734
735
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
736
    quotient of the parent block's gas limit and the
737
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
738
    passed through as a parameter is greater than or equal to the *sum* of
739
    the parent's gas and the adjustment delta then the limit for gas is too
740
    high and fails this function's check. Similarly, if the limit is less
741
    than or equal to the *difference* of the parent's gas and the adjustment
742
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
743
    check fails because the gas limit doesn't allow for a sufficient or
744
    reasonable amount of gas to be used on a block.
745
746
    Parameters
747
    ----------
748
    gas_limit :
749
        Gas limit to validate.
750
751
    parent_gas_limit :
752
        Gas limit of the parent block.
753
754
    Returns
755
    -------
756
    check : `bool`
757
        True if gas limit constraints are satisfied, False otherwise.
758
759
    """
760
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
761
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
762
        return False
763
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
764
        return False
765
    if gas_limit < GAS_LIMIT_MINIMUM:
766
        return False
767
768
    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:
778
    """
779
    Computes difficulty of a block using its header and parent header.
780
781
    The difficulty is determined by the time the block was created after its
782
    parent. The ``offset`` is calculated using the parent block's difficulty,
783
    ``parent_difficulty``, and the timestamp between blocks. This offset is
784
    then added to the parent difficulty and is stored as the ``difficulty``
785
    variable. If the time between the block and its parent is too short, the
786
    offset will result in a positive number thus making the sum of
787
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
788
    avoid mass forking. But, if the time is long enough, then the offset
789
    results in a negative value making the block less difficult than
790
    its parent.
791
792
    The base standard for a block's difficulty is the predefined value
793
    set for the genesis block since it has no parent. So, a block
794
    can't be less difficult than the genesis block, therefore each block's
795
    difficulty is set to the maximum value between the calculated
796
    difficulty and the ``GENESIS_DIFFICULTY``.
797
798
    Parameters
799
    ----------
800
    block_number :
801
        Block number of the block.
802
    block_timestamp :
803
        Timestamp of the block.
804
    parent_timestamp :
805
        Timestamp of the parent block.
806
    parent_difficulty :
807
        difficulty of the parent block.
808
    parent_has_ommers:
809
        does the parent have ommers.
810
811
    Returns
812
    -------
813
    difficulty : `ethereum.base_types.Uint`
814
        Computed difficulty for a block.
815
816
    """
817
    offset = (
818
        int(parent_difficulty)
819
        // 2048
820
        * max(
821
            (2 if parent_has_ommers else 1)
822
            - int(block_timestamp - parent_timestamp) // 9,
823
            -99,
824
        )
825
    )
826
    difficulty = int(parent_difficulty) + offset
827
    # Historical Note: The difficulty bomb was not present in Ethereum at the
828
    # start of Frontier, but was added shortly after launch. However since the
829
    # bomb has no effect prior to block 200000 we pretend it existed from
830
    # genesis.
831
    # See https://github.com/ethereum/go-ethereum/pull/1588
832
    num_bomb_periods = ((int(block_number) - BOMB_DELAY_BLOCKS) // 100000) - 2
833
    if num_bomb_periods >= 0:
834
        difficulty += 2**num_bomb_periods
835
836
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
837
    # the bomb. This bug does not matter because the difficulty is always much
838
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
839
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))