ethereum.shanghai.transactions

Transactions are atomic units of work created externally to Ethereum and submitted to be executed. If Ethereum is viewed as a state machine, transactions are the events that move between states.

TX_BASE_COST

Base cost of a transaction in gas units. This is the minimum amount of gas required to execute a transaction.

25
TX_BASE_COST = Uint(21000)

TX_DATA_COST_PER_NON_ZERO

Gas cost per non-zero byte in the transaction data.

31
TX_DATA_COST_PER_NON_ZERO = Uint(16)

TX_DATA_COST_PER_ZERO

Gas cost per zero byte in the transaction data.

36
TX_DATA_COST_PER_ZERO = Uint(4)

TX_CREATE_COST

Additional gas cost for creating a new contract.

41
TX_CREATE_COST = Uint(32000)

TX_ACCESS_LIST_ADDRESS_COST

Gas cost for including an address in the access list of a transaction.

46
TX_ACCESS_LIST_ADDRESS_COST = Uint(2400)

TX_ACCESS_LIST_STORAGE_KEY_COST

Gas cost for including a storage key in the access list of a transaction.

51
TX_ACCESS_LIST_STORAGE_KEY_COST = Uint(1900)

LegacyTransaction

Atomic operation performed on the block chain. This represents the original transaction format used before EIP-1559, and EIP-2930.

57
@slotted_freezable
58
@dataclass
class LegacyTransaction:

nonce

A scalar value equal to the number of transactions sent by the sender.

68
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

73
    gas_price: Uint

gas

The maximum amount of gas that can be used by this transaction.

78
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

83
    to: Bytes0 | Address

value

The amount of ether (in wei) to send with this transaction.

89
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

94
    data: Bytes

v

The recovery id of the signature.

100
    v: U256

r

The first part of the signature.

105
    r: U256

s

The second part of the signature.

110
    s: U256

Access

A mapping from account address to storage slots that are pre-warmed as part of a transaction.

116
@slotted_freezable
117
@dataclass
class Access:

account

The address of the account that is accessed.

124
    account: Address

slots

A tuple of storage slots that are accessed in the account.

129
    slots: Tuple[Bytes32, ...]

AccessListTransaction

The transaction type added in EIP-2930 to support access lists.

This transaction type extends the legacy transaction with an access list and chain ID. The access list specifies which addresses and storage slots the transaction will access.

135
@slotted_freezable
136
@dataclass
class AccessListTransaction:

chain_id

The ID of the chain on which this transaction is executed.

148
    chain_id: U64

nonce

A scalar value equal to the number of transactions sent by the sender.

153
    nonce: U256

gas_price

The price of gas for this transaction.

158
    gas_price: Uint

gas

The maximum amount of gas that can be used by this transaction.

163
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

168
    to: Bytes0 | Address

value

The amount of ether (in wei) to send with this transaction.

174
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

179
    data: Bytes

access_list

A tuple of Access objects that specify which addresses and storage slots are accessed in the transaction.

185
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

191
    y_parity: U256

r

The first part of the signature.

196
    r: U256

s

The second part of the signature.

201
    s: U256

FeeMarketTransaction

The transaction type added in EIP-1559.

This transaction type introduces a new fee market mechanism with two gas price parameters: max_priority_fee_per_gas and max_fee_per_gas.

207
@slotted_freezable
208
@dataclass
class FeeMarketTransaction:

chain_id

The ID of the chain on which this transaction is executed.

219
    chain_id: U64

nonce

A scalar value equal to the number of transactions sent by the sender.

224
    nonce: U256

max_priority_fee_per_gas

The maximum priority fee per gas that the sender is willing to pay.

229
    max_priority_fee_per_gas: Uint

max_fee_per_gas

The maximum fee per gas that the sender is willing to pay, including the base fee and priority fee.

234
    max_fee_per_gas: Uint

gas

The maximum amount of gas that can be used by this transaction.

240
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

245
    to: Bytes0 | Address

value

The amount of ether (in wei) to send with this transaction.

251
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

256
    data: Bytes

access_list

A tuple of Access objects that specify which addresses and storage slots are accessed in the transaction.

262
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

268
    y_parity: U256

r

The first part of the signature.

273
    r: U256

s

The second part of the signature.

278
    s: U256

Transaction

Union type representing any valid transaction type.

284
Transaction = LegacyTransaction | AccessListTransaction | FeeMarketTransaction

encode_transaction

Encode a transaction into its RLP or typed transaction format. Needed because non-legacy transactions aren't RLP.

Legacy transactions are returned as-is, while other transaction types are prefixed with their type identifier and RLP encoded.

