ethereum.tangerine_whistle.forkethereum.spurious_dragon.fork

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

51
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

52
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

53
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

54
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

57
@dataclass
class BlockChain:

blocks

63
    blocks: List[Block]

state

64
    state: State

chain_id

65
    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:
69
    """
70
    Transforms the state from the previous hard fork (`old`) into the block
71
    chain object for this hard fork and returns it.
72
73
    When forks need to implement an irregular state transition, this function
74
    is used to handle the irregularity. See the :ref:`DAO Fork <dao-fork>` for
75
    an example.
76
77
    Parameters
78
    ----------
79
    old :
80
        Previous block chain object.
81
82
    Returns
83
    -------
84
    new : `BlockChain`
85
        Upgraded block chain object for this hard fork.
86
    """
87
    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]:
91
    """
92
    Obtain the list of hashes of the previous 256 blocks in order of
93
    increasing block number.
94
95
    This function will return less hashes for the first 256 blocks.
96
97
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
98
    therefore this function retrieves them.
99
100
    Parameters
101
    ----------
102
    chain :
103
        History and current state.
104
105
    Returns
106
    -------
107
    recent_block_hashes : `List[Hash32]`
108
        Hashes of the recent 256 blocks in order of increasing block number.
109
    """
110
    recent_blocks = chain.blocks[-255:]
111
    # TODO: This function has not been tested rigorously
112
    if len(recent_blocks) == 0:
113
        return []
114
115
    recent_block_hashes = []
116
117
    for block in recent_blocks:
118
        prev_block_hash = block.header.parent_hash
119
        recent_block_hashes.append(prev_block_hash)
120
121
    # We are computing the hash only for the most recent block and not for
122
    # the rest of the blocks as they have successors which have the hash of
123
    # the current block as parent hash.
124
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
125
    recent_block_hashes.append(most_recent_block_hash)
126
127
    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:
131
    """
132
    Attempts to apply a block to an existing block chain.
133
134
    All parts of the block's contents need to be verified before being added
135
    to the chain. Blocks are verified by ensuring that the contents of the
136
    block make logical sense with the contents of the parent block. The
137
    information in the block's header must also match the corresponding
138
    information in the block.
139
140
    To implement Ethereum, in theory clients are only required to store the
141
    most recent 255 blocks of the chain since as far as execution is
142
    concerned, only those blocks are accessed. Practically, however, clients
143
    should store more blocks to handle reorgs.
144
145
    Parameters
146
    ----------
147
    chain :
148
        History and current state.
149
    block :
150
        Block to apply to `chain`.
151
    """
152
    validate_header(chain, block.header)
153
    validate_ommers(block.ommers, block.header, chain)
154
155
    block_env = vm.BlockEnvironment(
156
        chain_id=chain.chain_id,
157
        state=chain.state,
158
        block_gas_limit=block.header.gas_limit,
159
        block_hashes=get_last_256_block_hashes(chain),
160
        coinbase=block.header.coinbase,
161
        number=block.header.number,
162
        time=block.header.timestamp,
163
        difficulty=block.header.difficulty,
164
    )
165
166
    block_output = apply_body(
167
        block_env=block_env,
168
        transactions=block.transactions,
169
        ommers=block.ommers,
170
    )
171
    block_state_root = state_root(block_env.state)
172
    transactions_root = root(block_output.transactions_trie)
173
    receipt_root = root(block_output.receipts_trie)
174
    block_logs_bloom = logs_bloom(block_output.block_logs)
175
176
    if block_output.block_gas_used != block.header.gas_used:
177
        raise InvalidBlock(
178
            f"{block_output.block_gas_used} != {block.header.gas_used}"
179
        )
180
    if transactions_root != block.header.transactions_root:
181
        raise InvalidBlock
182
    if block_state_root != block.header.state_root:
183
        raise InvalidBlock
184
    if receipt_root != block.header.receipt_root:
185
        raise InvalidBlock
186
    if block_logs_bloom != block.header.bloom:
187
        raise InvalidBlock
188
189
    chain.blocks.append(block)
190
    if len(chain.blocks) > 255:
191
        # Real clients have to store more blocks to deal with reorgs, but the
192
        # protocol only requires the last 255
193
        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:
197
    """
198
    Verifies a block header.
199
200
    In order to consider a block's header valid, the logic for the
201
    quantities in the header should match the logic for the block itself.
202
    For example the header timestamp should be greater than the block's parent
203
    timestamp because the block was created *after* the parent block.
204
    Additionally, the block's number should be directly following the parent
205
    block's number since it is the next block in the sequence.
206
207
    Parameters
208
    ----------
209
    chain :
210
        History and current state.
211
    header :
212
        Header to check for correctness.
213
    """
214
    if header.number < Uint(1):
215
        raise InvalidBlock
216
    parent_header_number = header.number - Uint(1)
217
    first_block_number = chain.blocks[0].header.number
218
    last_block_number = chain.blocks[-1].header.number
219
220
    if (
221
        parent_header_number < first_block_number
222
        or parent_header_number > last_block_number
223
    ):
224
        raise InvalidBlock
225
226
    parent_header = chain.blocks[
227
        parent_header_number - first_block_number
228
    ].header
229
230
    if header.gas_used > header.gas_limit:
231
        raise InvalidBlock
232
233
    if header.timestamp <= parent_header.timestamp:
234
        raise InvalidBlock
235
    if header.number != parent_header.number + Uint(1):
236
        raise InvalidBlock
237
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
238
        raise InvalidBlock
239
    if len(header.extra_data) > 32:
240
        raise InvalidBlock
241
242
    block_difficulty = calculate_block_difficulty(
243
        header.number,
244
        header.timestamp,
245
        parent_header.timestamp,
246
        parent_header.difficulty,
247
    )
248
    if header.difficulty != block_difficulty:
249
        raise InvalidBlock
250
251
    block_parent_hash = keccak256(rlp.encode(parent_header))
252
    if header.parent_hash != block_parent_hash:
253
        raise InvalidBlock
254
255
    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:
259
    """
260
    Generate rlp hash of the header which is to be used for Proof-of-Work
261
    verification.
262
263
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
264
    while calculating this hash.
265
266
    A particular PoW is valid for a single hash, that hash is computed by
267
    this function. The `nonce` and `mix_digest` are omitted from this hash
268
    because they are being changed by miners in their search for a sufficient
269
    proof-of-work.
270
271
    Parameters
272
    ----------
273
    header :
274
        The header object for which the hash is to be generated.
275
276
    Returns
277
    -------
278
    hash : `Hash32`
279
        The PoW valid rlp hash of the passed in header.
280
    """
281
    header_data_without_pow_artefacts = (
282
        header.parent_hash,
283
        header.ommers_hash,
284
        header.coinbase,
285
        header.state_root,
286
        header.transactions_root,
287
        header.receipt_root,
288
        header.bloom,
289
        header.difficulty,
290
        header.number,
291
        header.gas_limit,
292
        header.gas_used,
293
        header.timestamp,
294
        header.extra_data,
295
    )
296
297
    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:
301
    """
302
    Validates the Proof of Work constraints.
303
304
    In order to verify that a miner's proof-of-work is valid for a block, a
305
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
306
    hash function. The mix digest is a hash of the header and the nonce that
307
    is passed through and it confirms whether or not proof-of-work was done
308
    on the correct block. The result is the actual hash value of the block.
309
310
    Parameters
311
    ----------
312
    header :
313
        Header of interest.
314
    """
315
    header_hash = generate_header_hash_for_pow(header)
316
    # TODO: Memoize this somewhere and read from that data instead of
317
    # calculating cache for every block validation.
318
    cache = generate_cache(header.number)
319
    mix_digest, result = hashimoto_light(
320
        header_hash, header.nonce, cache, dataset_size(header.number)
321
    )
322
    if mix_digest != header.mix_digest:
323
        raise InvalidBlock
324
325
    limit = Uint(U256.MAX_VALUE) + Uint(1)
326
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
327
        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.tangerine_whistle.vm.BlockEnvironmentethereum.spurious_dragon.vm.BlockEnvironment, ​​block_output: ethereum.tangerine_whistle.vm.BlockOutputethereum.spurious_dragon.vm.BlockOutput, ​​tx: Transaction) -> Address:
335
    """
336
    Check if the transaction is includable in the block.
337
338
    Parameters
339
    ----------
340
    block_env :
341
        The block scoped environment.
342
    block_output :
343
        The block output for the current block.
344
    tx :
345
        The transaction.
346
347
    Returns
348
    -------
349
    sender_address :
350
        The sender of the transaction.
351
352
    Raises
353
    ------
354
    InvalidBlock :
355
        If the transaction is not includable.
356
    """
