ethereum.dao_fork.forkethereum.tangerine_whistle.fork

.. _dao-fork:

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

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

Introduction

Entry point for the Ethereum specification.

BLOCK_REWARD

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

GAS_LIMIT_ADJUSTMENT_FACTOR

55
GAS_LIMIT_ADJUSTMENT_FACTOR = Uint(1024)

GAS_LIMIT_MINIMUM

56
GAS_LIMIT_MINIMUM = Uint(5000)

MINIMUM_DIFFICULTY

57
MINIMUM_DIFFICULTY = Uint(131072)

MAX_OMMER_DEPTH

58
MAX_OMMER_DEPTH = Uint(6)

BlockChain

History and current state of the block chain.

61
@dataclass
class BlockChain:

blocks

67
    blocks: List[Block]

state

68
    state: State

chain_id

69
    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.is used to handle the irregularity. See the :ref:DAO Fork <dao-fork> for an example.

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