def encode_transaction(tx: Transaction) -> LegacyTransaction | Bytes:
291
    """
292
    Encode a transaction into its RLP or typed transaction format.
293
    Needed because non-legacy transactions aren't RLP.
294
295
    Legacy transactions are returned as-is, while other transaction types
296
    are prefixed with their type identifier and RLP encoded.
297
    """
298
    if isinstance(tx, LegacyTransaction):
299
        return tx
300
    elif isinstance(tx, AccessListTransaction):
301
        return b"\x01" + rlp.encode(tx)
302
    elif isinstance(tx, FeeMarketTransaction):
303
        return b"\x02" + rlp.encode(tx)
304
    else:
305
        raise Exception(f"Unable to encode transaction of type {type(tx)}")

decode_transaction

Decode a transaction from its RLP or typed transaction format. Needed because non-legacy transactions aren't RLP.

Legacy transactions are returned as-is, while other transaction types are decoded based on their type identifier prefix.

def decode_transaction(tx: LegacyTransaction | Bytes) -> Transaction:
309
    """
310
    Decode a transaction from its RLP or typed transaction format.
311
    Needed because non-legacy transactions aren't RLP.
312
313
    Legacy transactions are returned as-is, while other transaction types
314
    are decoded based on their type identifier prefix.
315
    """
316
    if isinstance(tx, Bytes):
317
        if tx[0] == 1:
318
            return rlp.decode_to(AccessListTransaction, tx[1:])
319
        elif tx[0] == 2:
320
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
321
        else:
322
            raise TransactionTypeError(tx[0])
323
    else:
324
        return tx

validate_transaction

Verifies a transaction.

The gas in a transaction gets used to pay for the intrinsic cost of operations, therefore if there is insufficient gas then it would not be possible to execute a transaction and it will be declared invalid.

Additionally, the nonce of a transaction must not equal or exceed the limit defined in EIP-2681. In practice, defining the limit as 2**64-1 has no impact because sending 2**64-1 transactions is improbable. It's not strictly impossible though, 2**64-1 transactions is the entire capacity of the Ethereum blockchain at 2022 gas limits for a little over 22 years.

Also, the code size of a contract creation transaction must be within limits of the protocol.

This function takes a transaction as a parameter and returns the intrinsic gas cost of the transaction after validation. It throws an InsufficientTransactionGasError exception if the transaction does not provide enough gas to cover the intrinsic cost, and a NonceOverflowError exception if the nonce is greater than 2**64 - 2. It also raises an InitCodeTooLargeError if the code size of a contract creation transaction exceeds the maximum allowed size.

def validate_transaction(tx: Transaction) -> Uint:
328
    """
329
    Verifies a transaction.
330
331
    The gas in a transaction gets used to pay for the intrinsic cost of
332
    operations, therefore if there is insufficient gas then it would not
333
    be possible to execute a transaction and it will be declared invalid.
334
335
    Additionally, the nonce of a transaction must not equal or exceed the
336
    limit defined in [EIP-2681].
337
    In practice, defining the limit as ``2**64-1`` has no impact because
338
    sending ``2**64-1`` transactions is improbable. It's not strictly
339
    impossible though, ``2**64-1`` transactions is the entire capacity of the
340
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
341
342
    Also, the code size of a contract creation transaction must be within
343
    limits of the protocol.
344
345
    This function takes a transaction as a parameter and returns the intrinsic
346
    gas cost of the transaction after validation. It throws an
347
    `InsufficientTransactionGasError` exception if the transaction does not
348
    provide enough gas to cover the intrinsic cost, and a `NonceOverflowError`
349
    exception if the nonce is greater than `2**64 - 2`. It also raises an
350
    `InitCodeTooLargeError` if the code size of a contract creation transaction
351
    exceeds the maximum allowed size.
352
353
    [EIP-2681]: https://eips.ethereum.org/EIPS/eip-2681
354
    """
355
    from .vm.interpreter import MAX_INIT_CODE_SIZE
356
357
    intrinsic_gas = calculate_intrinsic_cost(tx)
358
    if intrinsic_gas > tx.gas:
359
        raise InsufficientTransactionGasError("Insufficient gas")
360
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
361
        raise NonceOverflowError("Nonce too high")
362
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
363
        raise InitCodeTooLargeError("Code size too large")
364
365
    return intrinsic_gas

calculate_intrinsic_cost

Calculates the gas that is charged before execution is started.

The intrinsic cost of the transaction is charged before execution has begun. Functions/operations in the EVM cost money to execute so this intrinsic cost is for the operations that need to be paid for as part of the transaction. Data transfer, for example, is part of this intrinsic cost. It costs ether to send data over the wire and that ether is accounted for in the intrinsic cost calculated in this function. This intrinsic cost must be calculated and paid for before execution in order for all operations to be implemented.