357
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
358
    if tx.gas > gas_available:
359
        raise InvalidBlock
358
    sender_address = recover_sender(tx)
360
    sender_address = recover_sender(block_env.chain_id, tx)
361
    sender_account = get_account(block_env.state, sender_address)
362
363
    max_gas_fee = tx.gas * tx.gas_price
364
365
    if sender_account.nonce != tx.nonce:
366
        raise InvalidBlock
367
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
368
        raise InvalidBlock
369
    if sender_account.code:
370
        raise InvalidSenderError("not EOA")
371
372
    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:
380
    """
381
    Make the receipt for a transaction that was executed.
382
383
    Parameters
384
    ----------
385
    post_state :
386
        The state root immediately after this transaction.
387
    cumulative_gas_used :
388
        The total gas used so far in the block after the transaction was
389
        executed.
390
    logs :
391
        The logs produced by the transaction.
392
393
    Returns
394
    -------
395
    receipt :
396
        The receipt for the transaction.
397
    """
398
    receipt = Receipt(
399
        post_state=post_state,
400
        cumulative_gas_used=cumulative_gas_used,
401
        bloom=logs_bloom(logs),
402
        logs=logs,
403
    )
404
405
    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.tangerine_whistle.vm.BlockEnvironmentethereum.spurious_dragon.vm.BlockEnvironment, ​​transactions: Tuple[Transaction, ...], ​​ommers: Tuple[Header, ...]) -> ethereum.tangerine_whistle.vm.BlockOutputethereum.spurious_dragon.vm.BlockOutput:
413
    """
414
    Executes a block.
415
416
    Many of the contents of a block are stored in data structures called
417
    tries. There is a transactions trie which is similar to a ledger of the
418
    transactions stored in the current block. There is also a receipts trie
419
    which stores the results of executing a transaction, like the post state
420
    and gas used. This function creates and executes the block that is to be
421
    added to the chain.
422
423
    Parameters
424
    ----------
425
    block_env :
426
        The block scoped environment.
427
    transactions :
428
        Transactions included in the block.
429
    ommers :
430
        Headers of ancestor blocks which are not direct parents (formerly
431
        uncles.)
432
433
    Returns
434
    -------
435
    block_output :
436
        The block output for the current block.
437
    """
438
    block_output = vm.BlockOutput()
439
440
    for i, tx in enumerate(transactions):
441
        process_transaction(block_env, block_output, tx, Uint(i))
442
443
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
444
445
    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:
451
    """
452
    Validates the ommers mentioned in the block.
453
454
    An ommer block is a block that wasn't canonically added to the
455
    blockchain because it wasn't validated as fast as the canonical block
456
    but was mined at the same time.
457
458
    To be considered valid, the ommers must adhere to the rules defined in
459
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
460
    there cannot be duplicate ommers in a block. Many of the other ommer
461
    constraints are listed in the in-line comments of this function.
462
463
    Parameters
464
    ----------
465
    ommers :
466
        List of ommers mentioned in the current block.
467
    block_header:
468
        The header of current block.
469
    chain :
470
        History and current state.
471
    """
472
    block_hash = keccak256(rlp.encode(block_header))
473
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
474
        raise InvalidBlock
475
476
    if len(ommers) == 0:
477
        # Nothing to validate
478
        return
479
480
    # Check that each ommer satisfies the constraints of a header
481
    for ommer in ommers:
482
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
483
            raise InvalidBlock
484
        validate_header(chain, ommer)
485
    if len(ommers) > 2:
486
        raise InvalidBlock
487
488
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
489
    if len(ommers_hashes) != len(set(ommers_hashes)):
490
        raise InvalidBlock
491
492
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
493
    recent_canonical_block_hashes = {
494
        keccak256(rlp.encode(block.header))
495
        for block in recent_canonical_blocks
496
    }
497
    recent_ommers_hashes: Set[Hash32] = set()
498
    for block in recent_canonical_blocks:
499
        recent_ommers_hashes = recent_ommers_hashes.union(
500
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
501
        )
502
503
    for ommer_index, ommer in enumerate(ommers):
504
        ommer_hash = ommers_hashes[ommer_index]
505
        if ommer_hash == block_hash:
506
            raise InvalidBlock
507
        if ommer_hash in recent_canonical_block_hashes:
508
            raise InvalidBlock
509
        if ommer_hash in recent_ommers_hashes:
510
            raise InvalidBlock
511
512
        # Ommer age with respect to the current block. For example, an age of
513
        # 1 indicates that the ommer is a sibling of previous block.
514
        ommer_age = block_header.number - ommer.number
515
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
516
            raise InvalidBlock
517
        if ommer.parent_hash not in recent_canonical_block_hashes:
518
            raise InvalidBlock
519
        if ommer.parent_hash == block_header.parent_hash:
520
            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:
529
    """
530
    Pay rewards to the block miner as well as the ommers miners.
531
532
    The miner of the canonical block is rewarded with the predetermined
533
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
534
    number of ommer blocks that were mined around the same time, and included
535
    in the canonical block's header. An ommer block is a block that wasn't
536
    added to the canonical blockchain because it wasn't validated as fast as
537
    the accepted block but was mined at the same time. Although not all blocks
538
    that are mined are added to the canonical chain, miners are still paid a
539
    reward for their efforts. This reward is called an ommer reward and is
540
    calculated based on the number associated with the ommer block that they
541
    mined.
542
543
    Parameters
544
    ----------
545
    state :
546
        Current account state.
547
    block_number :
548
        Position of the block within the chain.
549
    coinbase :
550
        Address of account which receives block reward and transaction fees.
551
    ommers :
552
        List of ommers mentioned in the current block.
553
    """
554
    ommer_count = U256(len(ommers))
555
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
556
    create_ether(state, coinbase, miner_reward)
557
558
    for ommer in ommers:
559
        # Ommer age with respect to the current block.
560
        ommer_age = U256(block_number - ommer.number)
561
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
562
        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.tangerine_whistle.vm.BlockEnvironmentethereum.spurious_dragon.vm.BlockEnvironment, ​​block_output: ethereum.tangerine_whistle.vm.BlockOutputethereum.spurious_dragon.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
571
    """
572
    Execute a transaction against the provided environment.
573
574
    This function processes the actions needed to execute a transaction.
575
    It decrements the sender's account after calculating the gas fee and
576
    refunds them the proper amount after execution. Calling contracts,
577
    deploying code, and incrementing nonces are all examples of actions that
578
    happen within this function or from a call made within this function.
579
580
    Accounts that are marked for deletion are processed and destroyed after
581
    execution.
582
583
    Parameters
584
    ----------
585
    block_env :
586
        Environment for the Ethereum Virtual Machine.
587
    block_output :
588
        The block output for the current block.
589
    tx :
590
        Transaction to execute.
591
    index:
592
        Index of the transaction in the block.
593
    """
594
    trie_set(block_output.transactions_trie, rlp.encode(Uint(index)), tx)
595
    intrinsic_gas = validate_transaction(tx)
596
597
    sender = check_transaction(
598
        block_env=block_env,
599
        block_output=block_output,
600
        tx=tx,
601
    )
602
603
    sender_account = get_account(block_env.state, sender)
604
605
    gas = tx.gas - intrinsic_gas
606
    increment_nonce(block_env.state, sender)
607
608
    gas_fee = tx.gas * tx.gas_price
609
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
610
    set_account_balance(
611
        block_env.state, sender, U256(sender_balance_after_gas_fee)
612
    )
613
614
    tx_env = vm.TransactionEnvironment(
615
        origin=sender,
616
        gas_price=tx.gas_price,
617
        gas=gas,
618
        index_in_block=index,
619
        tx_hash=get_transaction_hash(tx),
620
        traces=[],
621
    )
622
623
    message = prepare_message(block_env, tx_env, tx)
624
625
    tx_output = process_message_call(message)
626
627
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
628
    tx_gas_refund = min(
629
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
630
    )
631
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
632
    tx_gas_left = tx.gas - tx_gas_used_after_refund
633
    gas_refund_amount = tx_gas_left * tx.gas_price
634
635
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
636
637
    # refund gas
638
    sender_balance_after_refund = get_account(
639
        block_env.state, sender
640
    ).balance + U256(gas_refund_amount)
641
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
642
643
    # transfer miner fees
644
    coinbase_balance_after_mining_fee = get_account(
645
        block_env.state, block_env.coinbase
646
    ).balance + U256(transaction_fee)
