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

33
@final
34
@dataclass
class IntrinsicGasCost:

regular

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

38
    regular: Uint

calldata_floor

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

41
    calldata_floor: Uint

TX_MAX_GAS_LIMIT

45
TX_MAX_GAS_LIMIT = Uint(16_777_216)

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.

48
@final
49
@slotted_freezable
50
@dataclass
class LegacyTransaction:

nonce

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

63
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

68
    gas_price: Uint

gas

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

73
    gas: Uint

to

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

78
    to: Bytes0 | Address

value

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

84
    value: U256

data

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

89
    data: Bytes

v

The recovery id of the signature.

95
    v: U256

r

The first part of the signature.

100
    r: U256

s

The second part of the signature.

105
    s: U256

Access

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

111
@final
112
@slotted_freezable
113
@dataclass
class Access:

account

The address of the account that is accessed.

120
    account: Address

slots

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

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

131
@final
132
@slotted_freezable
133
@dataclass
class AccessListTransaction:

chain_id

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

145
    chain_id: U64

nonce

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

150
    nonce: U256

gas_price

The price of gas for this transaction.

155
    gas_price: Uint

gas

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

160
    gas: Uint

to

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

165
    to: Bytes0 | Address

value

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

171
    value: U256

data

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

176
    data: Bytes

access_list

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

182
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

188
    y_parity: U256

r

The first part of the signature.

193
    r: U256

s

The second part of the signature.

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

204
@final
205
@slotted_freezable
206
@dataclass
class FeeMarketTransaction:

chain_id

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

217
    chain_id: U64

nonce

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

222
    nonce: U256

max_priority_fee_per_gas

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

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

232
    max_fee_per_gas: Uint

gas

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

238
    gas: Uint

to

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

243
    to: Bytes0 | Address

value

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

249
    value: U256

data

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

254
    data: Bytes

access_list

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

260
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

266
    y_parity: U256

r

The first part of the signature.

271
    r: U256

s

The second part of the signature.

276
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

282
@final
283
@slotted_freezable
284
@dataclass
class BlobTransaction:

chain_id

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

295
    chain_id: U64

nonce

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

300
    nonce: U256

max_priority_fee_per_gas

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

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

310
    max_fee_per_gas: Uint

gas

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

316
    gas: Uint

to

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

321
    to: Address

value

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

327
    value: U256

data

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

332
    data: Bytes

access_list

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

338
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

349
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

355
    y_parity: U256

r

The first part of the signature.

360
    r: U256

s

The second part of the signature.

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

371
@final
372
@slotted_freezable
373
@dataclass
class SetCodeTransaction:

chain_id

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

384
    chain_id: U64

nonce

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

389
    nonce: U64

max_priority_fee_per_gas

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

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

399
    max_fee_per_gas: Uint

gas

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

405
    gas: Uint

to

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

410
    to: Address

value

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

416
    value: U256

data

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

421
    data: Bytes

access_list

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

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

433
    authorizations: Tuple[Authorization, ...]

y_parity

The recovery id of the signature.

439
    y_parity: U256

r

The first part of the signature.

444
    r: U256

s

The second part of the signature.

449
    s: U256

Transaction

Union type representing any valid transaction type.

455
Transaction = (
456
    LegacyTransaction
457
    | AccessListTransaction
458
    | FeeMarketTransaction
459
    | BlobTransaction
460
    | SetCodeTransaction
461
)

AccessListCapableTransaction

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

See has_access_list and Access for more details.

467
AccessListCapableTransaction = (
468
    AccessListTransaction
469
    | FeeMarketTransaction
470
    | BlobTransaction
471
    | SetCodeTransaction
472
)

FeeMarketCapableTransaction

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

See FeeMarketTransaction for more details.

484
FeeMarketCapableTransaction = (
485
    FeeMarketTransaction | BlobTransaction | SetCodeTransaction
486
)

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:
498
    <snip>
505
    if isinstance(tx, LegacyTransaction):
506
        return tx
507
    elif isinstance(tx, AccessListTransaction):
508
        return b"\x01" + rlp.encode(tx)
509
    elif isinstance(tx, FeeMarketTransaction):
510
        return b"\x02" + rlp.encode(tx)
