ethereum.dao_fork.fork

.. _dao-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)

GAS_LIMIT_ADJUSTMENT_FACTOR

58
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

59
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

60
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

61
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

64
@dataclass
class BlockChain:

blocks

70
    blocks: List[Block]

state

71
    state: State

chain_id

72
    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.

The DAO-Fork occurred as a result of the 2016 DAO Hacks <https://www.gemini.com/cryptopedia/the-dao-hack-makerdao>_ in which an unknown entity managed to drain more than 3.6 million ether causing the price of ether to drop by nearly 35%. This fork was the solution to the hacks and manually reset the affected parties' accounts to their state prior to the attack. This fork essentially rewrote the history of the Ethereum network.

Parameters

old : Previous block chain object.

Returns

new : BlockChain Upgraded block chain object for this hard fork.

def apply_fork(old: BlockChain) -> BlockChain:
76
    """
77
    Transforms the state from the previous hard fork (`old`) into the block
78
    chain object for this hard fork and returns it.
79
80
    When forks need to implement an irregular state transition, this function
81
    is used to handle the irregularity.
82
83
    The DAO-Fork occurred as a result of the `2016 DAO Hacks
84
    <https://www.gemini.com/cryptopedia/the-dao-hack-makerdao>`_ in which an
85
    unknown entity managed to drain more than 3.6 million ether causing the
86
    price of ether to drop by nearly 35%. This fork was the solution to the
87
    hacks and manually reset the affected parties' accounts to their state
88
    prior to the attack. This fork essentially rewrote the history of the
89
    Ethereum network.
90
91
    Parameters
92
    ----------
93
    old :
94
        Previous block chain object.
95
96
    Returns
97
    -------
98
    new : `BlockChain`
99
        Upgraded block chain object for this hard fork.
100
    """
101
    apply_dao(old.state)
102
    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]:
106
    """
107
    Obtain the list of hashes of the previous 256 blocks in order of
108
    increasing block number.
109
110
    This function will return less hashes for the first 256 blocks.
111
112
    The ``BLOCKHASH`` opcode needs to access the latest hashes on the chain,
113
    therefore this function retrieves them.
114
115
    Parameters
116
    ----------
117
    chain :
118
        History and current state.
119
120
    Returns
121
    -------
122
    recent_block_hashes : `List[Hash32]`
123
        Hashes of the recent 256 blocks in order of increasing block number.
124
    """
125
    recent_blocks = chain.blocks[-255:]
126
    # TODO: This function has not been tested rigorously
127
    if len(recent_blocks) == 0:
128
        return []
129
130
    recent_block_hashes = []
131
132
    for block in recent_blocks:
133
        prev_block_hash = block.header.parent_hash
134
        recent_block_hashes.append(prev_block_hash)
135
136
    # We are computing the hash only for the most recent block and not for
137
    # the rest of the blocks as they have successors which have the hash of
138
    # the current block as parent hash.
139
    most_recent_block_hash = keccak256(rlp.encode(recent_blocks[-1].header))
140
    recent_block_hashes.append(most_recent_block_hash)
141
142
    return recent_block_hashes

state_transition

Attempts to apply a block to an existing block chain.

All parts of the block's contents need to be verified before being added to the chain. Blocks are verified by ensuring that the contents of the block make logical sense with the contents of the parent block. The information in the block's header must also match the corresponding information in the block.

To implement Ethereum, in theory clients are only required to store the most recent 255 blocks of the chain since as far as execution is concerned, only those blocks are accessed. Practically, however, clients should store more blocks to handle reorgs.

Parameters

chain : History and current state. block : Block to apply to chain.

def state_transition(chain: BlockChain, ​​block: Block) -> None:
146
    """
147
    Attempts to apply a block to an existing block chain.
148
149
    All parts of the block's contents need to be verified before being added
150
    to the chain. Blocks are verified by ensuring that the contents of the
151
    block make logical sense with the contents of the parent block. The
152
    information in the block's header must also match the corresponding
153
    information in the block.
154
155
    To implement Ethereum, in theory clients are only required to store the
156
    most recent 255 blocks of the chain since as far as execution is
157
    concerned, only those blocks are accessed. Practically, however, clients
158
    should store more blocks to handle reorgs.
159
160
    Parameters
161
    ----------
162
    chain :
163
        History and current state.
164
    block :
165
        Block to apply to `chain`.
166
    """
