ethereum.forks.bpo5.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.

IntrinsicGasCost

Intrinsic gas costs for a transaction, split by gas type.

34
@final
35
@dataclass
class IntrinsicGasCost:

regular

Regular execution gas (calldata, base cost, access list, etc.).

39
    regular: Uint

calldata_floor

Minimum gas cost based on calldata size per EIP-7623.

42
    calldata_floor: Uint

LegacyTransaction

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

50
@final
51
@slotted_freezable
52
@dataclass
class LegacyTransaction:

nonce

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

65
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

70
    gas_price: Uint

gas

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

75
    gas: Uint

to

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

80
    to: Bytes0 | Address

value

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

86
    value: U256

data

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

91
    data: Bytes

v

The recovery id of the signature.

97
    v: U256

r

The first part of the signature.

102
    r: U256

s

The second part of the signature.

107
    s: U256

Access

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

113
@final
114
@slotted_freezable
115
@dataclass
class Access:

account

The address of the account that is accessed.

122
    account: Address

slots

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

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

133
@final
134
@slotted_freezable
135
@dataclass
class AccessListTransaction:

chain_id

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

147
    chain_id: U64

nonce

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

152
    nonce: U256

gas_price

The price of gas for this transaction.

157
    gas_price: Uint

gas

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

162
    gas: Uint

to

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

167
    to: Bytes0 | Address

value

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

173
    value: U256

data

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

178
    data: Bytes

access_list

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

184
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

190
    y_parity: U256

r

The first part of the signature.

195
    r: U256

s

The second part of the signature.

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

206
@final
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

BlobTransaction

The transaction type added in EIP-4844.

This transaction type extends the fee market transaction to support blob-carrying transactions.

284
@final
285
@slotted_freezable
286
@dataclass
class BlobTransaction:

chain_id

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

297
    chain_id: U64

nonce

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

302
    nonce: U256

max_priority_fee_per_gas

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

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

312
    max_fee_per_gas: Uint

gas

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

318
    gas: Uint

to

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

323
    to: Address

value

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

329
    value: U256

data

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

334
    data: Bytes

access_list

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

340
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

346
    max_fee_per_blob_gas: U256

blob_versioned_hashes

A tuple of objects that represent the versioned hashes of the blobs included in the transaction.

351
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

357
    y_parity: U256

r

The first part of the signature.

362
    r: U256

s

The second part of the signature.

367
    s: U256

SetCodeTransaction

The transaction type added in EIP-7702.

This transaction type allows Ethereum Externally Owned Accounts (EOAs) to set code on their account, enabling them to act as smart contracts.

373
@final
374
@slotted_freezable
375
@dataclass
class SetCodeTransaction:

chain_id

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

386
    chain_id: U64

nonce

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

391
    nonce: U64

max_priority_fee_per_gas

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

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

401
    max_fee_per_gas: Uint

gas

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

407
    gas: Uint

to

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

412
    to: Address

value

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

418
    value: U256

data

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

423
    data: Bytes

access_list

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

429
    access_list: Tuple[Access, ...]

authorizations

A tuple of Authorization objects that specify what code the signer desires to execute in the context of their EOA.

435
    authorizations: Tuple[Authorization, ...]

y_parity

The recovery id of the signature.

441
    y_parity: U256

r

The first part of the signature.

446
    r: U256

s

The second part of the signature.

451
    s: U256

Transaction

Union type representing any valid transaction type.

457
Transaction = (
458
    LegacyTransaction
459
    | AccessListTransaction
460
    | FeeMarketTransaction
461
    | BlobTransaction
462
    | SetCodeTransaction
463
)

AccessListCapableTransaction

Transaction types that include an EIP-2930-style access list.

See has_access_list and Access for more details.

469
AccessListCapableTransaction = (
470
    AccessListTransaction
471
    | FeeMarketTransaction
472
    | BlobTransaction
473
    | SetCodeTransaction
474
)

FeeMarketCapableTransaction

Transaction types that include the EIP-1559-style fee structure.

See FeeMarketTransaction for more details.

486
FeeMarketCapableTransaction = (
487
    FeeMarketTransaction | BlobTransaction | SetCodeTransaction
488
)

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:
500
    <snip>
507
    if isinstance(tx, LegacyTransaction):
508
        return tx
509
    elif isinstance(tx, AccessListTransaction):
510
        return b"\x01" + rlp.encode(tx)
511
    elif isinstance(tx, FeeMarketTransaction):
512
        return b"\x02" + rlp.encode(tx)
513
    elif isinstance(tx, BlobTransaction):
514
        return b"\x03" + rlp.encode(tx)
515
    elif isinstance(tx, SetCodeTransaction):
516
        return b"\x04" + rlp.encode(tx)
517
    else:
518
        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:
522
    <snip>
529
    if isinstance(tx, Bytes):
530
        if len(tx) == 0:
531
            raise InvalidBlock("empty transaction")
532
        if tx[0] == 1:
533
            return rlp.decode_to(AccessListTransaction, tx[1:])
534
        elif tx[0] == 2:
535
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
536
        elif tx[0] == 3:
537
            return rlp.decode_to(BlobTransaction, tx[1:])
538
        elif tx[0] == 4:
539
            return rlp.decode_to(SetCodeTransaction, tx[1:])
540
        else:
541
            raise TransactionTypeError(tx[0])
542
    else:
543
        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 and the minimum calldata gas cost for 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, and a PriorityFeeGreaterThanMaxFeeError if the maximum priority fee per gas of a fee market transaction exceeds its maximum fee per gas.

def validate_transaction(​tx: Transaction​) -> IntrinsicGasCost:
547
    <snip>
577
    from .vm.gas import GasCosts
578
    from .vm.interpreter import MAX_INIT_CODE_SIZE
579
580
    intrinsic = calculate_intrinsic_cost(tx)
581
    if max(intrinsic.regular, intrinsic.calldata_floor) > tx.gas:
582
        raise InsufficientTransactionGasError("Insufficient gas")
583
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
584
        raise InitCodeTooLargeError("Code size too large")
585
    if tx.gas > GasCosts.TX_MAX_GAS_LIMIT:
586
        raise TransactionGasLimitExceededError("Gas limit too high")
587
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
588
        raise NonceOverflowError("Nonce too high")
589
    if isinstance(tx, FeeMarketCapableTransaction):
590
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
591
            raise PriorityFeeGreaterThanMaxFeeError(
592
                "priority fee greater than max fee"
593
            )
594
595
    return intrinsic

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)

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

  3. Cost for contract creation (if applicable)

  4. Cost for access list entries (if applicable)

  5. Cost for authorizations (if applicable)

This function takes a transaction as a parameter and returns the intrinsic gas cost of the transaction and the minimum gas cost used by the transaction based on the calldata size.

def calculate_intrinsic_cost(​tx: Transaction​) -> IntrinsicGasCost:
599
    <snip>
623
    from .vm.gas import GasCosts, init_code_cost
624
625
    num_zeros = Uint(tx.data.count(0))
626
    num_non_zeros = ulen(tx.data) - num_zeros
627
628
    tokens_in_calldata = num_zeros + num_non_zeros * Uint(4)
629
    # EIP-7623 floor price (note: no EVM costs)
630
    calldata_floor_gas_cost = (
631
        tokens_in_calldata * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
632
    )
633
634
    data_cost = tokens_in_calldata * GasCosts.TX_DATA_TOKEN_STANDARD
635
636
    if tx.to == Bytes0(b""):
637
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
638
    else:
639
        create_cost = Uint(0)
640
641
    access_list_cost = Uint(0)
642
    if has_access_list(tx):
643
        for access in tx.access_list:
644
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
645
            access_list_cost += (
646
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
647
            )
648
649
    auth_cost = Uint(0)
650
    if isinstance(tx, SetCodeTransaction):
651
        auth_cost += Uint(
652
            GasCosts.AUTH_PER_EMPTY_ACCOUNT * len(tx.authorizations)
653
        )
654
655
    return IntrinsicGasCost(
656
        regular=Uint(
657
            GasCosts.TX_BASE
658
            + data_cost
659
            + create_cost
660
            + access_list_cost
661
            + auth_cost
662
        ),
663
        calldata_floor=calldata_floor_gas_cost,
664
    )

chain_id

Extract the chain identifier from a transaction. See EIP-155.

def chain_id(​tx: Transaction​) -> None | U64:
668
    <snip>
673
    if isinstance(tx, LegacyTransaction):
674
        if tx.v == 27 or tx.v == 28:
675
            return None
676
677
        if tx.v < U256(35):
678
            raise InvalidSignatureError("bad v")
679
680
        tx_chain_id = (tx.v - U256(35)) >> U256(1)
681
        if tx_chain_id > U256(U64.MAX_VALUE):
682
            raise InvalidSignatureError("bad v")
683
        return U64(tx_chain_id)
684
    else:
685
        return tx.chain_id

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(​tx: Transaction​) -> Address:
689
    <snip>
702
    r, s = tx.r, tx.s
703
    if U256(0) >= r or r >= SECP256K1N:
704
        raise InvalidSignatureError("bad r")
705
    if U256(0) >= s or s > SECP256K1N // U256(2):
706
        raise InvalidSignatureError("bad s")
707
708
    if isinstance(tx, LegacyTransaction):
709
        v = tx.v
710
        if v == 27 or v == 28:
711
            public_key = secp256k1_recover(
712
                r, s, v - U256(27), signing_hash_pre155(tx)
713
            )
714
        else:
715
            assert v >= U256(35), "call chain_id before recover_sender"