511
    elif isinstance(tx, BlobTransaction):
512
        return b"\x03" + rlp.encode(tx)
513
    elif isinstance(tx, SetCodeTransaction):
514
        return b"\x04" + rlp.encode(tx)
515
    else:
516
        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:
520
    <snip>
527
    if isinstance(tx, Bytes):
528
        if tx[0] == 1:
529
            return rlp.decode_to(AccessListTransaction, tx[1:])
530
        elif tx[0] == 2:
531
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
532
        elif tx[0] == 3:
533
            return rlp.decode_to(BlobTransaction, tx[1:])
534
        elif tx[0] == 4:
535
            return rlp.decode_to(SetCodeTransaction, tx[1:])
536
        else:
537
            raise TransactionTypeError(tx[0])
538
    else:
539
        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:
543
    <snip>
573
    from .vm.interpreter import MAX_INIT_CODE_SIZE
574
575
    intrinsic = calculate_intrinsic_cost(tx)
576
    if max(intrinsic.regular, intrinsic.calldata_floor) > tx.gas:
577
        raise InsufficientTransactionGasError("Insufficient gas")
578
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
579
        raise InitCodeTooLargeError("Code size too large")
580
    if tx.gas > TX_MAX_GAS_LIMIT:
581
        raise TransactionGasLimitExceededError("Gas limit too high")
582
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
583
        raise NonceOverflowError("Nonce too high")
584
    if isinstance(tx, FeeMarketCapableTransaction):
585
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
586
            raise PriorityFeeGreaterThanMaxFeeError(
587
                "priority fee greater than max fee"
588
            )
589
590
    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:
594
    <snip>
618
    from .vm.gas import GasCosts, init_code_cost
619
620
    num_zeros = Uint(tx.data.count(0))
621
    num_non_zeros = ulen(tx.data) - num_zeros
622
623
    tokens_in_calldata = num_zeros + num_non_zeros * Uint(4)
624
    # EIP-7623 floor price (note: no EVM costs)
625
    calldata_floor_gas_cost = (
626
        tokens_in_calldata * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
627
    )
628
629
    data_cost = tokens_in_calldata * GasCosts.TX_DATA_TOKEN_STANDARD
630
631
    if tx.to == Bytes0(b""):
632
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
633
    else:
634
        create_cost = Uint(0)
635
636
    access_list_cost = Uint(0)
637
    if has_access_list(tx):
638
        for access in tx.access_list:
639
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
640
            access_list_cost += (
641
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
642
            )
643
644
    auth_cost = Uint(0)
645
    if isinstance(tx, SetCodeTransaction):
646
        auth_cost += Uint(
647
            GasCosts.AUTH_PER_EMPTY_ACCOUNT * len(tx.authorizations)
648
        )
649
650
    return IntrinsicGasCost(
651
        regular=Uint(
652
            GasCosts.TX_BASE
653
            + data_cost
654
            + create_cost
655
            + access_list_cost
656
            + auth_cost
657
        ),
658
        calldata_floor=calldata_floor_gas_cost,
659
    )

chain_id

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

def chain_id(tx: Transaction) -> None | U64:
663
    <snip>
668
    if isinstance(tx, LegacyTransaction):
669
        if tx.v == 27 or tx.v == 28:
670
            return None
671
672
        if tx.v < U256(35):
673
            raise InvalidSignatureError("bad v")
674
675
        return U64((tx.v - U256(35)) >> U256(1))
676
    else:
677
        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:
681
    <snip>
694
    r, s = tx.r, tx.s
695
    if U256(0) >= r or r >= SECP256K1N:
696
        raise InvalidSignatureError("bad r")
697
    if U256(0) >= s or s > SECP256K1N // U256(2):
698
        raise InvalidSignatureError("bad s")
699
700
    if isinstance(tx, LegacyTransaction):
701
        v = tx.v
702
        if v == 27 or v == 28:
703
            public_key = secp256k1_recover(
704
                r, s, v - U256(27), signing_hash_pre155(tx)
705
            )
706
        else:
707
            assert v >= U256(35), "call chain_id before recover_sender"
708
            tx_chain_id = U64((v - U256(35)) >> U256(1))
709
            v = (v - U256(35)) & U256(1)