The intrinsic cost includes:

  1. Base cost (TX_BASE_COST)

  2. Cost for data (zero and non-zero bytes)

  3. Cost for contract creation (if applicable)

  4. Cost for access list entries (if applicable)

This function takes a transaction as a parameter and returns the intrinsic gas cost of the transaction.

def calculate_intrinsic_cost(tx: Transaction) -> Uint:
369
    """
370
    Calculates the gas that is charged before execution is started.
371
372
    The intrinsic cost of the transaction is charged before execution has
373
    begun. Functions/operations in the EVM cost money to execute so this
374
    intrinsic cost is for the operations that need to be paid for as part of
375
    the transaction. Data transfer, for example, is part of this intrinsic
376
    cost. It costs ether to send data over the wire and that ether is
377
    accounted for in the intrinsic cost calculated in this function. This
378
    intrinsic cost must be calculated and paid for before execution in order
379
    for all operations to be implemented.
380
381
    The intrinsic cost includes:
382
    1. Base cost (`TX_BASE_COST`)
383
    2. Cost for data (zero and non-zero bytes)
384
    3. Cost for contract creation (if applicable)
385
    4. Cost for access list entries (if applicable)
386
387
    This function takes a transaction as a parameter and returns the intrinsic
388
    gas cost of the transaction.
389
    """
390
    from .vm.gas import init_code_cost
391
392
    data_cost = Uint(0)
393
394
    for byte in tx.data:
395
        if byte == 0:
396
            data_cost += TX_DATA_COST_PER_ZERO
397
        else:
398
            data_cost += TX_DATA_COST_PER_NON_ZERO
399
400
    if tx.to == Bytes0(b""):
401
        create_cost = TX_CREATE_COST + init_code_cost(ulen(tx.data))
402
    else:
403
        create_cost = Uint(0)
404
405
    access_list_cost = Uint(0)
406
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
407
        for access in tx.access_list:
408
            access_list_cost += TX_ACCESS_LIST_ADDRESS_COST
409
            access_list_cost += (
410
                ulen(access.slots) * TX_ACCESS_LIST_STORAGE_KEY_COST
411
            )
412
413
    return TX_BASE_COST + data_cost + create_cost + access_list_cost

recover_sender

Extracts the sender address from a transaction.

The v, r, and s values are the three parts that make up the signature of a transaction. In order to recover the sender of a transaction the two components needed are the signature (v, r, and s) and the signing hash of the transaction. The sender's public key can be obtained with these two values and therefore the sender address can be retrieved.

This function takes chain_id and a transaction as parameters and returns the address of the sender of the transaction. It raises an InvalidSignatureError if the signature values (r, s, v) are invalid.

def recover_sender(chain_id: U64, ​​tx: Transaction) -> Address:
417
    """
418
    Extracts the sender address from a transaction.
419
420
    The v, r, and s values are the three parts that make up the signature
421
    of a transaction. In order to recover the sender of a transaction the two
422
    components needed are the signature (``v``, ``r``, and ``s``) and the
423
    signing hash of the transaction. The sender's public key can be obtained
424
    with these two values and therefore the sender address can be retrieved.
425
426
    This function takes chain_id and a transaction as parameters and returns
427
    the address of the sender of the transaction. It raises an
428
    `InvalidSignatureError` if the signature values (r, s, v) are invalid.
429
    """
430
    r, s = tx.r, tx.s
431
    if U256(0) >= r or r >= SECP256K1N:
432
        raise InvalidSignatureError("bad r")
433
    if U256(0) >= s or s > SECP256K1N // U256(2):
434
        raise InvalidSignatureError("bad s")
435
436
    if isinstance(tx, LegacyTransaction):
437
        v = tx.v
438
        if v == 27 or v == 28:
439
            public_key = secp256k1_recover(
440
                r, s, v - U256(27), signing_hash_pre155(tx)
441
            )
442
        else:
443
            chain_id_x2 = U256(chain_id) * U256(2)
444
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
445
                raise InvalidSignatureError("bad v")
446
            public_key = secp256k1_recover(
447
                r,
448
                s,
449
                v - U256(35) - chain_id_x2,
450
                signing_hash_155(tx, chain_id),
451
            )
452
    elif isinstance(tx, AccessListTransaction):
453
        if tx.y_parity not in (U256(0), U256(1)):
454
            raise InvalidSignatureError("bad y_parity")
455
        public_key = secp256k1_recover(
456
            r, s, tx.y_parity, signing_hash_2930(tx)
457
        )