167
    validate_header(chain, block.header)
168
    validate_ommers(block.ommers, block.header, chain)
169
170
    block_env = vm.BlockEnvironment(
171
        chain_id=chain.chain_id,
172
        state=chain.state,
173
        block_gas_limit=block.header.gas_limit,
174
        block_hashes=get_last_256_block_hashes(chain),
175
        coinbase=block.header.coinbase,
176
        number=block.header.number,
177
        time=block.header.timestamp,
178
        difficulty=block.header.difficulty,
179
    )
180
181
    block_output = apply_body(
182
        block_env=block_env,
183
        transactions=block.transactions,
184
        ommers=block.ommers,
185
    )
186
    block_state_root = state_root(block_env.state)
187
    transactions_root = root(block_output.transactions_trie)
188
    receipt_root = root(block_output.receipts_trie)
189
    block_logs_bloom = logs_bloom(block_output.block_logs)
190
191
    if block_output.block_gas_used != block.header.gas_used:
192
        raise InvalidBlock(
193
            f"{block_output.block_gas_used} != {block.header.gas_used}"
194
        )
195
    if transactions_root != block.header.transactions_root:
196
        raise InvalidBlock
197
    if block_state_root != block.header.state_root:
198
        raise InvalidBlock
199
    if receipt_root != block.header.receipt_root:
200
        raise InvalidBlock
201
    if block_logs_bloom != block.header.bloom:
202
        raise InvalidBlock
203
204
    chain.blocks.append(block)
205
    if len(chain.blocks) > 255:
206
        # Real clients have to store more blocks to deal with reorgs, but the
207
        # protocol only requires the last 255
208
        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:
212
    """
213
    Verifies a block header.
214
215
    In order to consider a block's header valid, the logic for the
216
    quantities in the header should match the logic for the block itself.
217
    For example the header timestamp should be greater than the block's parent
218
    timestamp because the block was created *after* the parent block.
219
    Additionally, the block's number should be directly following the parent
220
    block's number since it is the next block in the sequence.
221
222
    Parameters
223
    ----------
224
    chain :
225
        History and current state.
226
    header :
227
        Header to check for correctness.
228
    """
229
    if header.number < Uint(1):
230
        raise InvalidBlock
231
    parent_header_number = header.number - Uint(1)
232
    first_block_number = chain.blocks[0].header.number
233
    last_block_number = chain.blocks[-1].header.number
234
235
    if (
236
        parent_header_number < first_block_number
237
        or parent_header_number > last_block_number
238
    ):
239
        raise InvalidBlock
240
241
    parent_header = chain.blocks[
242
        parent_header_number - first_block_number
243
    ].header
244
245
    if header.gas_used > header.gas_limit:
246
        raise InvalidBlock
247
248
    if header.timestamp <= parent_header.timestamp:
249
        raise InvalidBlock
250
    if header.number != parent_header.number + Uint(1):
251
        raise InvalidBlock
252
    if not check_gas_limit(header.gas_limit, parent_header.gas_limit):
253
        raise InvalidBlock
254
    if len(header.extra_data) > 32:
255
        raise InvalidBlock
256
257
    block_difficulty = calculate_block_difficulty(
258
        header.number,
259
        header.timestamp,
260
        parent_header.timestamp,
261
        parent_header.difficulty,
262
    )
263
    if header.difficulty != block_difficulty:
264
        raise InvalidBlock
265
266
    block_parent_hash = keccak256(rlp.encode(parent_header))
267
    if header.parent_hash != block_parent_hash:
268
        raise InvalidBlock
269
270
    if (
271
        header.number >= FORK_CRITERIA.block_number
272
        and header.number < FORK_CRITERIA.block_number + Uint(10)
273
    ):
274
        if header.extra_data != b"dao-hard-fork":
275
            raise InvalidBlock
276
277
    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:
281
    """
282
    Generate rlp hash of the header which is to be used for Proof-of-Work
283
    verification.
284
285
    In other words, the PoW artefacts `mix_digest` and `nonce` are ignored
286
    while calculating this hash.
287
288
    A particular PoW is valid for a single hash, that hash is computed by
289
    this function. The `nonce` and `mix_digest` are omitted from this hash
290
    because they are being changed by miners in their search for a sufficient
291
    proof-of-work.
292
293
    Parameters
294
    ----------
295
    header :
296
        The header object for which the hash is to be generated.
297
298
    Returns
299
    -------
300
    hash : `Hash32`
301
        The PoW valid rlp hash of the passed in header.
302
    """