710
            public_key = secp256k1_recover(
711
                r,
712
                s,
713
                v,
714
                signing_hash_155(tx, tx_chain_id),
715
            )
716
    elif isinstance(tx, AccessListTransaction):
717
        if tx.y_parity not in (U256(0), U256(1)):
718
            raise InvalidSignatureError("bad y_parity")
719
        public_key = secp256k1_recover(
720
            r, s, tx.y_parity, signing_hash_2930(tx)
721
        )
722
    elif isinstance(tx, FeeMarketTransaction):
723
        if tx.y_parity not in (U256(0), U256(1)):
724
            raise InvalidSignatureError("bad y_parity")
725
        public_key = secp256k1_recover(
726
            r, s, tx.y_parity, signing_hash_1559(tx)
727
        )
728
    elif isinstance(tx, BlobTransaction):
729
        if tx.y_parity not in (U256(0), U256(1)):
730
            raise InvalidSignatureError("bad y_parity")
731
        public_key = secp256k1_recover(
732
            r, s, tx.y_parity, signing_hash_4844(tx)
733
        )
734
    elif isinstance(tx, SetCodeTransaction):
735
        if tx.y_parity not in (U256(0), U256(1)):
736
            raise InvalidSignatureError("bad y_parity")
737
        public_key = secp256k1_recover(
738
            r, s, tx.y_parity, signing_hash_7702(tx)
739
        )
740
741
    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:
745
    <snip>
754
    return keccak256(
755
        rlp.encode(
756
            (
757
                tx.nonce,
758
                tx.gas_price,
759
                tx.gas,
760
                tx.to,
761
                tx.value,
762
                tx.data,
763
            )
764
        )
765
    )

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:
769
    <snip>
777
    return keccak256(
778
        rlp.encode(
779
            (
780
                tx.nonce,
781
                tx.gas_price,
782
                tx.gas,
783
                tx.to,
784
                tx.value,
785
                tx.data,
786
                chain_id,
787
                Uint(0),
788
                Uint(0),
789
            )
790
        )
791
    )

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:
795
    <snip>
803
    return keccak256(
804
        b"\x01"
805
        + rlp.encode(
806
            (
807
                tx.chain_id,
808
                tx.nonce,
809
                tx.gas_price,
810
                tx.gas,
811
                tx.to,
812
                tx.value,
813
                tx.data,
814
                tx.access_list,
815
            )
816
        )
817
    )

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:
821
    <snip>
829
    return keccak256(
830
        b"\x02"
831
        + rlp.encode(
832
            (
833
                tx.chain_id,
834
                tx.nonce,
835
                tx.max_priority_fee_per_gas,
836
                tx.max_fee_per_gas,
837
                tx.gas,
838
                tx.to,
839
                tx.value,
840
                tx.data,
841
                tx.access_list,
842
            )
843
        )
844
    )

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:
848
    <snip>
856
    return keccak256(
857
        b"\x03"
858
        + rlp.encode(
859
            (
860
                tx.chain_id,
861
                tx.nonce,
862
                tx.max_priority_fee_per_gas,
863
                tx.max_fee_per_gas,
864
                tx.gas,
865
                tx.to,
866
                tx.value,
867
                tx.data,
868
                tx.access_list,
869
                tx.max_fee_per_blob_gas,
870
                tx.blob_versioned_hashes,
871
            )
872
        )
873
    )

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:
877
    <snip>
885
    return keccak256(
886
        b"\x04"
887
        + rlp.encode(
888
            (
889
                tx.chain_id,
890
                tx.nonce,
891
                tx.max_priority_fee_per_gas,
892
                tx.max_fee_per_gas,
893
                tx.gas,
894
                tx.to,
895
                tx.value,
896
                tx.data,
897
                tx.access_list,
898
                tx.authorizations,
899
            )
900
        )
901
    )

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:
905
    <snip>
913
    assert isinstance(tx, (LegacyTransaction, Bytes))
914
    if isinstance(tx, LegacyTransaction):
915
        return keccak256(rlp.encode(tx))
916
    else:
917
        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]:
923
    <snip>
928
    return isinstance(
929
        tx,
930
        AccessListCapableTransaction,
931
    )