716
            tx_chain_id = U64((v - U256(35)) >> U256(1))
717
            v = (v - U256(35)) & U256(1)
718
            public_key = secp256k1_recover(
719
                r,
720
                s,
721
                v,
722
                signing_hash_155(tx, tx_chain_id),
723
            )
724
    elif isinstance(tx, AccessListTransaction):
725
        if tx.y_parity not in (U256(0), U256(1)):
726
            raise InvalidSignatureError("bad y_parity")
727
        public_key = secp256k1_recover(
728
            r, s, tx.y_parity, signing_hash_2930(tx)
729
        )
730
    elif isinstance(tx, FeeMarketTransaction):
731
        if tx.y_parity not in (U256(0), U256(1)):
732
            raise InvalidSignatureError("bad y_parity")
733
        public_key = secp256k1_recover(
734
            r, s, tx.y_parity, signing_hash_1559(tx)
735
        )
736
    elif isinstance(tx, BlobTransaction):
737
        if tx.y_parity not in (U256(0), U256(1)):
738
            raise InvalidSignatureError("bad y_parity")
739
        public_key = secp256k1_recover(
740
            r, s, tx.y_parity, signing_hash_4844(tx)
741
        )
742
    elif isinstance(tx, SetCodeTransaction):
743
        if tx.y_parity not in (U256(0), U256(1)):
744
            raise InvalidSignatureError("bad y_parity")
745
        public_key = secp256k1_recover(
746
            r, s, tx.y_parity, signing_hash_7702(tx)
747
        )
748
749
    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:
753
    <snip>
762
    return keccak256(
763
        rlp.encode(
764
            (
765
                tx.nonce,
766
                tx.gas_price,
767
                tx.gas,
768
                tx.to,
769
                tx.value,
770
                tx.data,
771
            )
772
        )
773
    )

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:
777
    <snip>
785
    return keccak256(
786
        rlp.encode(
787
            (
788
                tx.nonce,
789
                tx.gas_price,
790
                tx.gas,
791
                tx.to,
792
                tx.value,
793
                tx.data,
794
                chain_id,
795
                Uint(0),
796
                Uint(0),
797
            )
798
        )
799
    )

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:
803
    <snip>
811
    return keccak256(
812
        b"\x01"
813
        + rlp.encode(
814
            (
815
                tx.chain_id,
816
                tx.nonce,
817
                tx.gas_price,
818
                tx.gas,
819
                tx.to,
820
                tx.value,
821
                tx.data,
822
                tx.access_list,
823
            )
824
        )
825
    )

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:
829
    <snip>
837
    return keccak256(
838
        b"\x02"
839
        + rlp.encode(
840
            (
841
                tx.chain_id,
842
                tx.nonce,
843
                tx.max_priority_fee_per_gas,
844
                tx.max_fee_per_gas,
845
                tx.gas,
846
                tx.to,
847
                tx.value,
848
                tx.data,
849
                tx.access_list,
850
            )
851
        )
852
    )

signing_hash_4844

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

This function takes a transaction as a parameter and returns the signing hash of the transaction used in an EIP-4844 signature.

def signing_hash_4844(​tx: BlobTransaction​) -> Hash32:
856
    <snip>
864
    return keccak256(
865
        b"\x03"
866
        + rlp.encode(
867
            (
868
                tx.chain_id,
869
                tx.nonce,
870
                tx.max_priority_fee_per_gas,
871
                tx.max_fee_per_gas,
872
                tx.gas,
873
                tx.to,
874
                tx.value,
875
                tx.data,
876
                tx.access_list,
877
                tx.max_fee_per_blob_gas,
878
                tx.blob_versioned_hashes,
879
            )
880
        )
881
    )

signing_hash_7702

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

This function takes a transaction as a parameter and returns the signing hash of the transaction used in a EIP-7702 signature.

def signing_hash_7702(​tx: SetCodeTransaction​) -> Hash32:
885
    <snip>
893
    return keccak256(
894
        b"\x04"
895
        + rlp.encode(
896
            (
897
                tx.chain_id,
898
                tx.nonce,
899
                tx.max_priority_fee_per_gas,
900
                tx.max_fee_per_gas,
901
                tx.gas,
902
                tx.to,
903
                tx.value,
904
                tx.data,
905
                tx.access_list,
906
                tx.authorizations,
907
            )
908
        )
909
    )

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:
913
    <snip>
921
    assert isinstance(tx, (LegacyTransaction, Bytes))
922
    if isinstance(tx, LegacyTransaction):
923
        return keccak256(rlp.encode(tx))
924
    else:
925
        return keccak256(tx)

has_access_list

Return whether the transaction has an EIP-2930-style access list.

def has_access_list(​tx: Transaction​) -> TypeGuard[AccessListCapableTransaction]:
931
    <snip>
936
    return isinstance(
937
        tx,
938
        AccessListCapableTransaction,
939
    )