ethereum.forks.spurious_dragon.fork

Ethereum Specification.

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

MINIMUM_DIFFICULTY

58
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

59
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

62
@dataclass
class BlockChain:

blocks

68
    blocks: List[Block]

state

69
    state: State

chain_id

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

make_receipt

Make the receipt for a transaction that was executed.

Parameters

post_state : The state root immediately after this transaction. cumulative_gas_used : The total gas used so far in the block after the transaction was executed. logs : The logs produced by the transaction.

Returns

receipt : The receipt for the transaction.

def make_receipt(post_state: Bytes32, ​​cumulative_gas_used: Uint, ​​logs: Tuple[Log, ...]) -> Receipt:
400
    """
401
    Make the receipt for a transaction that was executed.
402
403
    Parameters
404
    ----------
405
    post_state :
406
        The state root immediately after this transaction.
407
    cumulative_gas_used :
408
        The total gas used so far in the block after the transaction was
409
        executed.
410
    logs :
411
        The logs produced by the transaction.
412
413
    Returns
414
    -------
415
    receipt :
416
        The receipt for the transaction.
417
418
    """
419
    receipt = Receipt(
420
        post_state=post_state,
421
        cumulative_gas_used=cumulative_gas_used,
422
        bloom=logs_bloom(logs),
423
        logs=logs,
424
    )
425
426
    return 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.spurious_dragon.vm.BlockEnvironment, ​​transactions: Tuple[Transaction, ...], ​​ommers: Tuple[Header, ...]) -> ethereum.forks.spurious_dragon.vm.BlockOutput:
434
    """
435
    Executes a block.
436
437
    Many of the contents of a block are stored in data structures called
438
    tries. There is a transactions trie which is similar to a ledger of the
439
    transactions stored in the current block. There is also a receipts trie
440
    which stores the results of executing a transaction, like the post state
441
    and gas used. This function creates and executes the block that is to be
442
    added to the chain.
443
444
    Parameters
445
    ----------
446
    block_env :
447
        The block scoped environment.
448
    transactions :
449
        Transactions included in the block.
450
    ommers :
451
        Headers of ancestor blocks which are not direct parents (formerly
452
        uncles.)
453
454
    Returns
455
    -------
456
    block_output :
457
        The block output for the current block.
458
459
    """
460
    block_output = vm.BlockOutput()
461
462
    for i, tx in enumerate(transactions):
463
        process_transaction(block_env, block_output, tx, Uint(i))
464
465
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
466
467
    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:
473
    """
474
    Validates the ommers mentioned in the block.
475
476
    An ommer block is a block that wasn't canonically added to the
477
    blockchain because it wasn't validated as fast as the canonical block
478
    but was mined at the same time.
479
480
    To be considered valid, the ommers must adhere to the rules defined in
481
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
482
    there cannot be duplicate ommers in a block. Many of the other ommer
483
    constraints are listed in the in-line comments of this function.
484
485
    Parameters
486
    ----------
487
    ommers :
488
        List of ommers mentioned in the current block.
489
    block_header:
490
        The header of current block.
491
    chain :
492
        History and current state.
493
494
    """
495
    block_hash = keccak256(rlp.encode(block_header))
496
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
497
        raise InvalidBlock
498
499
    if len(ommers) == 0:
500
        # Nothing to validate
501
        return
502
503
    # Check that each ommer satisfies the constraints of a header
504
    for ommer in ommers:
505
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
506
            raise InvalidBlock
507
        validate_header(chain, ommer)
508
    if len(ommers) > 2:
509
        raise InvalidBlock
510
511
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
512
    if len(ommers_hashes) != len(set(ommers_hashes)):
513
        raise InvalidBlock
514
515
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
516
    recent_canonical_block_hashes = {
517
        keccak256(rlp.encode(block.header))
518
        for block in recent_canonical_blocks
519
    }
520
    recent_ommers_hashes: Set[Hash32] = set()
521
    for block in recent_canonical_blocks:
522
        recent_ommers_hashes = recent_ommers_hashes.union(
523
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
524
        )
525
526
    for ommer_index, ommer in enumerate(ommers):
527
        ommer_hash = ommers_hashes[ommer_index]
528
        if ommer_hash == block_hash:
529
            raise InvalidBlock
530
        if ommer_hash in recent_canonical_block_hashes:
531
            raise InvalidBlock
532
        if ommer_hash in recent_ommers_hashes:
533
            raise InvalidBlock
534
535
        # Ommer age with respect to the current block. For example, an age of
536
        # 1 indicates that the ommer is a sibling of previous block.
537
        ommer_age = block_header.number - ommer.number
538
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
539
            raise InvalidBlock
540
        if ommer.parent_hash not in recent_canonical_block_hashes:
541
            raise InvalidBlock
542
        if ommer.parent_hash == block_header.parent_hash:
543
            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:
552
    """
553
    Pay rewards to the block miner as well as the ommers miners.
554
555
    The miner of the canonical block is rewarded with the predetermined
556
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
557
    number of ommer blocks that were mined around the same time, and included
558
    in the canonical block's header. An ommer block is a block that wasn't
559
    added to the canonical blockchain because it wasn't validated as fast as
560
    the accepted block but was mined at the same time. Although not all blocks
561
    that are mined are added to the canonical chain, miners are still paid a
562
    reward for their efforts. This reward is called an ommer reward and is
563
    calculated based on the number associated with the ommer block that they
564
    mined.
565
566
    Parameters
567
    ----------
568
    state :
569
        Current account state.
570
    block_number :
571
        Position of the block within the chain.
572
    coinbase :
573
        Address of account which receives block reward and transaction fees.
574
    ommers :
575
        List of ommers mentioned in the current block.
576
577
    """
578
    ommer_count = U256(len(ommers))
579
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
580
    create_ether(state, coinbase, miner_reward)
581
582
    for ommer in ommers:
583
        # Ommer age with respect to the current block.
584
        ommer_age = U256(block_number - ommer.number)
585
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
586
        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.spurious_dragon.vm.BlockEnvironment, ​​block_output: ethereum.forks.spurious_dragon.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
595
    """
596
    Execute a transaction against the provided environment.
597
598
    This function processes the actions needed to execute a transaction.
599
    It decrements the sender's account balance after calculating the gas fee
600
    and refunds them the proper amount after execution. Calling contracts,
601
    deploying code, and incrementing nonces are all examples of actions that
602
    happen within this function or from a call made within this function.
603
604
    Accounts that are marked for deletion are processed and destroyed after
605
    execution.
606
607
    Parameters
608
    ----------
609
    block_env :
610
        Environment for the Ethereum Virtual Machine.
611
    block_output :
612
        The block output for the current block.
613
    tx :
614
        Transaction to execute.
615
    index:
616
        Index of the transaction in the block.
617
618
    """
619
    trie_set(block_output.transactions_trie, rlp.encode(Uint(index)), tx)
620
    intrinsic_gas = validate_transaction(tx)
621
622
    sender = check_transaction(
623
        block_env=block_env,
624
        block_output=block_output,
625
        tx=tx,
626
    )
627
628
    sender_account = get_account(block_env.state, sender)
629
630
    gas = tx.gas - intrinsic_gas
631
    increment_nonce(block_env.state, sender)
632
633
    gas_fee = tx.gas * tx.gas_price
634
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
635
    set_account_balance(
636
        block_env.state, sender, U256(sender_balance_after_gas_fee)
637
    )
638
639
    tx_env = vm.TransactionEnvironment(
640
        origin=sender,
641
        gas_price=tx.gas_price,
642
        gas=gas,
643
        index_in_block=index,
644
        tx_hash=get_transaction_hash(tx),
645
    )
646
647
    message = prepare_message(block_env, tx_env, tx)
648
649
    tx_output = process_message_call(message)
650
651
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
652
    tx_gas_refund = min(
653
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
654
    )
655
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
656
    tx_gas_left = tx.gas - tx_gas_used_after_refund
657
    gas_refund_amount = tx_gas_left * tx.gas_price
658
659
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
660
661
    # refund gas
662
    sender_balance_after_refund = get_account(
663
        block_env.state, sender
664
    ).balance + U256(gas_refund_amount)
665
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
666
667
    # transfer miner fees
668
    coinbase_balance_after_mining_fee = get_account(
669
        block_env.state, block_env.coinbase
670
    ).balance + U256(transaction_fee)
671
    if coinbase_balance_after_mining_fee != 0:
672
        set_account_balance(
673
            block_env.state,
674
            block_env.coinbase,
675
            coinbase_balance_after_mining_fee,
676
        )
677
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
678
        destroy_account(block_env.state, block_env.coinbase)
679
680
    for address in tx_output.accounts_to_delete:
681
        destroy_account(block_env.state, address)
682
683
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
684
685
    block_output.block_gas_used += tx_gas_used_after_refund
686
687
    receipt = make_receipt(
688
        state_root(block_env.state),
689
        block_output.block_gas_used,
690
        tx_output.logs,
691
    )
692
693
    receipt_key = rlp.encode(Uint(index))
694
    block_output.receipt_keys += (receipt_key,)
695
696
    trie_set(
697
        block_output.receipts_trie,
698
        receipt_key,
699
        receipt,
700
    )
701
702
    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 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 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:
706
    """
707
    Validates the gas limit for a block.
708
709
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
710
    quotient of the parent block's gas limit and the
711
    ``LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
712
    passed through as a parameter is greater than or equal to the *sum* of
713
    the parent's gas and the adjustment delta then the limit for gas is too
714
    high and fails this function's check. Similarly, if the limit is less
715
    than or equal to the *difference* of the parent's gas and the adjustment
716
    delta *or* the predefined ``LIMIT_MINIMUM`` then this function's
717
    check fails because the gas limit doesn't allow for a sufficient or
718
    reasonable amount of gas to be used on a block.
719
720
    Parameters
721
    ----------
722
    gas_limit :
723
        Gas limit to validate.
724
725
    parent_gas_limit :
726
        Gas limit of the parent block.
727
728
    Returns
729
    -------
730
    check : `bool`
731
        True if gas limit constraints are satisfied, False otherwise.
732
733
    """
734
    max_adjustment_delta = parent_gas_limit // GasCosts.LIMIT_ADJUSTMENT_FACTOR
735
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
736
        return False
737
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
738
        return False
739
    if gas_limit < GasCosts.LIMIT_MINIMUM:
740
        return False
741
742
    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 MINIMUM_DIFFICULTY.

Parameters

block_number : Block number of the block. block_timestamp : Timestamp of the block. parent_timestamp : Timestamp of the parent block. parent_difficulty : difficulty of the parent block.

Returns

difficulty : ethereum.base_types.Uint Computed difficulty for a block.

def calculate_block_difficulty(block_number: Uint, ​​block_timestamp: U256, ​​parent_timestamp: U256, ​​parent_difficulty: Uint) -> Uint:
751
    """
752
    Computes difficulty of a block using its header and parent header.
753
754
    The difficulty is determined by the time the block was created after its
755
    parent. The ``offset`` is calculated using the parent block's difficulty,
756
    ``parent_difficulty``, and the timestamp between blocks. This offset is
757
    then added to the parent difficulty and is stored as the ``difficulty``
758
    variable. If the time between the block and its parent is too short, the
759
    offset will result in a positive number thus making the sum of
760
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
761
    avoid mass forking. But, if the time is long enough, then the offset
762
    results in a negative value making the block less difficult than
763
    its parent.
764
765
    The base standard for a block's difficulty is the predefined value
766
    set for the genesis block since it has no parent. So, a block
767
    can't be less difficult than the genesis block, therefore each block's
768
    difficulty is set to the maximum value between the calculated
769
    difficulty and the ``MINIMUM_DIFFICULTY``.
770
771
    Parameters
772
    ----------
773
    block_number :
774
        Block number of the block.
775
    block_timestamp :
776
        Timestamp of the block.
777
    parent_timestamp :
778
        Timestamp of the parent block.
779
    parent_difficulty :
780
        difficulty of the parent block.
781
782
    Returns
783
    -------
784
    difficulty : `ethereum.base_types.Uint`
785
        Computed difficulty for a block.
786
787
    """
788
    offset = (
789
        int(parent_difficulty)
790
        // 2048
791
        * max(1 - int(block_timestamp - parent_timestamp) // 10, -99)
792
    )
793
    difficulty = int(parent_difficulty) + offset
794
    # Historical Note: The difficulty bomb was not present in Ethereum at the
795
    # start of Frontier, but was added shortly after launch. However since the
796
    # bomb has no effect prior to block 200000 we pretend it existed from
797
    # genesis.
798
    # See https://github.com/ethereum/go-ethereum/pull/1588
799
    num_bomb_periods = (int(block_number) // 100000) - 2
800
    if num_bomb_periods >= 0:
801
        difficulty += 2**num_bomb_periods
802
803
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
804
    # the bomb. This bug does not matter because the difficulty is always much
805
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
806
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))