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

31
TX_MAX_GAS_LIMIT = Uint(16_777_216)

ACCESS_LIST_ADDRESS_FLOOR_TOKENS

Floor data tokens contributed by a single access list address per EIP-7981.

33
ACCESS_LIST_ADDRESS_FLOOR_TOKENS = Uint(80)

ACCESS_LIST_STORAGE_KEY_FLOOR_TOKENS

Floor data tokens contributed by a single access list storage key per EIP-7981.

41
ACCESS_LIST_STORAGE_KEY_FLOOR_TOKENS = Uint(128)

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
@slotted_freezable
51
@dataclass
class LegacyTransaction:

nonce

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

64
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

69
    gas_price: Uint

gas

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

74
    gas: Uint

to

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

79
    to: Bytes0 | Address

value

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

85
    value: U256

data

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

90
    data: Bytes

v

The recovery id of the signature.

96
    v: U256

r

The first part of the signature.

101
    r: U256

s

The second part of the signature.

106
    s: U256

Access

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

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
@slotted_freezable
132
@dataclass
class AccessListTransaction:

chain_id

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

144
    chain_id: U64

nonce

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

149
    nonce: U256

gas_price

The price of gas for this transaction.

154
    gas_price: Uint

gas

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

159
    gas: Uint

to

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

164
    to: Bytes0 | Address

value

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

170
    value: U256

data

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

175
    data: Bytes

access_list

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

181
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

187
    y_parity: U256

r

The first part of the signature.

192
    r: U256

s

The second part of the signature.

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

203
@slotted_freezable
204
@dataclass
class FeeMarketTransaction:

chain_id

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

215
    chain_id: U64

nonce

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

220
    nonce: U256

max_priority_fee_per_gas

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

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

230
    max_fee_per_gas: Uint

gas

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

236
    gas: Uint

to

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

241
    to: Bytes0 | Address

value

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

247
    value: U256

data

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

252
    data: Bytes

access_list

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

258
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

264
    y_parity: U256

r

The first part of the signature.

269
    r: U256

s

The second part of the signature.

274
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

280
@slotted_freezable
281
@dataclass
class BlobTransaction:

chain_id

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

292
    chain_id: U64

nonce

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

297
    nonce: U256

max_priority_fee_per_gas

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

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

307
    max_fee_per_gas: Uint

gas

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

313
    gas: Uint

to

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

318
    to: Address

value

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

324
    value: U256

data

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

329
    data: Bytes

access_list

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

335
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

346
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

352
    y_parity: U256

r

The first part of the signature.

357
    r: U256

s

The second part of the signature.

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

368
@slotted_freezable
369
@dataclass
class SetCodeTransaction:

chain_id

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

380
    chain_id: U64

nonce

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

385
    nonce: U64

max_priority_fee_per_gas

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

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

395
    max_fee_per_gas: Uint

gas

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

401
    gas: Uint

to

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

406
    to: Address

value

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

412
    value: U256

data

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

417
    data: Bytes

access_list

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

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

429
    authorizations: Tuple[Authorization, ...]

y_parity

The recovery id of the signature.

435
    y_parity: U256

r

The first part of the signature.

440
    r: U256

s

The second part of the signature.

445
    s: U256

Transaction

Union type representing any valid transaction type.

451
Transaction = (
452
    LegacyTransaction
453
    | AccessListTransaction
454
    | FeeMarketTransaction
455
    | BlobTransaction
456
    | SetCodeTransaction
457
)

AccessListCapableTransaction

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

See has_access_list and Access for more details.

463
AccessListCapableTransaction = (
464
    AccessListTransaction
465
    | FeeMarketTransaction
466
    | BlobTransaction
467
    | SetCodeTransaction
468
)

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:
481
    <snip>
488
    if isinstance(tx, LegacyTransaction):
489
        return tx
490
    elif isinstance(tx, AccessListTransaction):
491
        return b"\x01" + rlp.encode(tx)
492
    elif isinstance(tx, FeeMarketTransaction):
493
        return b"\x02" + rlp.encode(tx)
494
    elif isinstance(tx, BlobTransaction):
495
        return b"\x03" + rlp.encode(tx)
496
    elif isinstance(tx, SetCodeTransaction):
497
        return b"\x04" + rlp.encode(tx)
498
    else:
499
        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 typesAccept a LegacyTransaction object (returned as-is) or raw are decoded based on their type identifier prefix.bytes.

EIP-2718 states that the first byte distinguishes the format: [0x00, 0x7f] is a typed transaction, [0xc0, 0xfe] is a legacy transaction (RLP list prefix).

def decode_transaction(tx: LegacyTransaction | Bytes) -> Transaction:
503
    <snip>
514
    if isinstance(tx, Bytes):
515
        if tx[0] == 1:
