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

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

GAS_LIMIT_ADJUSTMENT_FACTOR

57
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

58
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

59
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

60
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

63
@dataclass
class BlockChain:

blocks

69
    blocks: List[Block]

state

70
    state: State

chain_id

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