303
    header_data_without_pow_artefacts = (
304
        header.parent_hash,
305
        header.ommers_hash,
306
        header.coinbase,
307
        header.state_root,
308
        header.transactions_root,
309
        header.receipt_root,
310
        header.bloom,
311
        header.difficulty,
312
        header.number,
313
        header.gas_limit,
314
        header.gas_used,
315
        header.timestamp,
316
        header.extra_data,
317
    )
318
319
    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:
323
    """
324
    Validates the Proof of Work constraints.
325
326
    In order to verify that a miner's proof-of-work is valid for a block, a
327
    ``mix-digest`` and ``result`` are calculated using the ``hashimoto_light``
328
    hash function. The mix digest is a hash of the header and the nonce that
329
    is passed through and it confirms whether or not proof-of-work was done
330
    on the correct block. The result is the actual hash value of the block.
331
332
    Parameters
333
    ----------
334
    header :
335
        Header of interest.
336
    """
337
    header_hash = generate_header_hash_for_pow(header)
338
    # TODO: Memoize this somewhere and read from that data instead of
339
    # calculating cache for every block validation.
340
    cache = generate_cache(header.number)
341
    mix_digest, result = hashimoto_light(
342
        header_hash, header.nonce, cache, dataset_size(header.number)
343
    )
344
    if mix_digest != header.mix_digest:
345
        raise InvalidBlock
346
347
    limit = Uint(U256.MAX_VALUE) + Uint(1)
348
    if Uint.from_be_bytes(result) > (limit // header.difficulty):
349
        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.dao_fork.vm.BlockEnvironment, ​​block_output: ethereum.dao_fork.vm.BlockOutput, ​​tx: Transaction) -> Address:
357
    """
358
    Check if the transaction is includable in the block.
359
360
    Parameters
361
    ----------
362
    block_env :
363
        The block scoped environment.
364
    block_output :
365
        The block output for the current block.
366
    tx :
367
        The transaction.
368
369
    Returns
370
    -------
371
    sender_address :
372
        The sender of the transaction.
373
374
    Raises
375
    ------
376
    GasUsedExceedsLimitError :
377
        If the gas used by the transaction exceeds the block's gas limit.
378
    NonceMismatchError :
379
        If the nonce of the transaction is not equal to the sender's nonce.
380
    InsufficientBalanceError :
381
        If the sender's balance is not enough to pay for the transaction.
382
    InvalidSenderError :
383
        If the transaction is from an address that does not exist anymore.
384
    """
385
    gas_available = block_env.block_gas_limit - block_output.block_gas_used
386
    if tx.gas > gas_available:
387
        raise GasUsedExceedsLimitError("gas used exceeds limit")
388
    sender_address = recover_sender(tx)
389
    sender_account = get_account(block_env.state, sender_address)
390
391
    max_gas_fee = tx.gas * tx.gas_price
392
393
    if sender_account.nonce > Uint(tx.nonce):
394
        raise NonceMismatchError("nonce too low")
395
    elif sender_account.nonce < Uint(tx.nonce):
396
        raise NonceMismatchError("nonce too high")
397
    if Uint(sender_account.balance) < max_gas_fee + Uint(tx.value):
398
        raise InsufficientBalanceError("insufficient sender balance")
399
    if sender_account.code:
400
        raise InvalidSenderError("not EOA")
401
402
    return sender_address

make_receipt

Make the receipt for a transaction that was executed.

Parameters

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:
410
    """
411
    Make the receipt for a transaction that was executed.
412
413
    Parameters
414
    ----------
415
    post_state :
416
        The state root immediately after this transaction.
417
    cumulative_gas_used :
418
        The total gas used so far in the block after the transaction was
419
        executed.
420
    logs :
421
        The logs produced by the transaction.
422
423
    Returns
424
    -------
425
    receipt :
426
        The receipt for the transaction.
427
    """
428
    receipt = Receipt(
429
        post_state=post_state,
430
        cumulative_gas_used=cumulative_gas_used,
431
        bloom=logs_bloom(logs),
432
        logs=logs,
433
    )