458
    elif isinstance(tx, FeeMarketTransaction):
459
        if tx.y_parity not in (U256(0), U256(1)):
460
            raise InvalidSignatureError("bad y_parity")
461
        public_key = secp256k1_recover(
462
            r, s, tx.y_parity, signing_hash_1559(tx)
463
        )
464
465
    return Address(keccak256(public_key)[12:32])

signing_hash_pre155

Compute the hash of a transaction used in a legacy (pre EIP-155) signature.

This function takes a legacy transaction as a parameter and returns the signing hash of the transaction.

def signing_hash_pre155(tx: LegacyTransaction) -> Hash32:
469
    """
470
    Compute the hash of a transaction used in a legacy (pre [EIP-155])
471
    signature.
472
473
    This function takes a legacy transaction as a parameter and returns the
474
    signing hash of the transaction.
475
476
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
477
    """
478
    return keccak256(
479
        rlp.encode(
480
            (
481
                tx.nonce,
482
                tx.gas_price,
483
                tx.gas,
484
                tx.to,
485
                tx.value,
486
                tx.data,
487
            )
488
        )
489
    )

signing_hash_155

Compute the hash of a transaction used in a EIP-155 signature.

This function takes a legacy transaction and a chain ID as parameters and returns the hash of the transaction used in an EIP-155 signature.

def signing_hash_155(tx: LegacyTransaction, ​​chain_id: U64) -> Hash32:
493
    """
494
    Compute the hash of a transaction used in a [EIP-155] signature.
495
496
    This function takes a legacy transaction and a chain ID as parameters
497
    and returns the hash of the transaction used in an [EIP-155] signature.
498
499
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
500
    """
501
    return keccak256(
502
        rlp.encode(
503
            (
504
                tx.nonce,
505
                tx.gas_price,
506
                tx.gas,
507
                tx.to,
508
                tx.value,
509
                tx.data,
510
                chain_id,
511
                Uint(0),
512
                Uint(0),
513
            )
514
        )
515
    )

signing_hash_2930

Compute the hash of a transaction used in a EIP-2930 signature.

This function takes an access list transaction as a parameter and returns the hash of the transaction used in an EIP-2930 signature.

def signing_hash_2930(tx: AccessListTransaction) -> Hash32:
519
    """
520
    Compute the hash of a transaction used in a [EIP-2930] signature.
521
522
    This function takes an access list transaction as a parameter
523
    and returns the hash of the transaction used in an [EIP-2930] signature.
524
525
    [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
526
    """
527
    return keccak256(
528
        b"\x01"
529
        + rlp.encode(
530
            (
531
                tx.chain_id,
532
                tx.nonce,
533
                tx.gas_price,
534
                tx.gas,
535
                tx.to,
536
                tx.value,
537
                tx.data,
538
                tx.access_list,
539
            )
540
        )
541
    )

signing_hash_1559

Compute the hash of a transaction used in an EIP-1559 signature.

This function takes a fee market transaction as a parameter and returns the hash of the transaction used in an EIP-1559 signature.

def signing_hash_1559(tx: FeeMarketTransaction) -> Hash32:
545
    """
546
    Compute the hash of a transaction used in an [EIP-1559] signature.
547
548
    This function takes a fee market transaction as a parameter
549
    and returns the hash of the transaction used in an [EIP-1559] signature.
550
551
    [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
552
    """
553
    return keccak256(
554
        b"\x02"
555
        + rlp.encode(
556
            (
557
                tx.chain_id,
558
                tx.nonce,
559
                tx.max_priority_fee_per_gas,
560
                tx.max_fee_per_gas,
561
                tx.gas,
562
                tx.to,
563
                tx.value,
564
                tx.data,
565
                tx.access_list,
566
            )
567
        )
568
    )

get_transaction_hash

Compute the hash of a transaction.

This function takes a transaction as a parameter and returns the keccak256 hash of the transaction. It can handle both legacy transactions and typed transactions (AccessListTransaction, FeeMarketTransaction, etc.).

def get_transaction_hash(tx: Bytes | LegacyTransaction) -> Hash32:
572
    """
573
    Compute the hash of a transaction.
574
575
    This function takes a transaction as a parameter and returns the
576
    keccak256 hash of the transaction. It can handle both legacy transactions
577
    and typed transactions (`AccessListTransaction`, `FeeMarketTransaction`,
578
    etc.).
579
    """
580
    assert isinstance(tx, (LegacyTransaction, Bytes))
581
    if isinstance(tx, LegacyTransaction):
582
        return keccak256(rlp.encode(tx))
583
    else:
584
        return keccak256(tx)