645
    set_account_balance(
646
        block_env.state, block_env.coinbase, coinbase_balance_after_mining_fee
647
    )
647
    if coinbase_balance_after_mining_fee != 0:
648
        set_account_balance(
649
            block_env.state,
650
            block_env.coinbase,
651
            coinbase_balance_after_mining_fee,
652
        )
653
    elif account_exists_and_is_empty(block_env.state, block_env.coinbase):
654
        destroy_account(block_env.state, block_env.coinbase)
655
656
    for address in tx_output.accounts_to_delete:
657
        destroy_account(block_env.state, address)
658
659
    destroy_touched_empty_accounts(block_env.state, tx_output.touched_accounts)
660
661
    block_output.block_gas_used += tx_gas_used_after_refund
662
663
    receipt = make_receipt(
664
        state_root(block_env.state),
665
        block_output.block_gas_used,
666
        tx_output.logs,
667
    )
668
669
    receipt_key = rlp.encode(Uint(index))
670
    block_output.receipt_keys += (receipt_key,)
671
672
    trie_set(
673
        block_output.receipts_trie,
674
        receipt_key,
675
        receipt,
676
    )
677
678
    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:
682
    """
683
    Validates the gas limit for a block.
684
685
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
686
    quotient of the parent block's gas limit and the
687
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
688
    passed through as a parameter is greater than or equal to the *sum* of
689
    the parent's gas and the adjustment delta then the limit for gas is too
690
    high and fails this function's check. Similarly, if the limit is less
691
    than or equal to the *difference* of the parent's gas and the adjustment
692
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
693
    check fails because the gas limit doesn't allow for a sufficient or
694
    reasonable amount of gas to be used on a block.
695
696
    Parameters
697
    ----------
698
    gas_limit :
699
        Gas limit to validate.
700
701
    parent_gas_limit :
702
        Gas limit of the parent block.
703
704
    Returns
705
    -------
706
    check : `bool`
707
        True if gas limit constraints are satisfied, False otherwise.
708
    """
709
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
710
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
711
        return False
712
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
713
        return False
714
    if gas_limit < GAS_LIMIT_MINIMUM:
715
        return False
716
717
    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.

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:
726
    """
727
    Computes difficulty of a block using its header and parent header.
728
729
    The difficulty is determined by the time the block was created after its
730
    parent. The ``offset`` is calculated using the parent block's difficulty,
731
    ``parent_difficulty``, and the timestamp between blocks. This offset is
732
    then added to the parent difficulty and is stored as the ``difficulty``
733
    variable. If the time between the block and its parent is too short, the
734
    offset will result in a positive number thus making the sum of
735
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
736
    avoid mass forking. But, if the time is long enough, then the offset
737
    results in a negative value making the block less difficult than
738
    its parent.
739
740
    The base standard for a block's difficulty is the predefined value
741
    set for the genesis block since it has no parent. So, a block
742
    can't be less difficult than the genesis block, therefore each block's
743
    difficulty is set to the maximum value between the calculated
744
    difficulty and the ``GENESIS_DIFFICULTY``.
745
746
    Parameters
747
    ----------
748
    block_number :
749
        Block number of the block.
750
    block_timestamp :
751
        Timestamp of the block.
752
    parent_timestamp :
753
        Timestamp of the parent block.
754
    parent_difficulty :
755
        difficulty of the parent block.
756
757
    Returns
758
    -------
759
    difficulty : `ethereum.base_types.Uint`
760
        Computed difficulty for a block.
761
    """
762
    offset = (
763
        int(parent_difficulty)
764
        // 2048
765
        * max(1 - int(block_timestamp - parent_timestamp) // 10, -99)
766
    )
767
    difficulty = int(parent_difficulty) + offset
768
    # Historical Note: The difficulty bomb was not present in Ethereum at the
769
    # start of Frontier, but was added shortly after launch. However since the
770
    # bomb has no effect prior to block 200000 we pretend it existed from
771
    # genesis.
772
    # See https://github.com/ethereum/go-ethereum/pull/1588
773
    num_bomb_periods = (int(block_number) // 100000) - 2
774
    if num_bomb_periods >= 0:
775
        difficulty += 2**num_bomb_periods
776
777
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
778
    # the bomb. This bug does not matter because the difficulty is always much
779
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
780
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))