434
435
    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.dao_fork.vm.BlockEnvironment, ​​transactions: Tuple[Transaction, ...], ​​ommers: Tuple[Header, ...]) -> ethereum.dao_fork.vm.BlockOutput:
443
    """
444
    Executes a block.
445
446
    Many of the contents of a block are stored in data structures called
447
    tries. There is a transactions trie which is similar to a ledger of the
448
    transactions stored in the current block. There is also a receipts trie
449
    which stores the results of executing a transaction, like the post state
450
    and gas used. This function creates and executes the block that is to be
451
    added to the chain.
452
453
    Parameters
454
    ----------
455
    block_env :
456
        The block scoped environment.
457
    transactions :
458
        Transactions included in the block.
459
    ommers :
460
        Headers of ancestor blocks which are not direct parents (formerly
461
        uncles.)
462
463
    Returns
464
    -------
465
    block_output :
466
        The block output for the current block.
467
    """
468
    block_output = vm.BlockOutput()
469
470
    for i, tx in enumerate(transactions):
471
        process_transaction(block_env, block_output, tx, Uint(i))
472
473
    pay_rewards(block_env.state, block_env.number, block_env.coinbase, ommers)
474
475
    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:
481
    """
482
    Validates the ommers mentioned in the block.
483
484
    An ommer block is a block that wasn't canonically added to the
485
    blockchain because it wasn't validated as fast as the canonical block
486
    but was mined at the same time.
487
488
    To be considered valid, the ommers must adhere to the rules defined in
489
    the Ethereum protocol. The maximum amount of ommers is 2 per block and
490
    there cannot be duplicate ommers in a block. Many of the other ommer
491
    constraints are listed in the in-line comments of this function.
492
493
    Parameters
494
    ----------
495
    ommers :
496
        List of ommers mentioned in the current block.
497
    block_header:
498
        The header of current block.
499
    chain :
500
        History and current state.
501
    """
502
    block_hash = keccak256(rlp.encode(block_header))
503
    if keccak256(rlp.encode(ommers)) != block_header.ommers_hash:
504
        raise InvalidBlock
505
506
    if len(ommers) == 0:
507
        # Nothing to validate
508
        return
509
510
    # Check that each ommer satisfies the constraints of a header
511
    for ommer in ommers:
512
        if Uint(1) > ommer.number or ommer.number >= block_header.number:
513
            raise InvalidBlock
514
        validate_header(chain, ommer)
515
    if len(ommers) > 2:
516
        raise InvalidBlock
517
518
    ommers_hashes = [keccak256(rlp.encode(ommer)) for ommer in ommers]
519
    if len(ommers_hashes) != len(set(ommers_hashes)):
520
        raise InvalidBlock
521
522
    recent_canonical_blocks = chain.blocks[-(MAX_OMMER_DEPTH + Uint(1)) :]
523
    recent_canonical_block_hashes = {
524
        keccak256(rlp.encode(block.header))
525
        for block in recent_canonical_blocks
526
    }
527
    recent_ommers_hashes: Set[Hash32] = set()
528
    for block in recent_canonical_blocks:
529
        recent_ommers_hashes = recent_ommers_hashes.union(
530
            {keccak256(rlp.encode(ommer)) for ommer in block.ommers}
531
        )
532
533
    for ommer_index, ommer in enumerate(ommers):
534
        ommer_hash = ommers_hashes[ommer_index]
535
        if ommer_hash == block_hash:
536
            raise InvalidBlock
537
        if ommer_hash in recent_canonical_block_hashes:
538
            raise InvalidBlock
539
        if ommer_hash in recent_ommers_hashes:
540
            raise InvalidBlock
541
542
        # Ommer age with respect to the current block. For example, an age of
543
        # 1 indicates that the ommer is a sibling of previous block.
544
        ommer_age = block_header.number - ommer.number
545
        if Uint(1) > ommer_age or ommer_age > MAX_OMMER_DEPTH:
546
            raise InvalidBlock
547
        if ommer.parent_hash not in recent_canonical_block_hashes:
548
            raise InvalidBlock
549
        if ommer.parent_hash == block_header.parent_hash:
550
            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:
559
    """
560
    Pay rewards to the block miner as well as the ommers miners.
561
562
    The miner of the canonical block is rewarded with the predetermined
563
    block reward, ``BLOCK_REWARD``, plus a variable award based off of the
564
    number of ommer blocks that were mined around the same time, and included
565
    in the canonical block's header. An ommer block is a block that wasn't
566
    added to the canonical blockchain because it wasn't validated as fast as
567
    the accepted block but was mined at the same time. Although not all blocks
568
    that are mined are added to the canonical chain, miners are still paid a
569
    reward for their efforts. This reward is called an ommer reward and is
570
    calculated based on the number associated with the ommer block that they
571
    mined.
572
573
    Parameters
574
    ----------
575
    state :
576
        Current account state.
577
    block_number :
578
        Position of the block within the chain.
579
    coinbase :
580
        Address of account which receives block reward and transaction fees.
581
    ommers :
582
        List of ommers mentioned in the current block.
583
    """
584
    ommer_count = U256(len(ommers))
585
    miner_reward = BLOCK_REWARD + (ommer_count * (BLOCK_REWARD // U256(32)))
586
    create_ether(state, coinbase, miner_reward)
587
588
    for ommer in ommers:
589
        # Ommer age with respect to the current block.
590
        ommer_age = U256(block_number - ommer.number)
591
        ommer_miner_reward = ((U256(8) - ommer_age) * BLOCK_REWARD) // U256(8)
592
        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.dao_fork.vm.BlockEnvironment, ​​block_output: ethereum.dao_fork.vm.BlockOutput, ​​tx: Transaction, ​​index: Uint) -> None:
601
    """
602
    Execute a transaction against the provided environment.
603
604
    This function processes the actions needed to execute a transaction.
605
    It decrements the sender's account after calculating the gas fee and
606
    refunds them the proper amount after execution. Calling contracts,
607
    deploying code, and incrementing nonces are all examples of actions that
608
    happen within this function or from a call made within this function.
609
610
    Accounts that are marked for deletion are processed and destroyed after
611
    execution.
612
613
    Parameters
614
    ----------
615
    block_env :
616
        Environment for the Ethereum Virtual Machine.
617
    block_output :
618
        The block output for the current block.
619
    tx :
620
        Transaction to execute.
621
    index:
622
        Index of the transaction in the block.
623
    """
624
    trie_set(block_output.transactions_trie, rlp.encode(Uint(index)), tx)
625
    intrinsic_gas = validate_transaction(tx)
626
627
    sender = check_transaction(
628
        block_env=block_env,
629
        block_output=block_output,
630
        tx=tx,
631
    )
632
633
    sender_account = get_account(block_env.state, sender)
634
635
    gas = tx.gas - intrinsic_gas
636
    increment_nonce(block_env.state, sender)
637
638
    gas_fee = tx.gas * tx.gas_price
639
    sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee
640
    set_account_balance(
641
        block_env.state, sender, U256(sender_balance_after_gas_fee)
642
    )
643
644
    tx_env = vm.TransactionEnvironment(
645
        origin=sender,
646
        gas_price=tx.gas_price,
647
        gas=gas,
648
        index_in_block=index,
649
        tx_hash=get_transaction_hash(tx),
650
        traces=[],
651
    )
652
653
    message = prepare_message(block_env, tx_env, tx)
654
655
    tx_output = process_message_call(message)
656
657
    tx_gas_used_before_refund = tx.gas - tx_output.gas_left
658
    tx_gas_refund = min(
659
        tx_gas_used_before_refund // Uint(2), Uint(tx_output.refund_counter)
660
    )
661
    tx_gas_used_after_refund = tx_gas_used_before_refund - tx_gas_refund
662
    tx_gas_left = tx.gas - tx_gas_used_after_refund
663
    gas_refund_amount = tx_gas_left * tx.gas_price
664
665
    transaction_fee = tx_gas_used_after_refund * tx.gas_price
666
667
    # refund gas
668
    sender_balance_after_refund = get_account(
669
        block_env.state, sender
670
    ).balance + U256(gas_refund_amount)
671
    set_account_balance(block_env.state, sender, sender_balance_after_refund)
672
673
    # transfer miner fees
674
    coinbase_balance_after_mining_fee = get_account(
675
        block_env.state, block_env.coinbase
676
    ).balance + U256(transaction_fee)
677
    set_account_balance(
678
        block_env.state, block_env.coinbase, coinbase_balance_after_mining_fee
679
    )
680
681
    for address in tx_output.accounts_to_delete:
682
        destroy_account(block_env.state, address)
683
684
    block_output.block_gas_used += tx_gas_used_after_refund
685
686
    receipt = make_receipt(
687
        state_root(block_env.state),
688
        block_output.block_gas_used,
689
        tx_output.logs,
690
    )
691
692
    receipt_key = rlp.encode(Uint(index))
693
    block_output.receipt_keys += (receipt_key,)
694
695
    trie_set(
696
        block_output.receipts_trie,
697
        receipt_key,
698
        receipt,
699
    )
700
701
    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:
705
    """
706
    Validates the gas limit for a block.
707
708
    The bounds of the gas limit, ``max_adjustment_delta``, is set as the
709
    quotient of the parent block's gas limit and the
710
    ``GAS_LIMIT_ADJUSTMENT_FACTOR``. Therefore, if the gas limit that is
711
    passed through as a parameter is greater than or equal to the *sum* of
712
    the parent's gas and the adjustment delta then the limit for gas is too
713
    high and fails this function's check. Similarly, if the limit is less
714
    than or equal to the *difference* of the parent's gas and the adjustment
715
    delta *or* the predefined ``GAS_LIMIT_MINIMUM`` then this function's
716
    check fails because the gas limit doesn't allow for a sufficient or
717
    reasonable amount of gas to be used on a block.
718
719
    Parameters
720
    ----------
721
    gas_limit :
722
        Gas limit to validate.
723
724
    parent_gas_limit :
725
        Gas limit of the parent block.
726
727
    Returns
728
    -------
729
    check : `bool`
730
        True if gas limit constraints are satisfied, False otherwise.
731
    """
732
    max_adjustment_delta = parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
733
    if gas_limit >= parent_gas_limit + max_adjustment_delta:
734
        return False
735
    if gas_limit <= parent_gas_limit - max_adjustment_delta:
736
        return False
737
    if gas_limit < GAS_LIMIT_MINIMUM:
738
        return False
739
740
    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:
749
    """
750
    Computes difficulty of a block using its header and parent header.
751
752
    The difficulty is determined by the time the block was created after its
753
    parent. The ``offset`` is calculated using the parent block's difficulty,
754
    ``parent_difficulty``, and the timestamp between blocks. This offset is
755
    then added to the parent difficulty and is stored as the ``difficulty``
756
    variable. If the time between the block and its parent is too short, the
757
    offset will result in a positive number thus making the sum of
758
    ``parent_difficulty`` and ``offset`` to be a greater value in order to
759
    avoid mass forking. But, if the time is long enough, then the offset
760
    results in a negative value making the block less difficult than
761
    its parent.
762
763
    The base standard for a block's difficulty is the predefined value
764
    set for the genesis block since it has no parent. So, a block
765
    can't be less difficult than the genesis block, therefore each block's
766
    difficulty is set to the maximum value between the calculated
767
    difficulty and the ``GENESIS_DIFFICULTY``.
768
769
    Parameters
770
    ----------
771
    block_number :
772
        Block number of the block.
773
    block_timestamp :
774
        Timestamp of the block.
775
    parent_timestamp :
776
        Timestamp of the parent block.
777
    parent_difficulty :
778
        difficulty of the parent block.
779
780
    Returns
781
    -------
782
    difficulty : `ethereum.base_types.Uint`
783
        Computed difficulty for a block.
784
    """
785
    offset = (
786
        int(parent_difficulty)
787
        // 2048
788
        * max(1 - int(block_timestamp - parent_timestamp) // 10, -99)
789
    )
790
    difficulty = int(parent_difficulty) + offset
791
    # Historical Note: The difficulty bomb was not present in Ethereum at the
792
    # start of Frontier, but was added shortly after launch. However since the
793
    # bomb has no effect prior to block 200000 we pretend it existed from
794
    # genesis.
795
    # See https://github.com/ethereum/go-ethereum/pull/1588
796
    num_bomb_periods = (int(block_number) // 100000) - 2
797
    if num_bomb_periods >= 0:
798
        difficulty += 2**num_bomb_periods
799
800
    # Some clients raise the difficulty to `MINIMUM_DIFFICULTY` prior to adding
801
    # the bomb. This bug does not matter because the difficulty is always much
802
    # greater than `MINIMUM_DIFFICULTY` on Mainnet.
803
    return Uint(max(difficulty, int(MINIMUM_DIFFICULTY)))