516
            return rlp.decode_to(AccessListTransaction, tx[1:])
517
        elif tx[0] == 2:
518
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
519
        elif tx[0] == 3:
520
            return rlp.decode_to(BlobTransaction, tx[1:])
521
        elif tx[0] == 4:
522
            return rlp.decode_to(SetCodeTransaction, tx[1:])
503
        else:
504
            raise TransactionTypeError(tx[0])
523
        elif tx[0] >= 0xC0:
524
            assert tx[0] <= 0xFE
525
            return rlp.decode_to(LegacyTransaction, tx)
526
        else:
527
            raise TransactionTypeError(tx[0])
528
    else:
529
        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.

def validate_transaction(tx: Transaction) -> Tuple[Uint, Uint]:
533
    <snip>
561
    from .vm.interpreter import MAX_INIT_CODE_SIZE
562
540
    intrinsic_gas, calldata_floor_gas_cost = calculate_intrinsic_cost(tx)
541
    if max(intrinsic_gas, calldata_floor_gas_cost) > tx.gas:
563
    intrinsic_gas, data_floor_gas_cost = calculate_intrinsic_cost(tx)
564
    if max(intrinsic_gas, data_floor_gas_cost) > tx.gas:
565
        raise InsufficientTransactionGasError("Insufficient gas")
566
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
567
        raise NonceOverflowError("Nonce too high")
568
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
569
        raise InitCodeTooLargeError("Code size too large")
570
    if tx.gas > TX_MAX_GAS_LIMIT:
571
        raise TransactionGasLimitExceededError("Gas limit too high")
572
550
    return intrinsic_gas, calldata_floor_gas_cost
573
    return intrinsic_gas, data_floor_gas_cost

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) -> Tuple[Uint, Uint]:
577
    <snip>
601
    from .vm.gas import GasCosts, init_code_cost
602
580
    num_zeros = Uint(tx.data.count(0))
581
    num_non_zeros = ulen(tx.data) - num_zeros
582
583
    tokens_in_calldata = num_zeros + num_non_zeros * Uint(4)
584
    # EIP-7623 floor price (note: no EVM costs)
585
    calldata_floor_gas_cost = (
586
        tokens_in_calldata * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
587
    )
603
    tokens_in_calldata = count_tokens_in_data(tx.data)
604
605
    data_cost = tokens_in_calldata * GasCosts.TX_DATA_TOKEN_STANDARD
606
607
    if tx.to == Bytes0(b""):
608
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
609
    else:
610
        create_cost = Uint(0)
611
612
    access_list_cost = Uint(0)
613
    tokens_in_access_list = Uint(0)
614
    if has_access_list(tx):
615
        for access in tx.access_list:
616
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
617
            access_list_cost += (
618
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
619
            )
620
            tokens_in_access_list += ACCESS_LIST_ADDRESS_FLOOR_TOKENS
621
            tokens_in_access_list += (
622
                ulen(access.slots) * ACCESS_LIST_STORAGE_KEY_FLOOR_TOKENS
623
            )
624
625
    # Data token floor cost for access list bytes.
626
    access_list_cost += tokens_in_access_list * GasCosts.TX_DATA_TOKEN_FLOOR
627
628
    auth_cost = Uint(0)
629
    if isinstance(tx, SetCodeTransaction):
630
        auth_cost += Uint(
631
            GasCosts.AUTH_PER_EMPTY_ACCOUNT * len(tx.authorizations)
632
        )
633
634
    # EIP-7976 floor tokens: all calldata bytes count uniformly.
635
    floor_tokens_in_calldata = ulen(tx.data) * GasCosts.TX_DATA_TOKEN_STANDARD
636
637
    # Total floor tokens.
638
    total_floor_tokens = floor_tokens_in_calldata + tokens_in_access_list
639
640
    # Floor gas cost (EIP-7623: minimum gas for data-heavy transactions).
641
    data_floor_gas_cost = (
642
        total_floor_tokens * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
643
    )
644
645
    return (
646
        Uint(
647
            GasCosts.TX_BASE
648
            + data_cost
649
            + create_cost
650
            + access_list_cost
651
            + auth_cost
652
        ),
618
        calldata_floor_gas_cost,
653
        data_floor_gas_cost,
654
    )

count_tokens_in_data

Count the data tokens in arbitrary input bytes.

Zero bytes count as 1 token; non-zero bytes count as 4 tokens.

def count_tokens_in_data(data: bytes) -> Uint:
658
    <snip>
663
    num_zeros = Uint(data.count(0))
664
    num_non_zeros = ulen(data) - num_zeros
665
666
    return num_zeros + num_non_zeros * Uint(4)

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:
670
    <snip>
683
    r, s = tx.r, tx.s
684
    if U256(0) >= r or r >= SECP256K1N:
685
        raise InvalidSignatureError("bad r")
686
    if U256(0) >= s or s > SECP256K1N // U256(2):
687
        raise InvalidSignatureError("bad s")
688
689
    if isinstance(tx, LegacyTransaction):
690
        v = tx.v
691
        if v == 27 or v == 28:
692
            public_key = secp256k1_recover(
693
                r, s, v - U256(27), signing_hash_pre155(tx)
694
            )
695
        else:
696
            chain_id_x2 = U256(chain_id) * U256(2)
697
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
698
                raise InvalidSignatureError("bad v")
699
            public_key = secp256k1_recover(
700
                r,
701
                s,
702
                v - U256(35) - chain_id_x2,
703
                signing_hash_155(tx, chain_id),
704
            )
705
    elif isinstance(tx, AccessListTransaction):
706
        if tx.y_parity not in (U256(0), U256(1)):
707
            raise InvalidSignatureError("bad y_parity")
708
        public_key = secp256k1_recover(
709
            r, s, tx.y_parity, signing_hash_2930(tx)
710
        )
711
    elif isinstance(tx, FeeMarketTransaction):
712
        if tx.y_parity not in (U256(0), U256(1)):
713
            raise InvalidSignatureError("bad y_parity")
714
        public_key = secp256k1_recover(
715
            r, s, tx.y_parity, signing_hash_1559(tx)
716
        )
717
    elif isinstance(tx, BlobTransaction):
718
        if tx.y_parity not in (U256(0), U256(1)):
719
            raise InvalidSignatureError("bad y_parity")
720
        public_key = secp256k1_recover(
721
            r, s, tx.y_parity, signing_hash_4844(tx)
722
        )
723
    elif isinstance(tx, SetCodeTransaction):
724
        if tx.y_parity not in (U256(0), U256(1)):
725
            raise InvalidSignatureError("bad y_parity")
726
        public_key = secp256k1_recover(
727
            r, s, tx.y_parity, signing_hash_7702(tx)
728
        )
729
730
    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:
734
    <snip>
743
    return keccak256(
744
        rlp.encode(
745
            (
746
                tx.nonce,
747
                tx.gas_price,
748
                tx.gas,
749
                tx.to,
750
                tx.value,
751
                tx.data,
752
            )
753
        )
754
    )

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:
758
    <snip>
766
    return keccak256(
767
        rlp.encode(
768
            (
769
                tx.nonce,
770
                tx.gas_price,
771
                tx.gas,
772
                tx.to,
773
                tx.value,
774
                tx.data,
775
                chain_id,
776
                Uint(0),
777
                Uint(0),
778
            )
779
        )
780
    )

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:
784
    <snip>
792
    return keccak256(
793
        b"\x01"
794
        + rlp.encode(
795
            (
796
                tx.chain_id,
797
                tx.nonce,
798
                tx.gas_price,
799
                tx.gas,
800
                tx.to,
801
                tx.value,
802
                tx.data,
803
                tx.access_list,
804
            )
805
        )
806
    )

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:
810
    <snip>
818
    return keccak256(
819
        b"\x02"
820
        + rlp.encode(
821
            (
822
                tx.chain_id,
823
                tx.nonce,
824
                tx.max_priority_fee_per_gas,
825
                tx.max_fee_per_gas,
826
                tx.gas,
827
                tx.to,
828
                tx.value,
829
                tx.data,
830
                tx.access_list,
831
            )
832
        )
833
    )

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:
837
    <snip>
845
    return keccak256(
846
        b"\x03"
847
        + rlp.encode(
848
            (
849
                tx.chain_id,
850
                tx.nonce,
851
                tx.max_priority_fee_per_gas,
852
                tx.max_fee_per_gas,
853
                tx.gas,
854
                tx.to,
855
                tx.value,
856
                tx.data,
857
                tx.access_list,
858
                tx.max_fee_per_blob_gas,
859
                tx.blob_versioned_hashes,
860
            )
861
        )
862
    )

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:
866
    <snip>
874
    return keccak256(
875
        b"\x04"
876
        + rlp.encode(
877
            (
878
                tx.chain_id,
879
                tx.nonce,
880
                tx.max_priority_fee_per_gas,
881
                tx.max_fee_per_gas,
882
                tx.gas,
883
                tx.to,
884
                tx.value,
885
                tx.data,
886
                tx.access_list,
887
                tx.authorizations,
888
            )
889
        )
890
    )

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:
894
    <snip>
902
    assert isinstance(tx, (LegacyTransaction, Bytes))
903
    if isinstance(tx, LegacyTransaction):
904
        return keccak256(rlp.encode(tx))
905
    else:
906
        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]:
912
    <snip>
917
    return isinstance(
918
        tx,
919
        AccessListCapableTransaction,
920
    )