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.

IntrinsicGasCost

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

regular: ethereum.base_types.Uint Regular execution gas (calldata, base cost, access list, etc.) state: ethereum.base_types.Uint State growth gas (account creation, storage set, authorization). calldata_floor: ethereum.base_types.Uint Minimum gas cost based on calldata size per [EIP-7623].

31
@dataclass
class IntrinsicGasCost:

regular

44
    regular: Uint

state

45
    state: Uint

calldata_floor

46
    calldata_floor: Uint

TX_MAX_GAS_LIMIT

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

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

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

68
@slotted_freezable
69
@dataclass
class LegacyTransaction:

nonce

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

82
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

87
    gas_price: Uint

gas

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

92
    gas: Uint

to

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

97
    to: Bytes0 | Address

value

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

103
    value: U256

data

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

108
    data: Bytes

v

The recovery id of the signature.

114
    v: U256

r

The first part of the signature.

119
    r: U256

s

The second part of the signature.

124
    s: U256

Access

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

130
@slotted_freezable
131
@dataclass
class Access:

account

The address of the account that is accessed.

138
    account: Address

slots

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

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

149
@slotted_freezable
150
@dataclass
class AccessListTransaction:

chain_id

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

162
    chain_id: U64

nonce

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

167
    nonce: U256

gas_price

The price of gas for this transaction.

172
    gas_price: Uint

gas

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

177
    gas: Uint

to

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

182
    to: Bytes0 | Address

value

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

188
    value: U256

data

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

193
    data: Bytes

access_list

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

199
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

205
    y_parity: U256

r

The first part of the signature.

210
    r: U256

s

The second part of the signature.

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

221
@slotted_freezable
222
@dataclass
class FeeMarketTransaction:

chain_id

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

233
    chain_id: U64

nonce

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

238
    nonce: U256

max_priority_fee_per_gas

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

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

248
    max_fee_per_gas: Uint

gas

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

254
    gas: Uint

to

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

259
    to: Bytes0 | Address

value

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

265
    value: U256

data

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

270
    data: Bytes

access_list

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

276
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

282
    y_parity: U256

r

The first part of the signature.

287
    r: U256

s

The second part of the signature.

292
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

298
@slotted_freezable
299
@dataclass
class BlobTransaction:

chain_id

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

310
    chain_id: U64

nonce

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

315
    nonce: U256

max_priority_fee_per_gas

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

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

325
    max_fee_per_gas: Uint

gas

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

331
    gas: Uint

to

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

336
    to: Address

value

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

342
    value: U256

data

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

347
    data: Bytes

access_list

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

353
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

364
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

370
    y_parity: U256

r

The first part of the signature.

375
    r: U256

s

The second part of the signature.

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

386
@slotted_freezable
387
@dataclass
class SetCodeTransaction:

chain_id

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

398
    chain_id: U64

nonce

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

403
    nonce: U64

max_priority_fee_per_gas

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

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

413
    max_fee_per_gas: Uint

gas

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

419
    gas: Uint

to

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

424
    to: Address

value

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

430
    value: U256

data

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

435
    data: Bytes

access_list

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

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

447
    authorizations: Tuple[Authorization, ...]

y_parity

The recovery id of the signature.

453
    y_parity: U256

r

The first part of the signature.

458
    r: U256

s

The second part of the signature.

463
    s: U256

Transaction

Union type representing any valid transaction type.

469
Transaction = (
470
    LegacyTransaction
471
    | AccessListTransaction
472
    | FeeMarketTransaction
473
    | BlobTransaction
474
    | SetCodeTransaction
475
)

AccessListCapableTransaction

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

See has_access_list and Access for more details.

481
AccessListCapableTransaction = (
482
    AccessListTransaction
483
    | FeeMarketTransaction
484
    | BlobTransaction
485
    | 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:
499
    """
500
    Encode a transaction into its RLP or typed transaction format.
501
    Needed because non-legacy transactions aren't RLP.
502
503
    Legacy transactions are returned as-is, while other transaction types
504
    are prefixed with their type identifier and RLP encoded.
505
    """
506
    if isinstance(tx, LegacyTransaction):
507
        return tx
508
    elif isinstance(tx, AccessListTransaction):
509
        return b"\x01" + rlp.encode(tx)
510
    elif isinstance(tx, FeeMarketTransaction):
511
        return b"\x02" + rlp.encode(tx)
512
    elif isinstance(tx, BlobTransaction):
513
        return b"\x03" + rlp.encode(tx)
514
    elif isinstance(tx, SetCodeTransaction):
515
        return b"\x04" + rlp.encode(tx)
516
    else:
517
        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:
521
    """
522
    Decode a transaction from its RLP or typed transaction format.
523
    Needed because non-legacy transactions aren't RLP.
524
491
    Legacy transactions are returned as-is, while other transaction types
492
    are decoded based on their type identifier prefix.
525
    Accept a ``LegacyTransaction`` object (returned as-is) or raw
526
    bytes.
527
528
    EIP-2718 states that the first byte distinguishes the format:
529
    [0x00, 0x7f] is a typed transaction, [0xc0, 0xfe] is a legacy
530
    transaction (RLP list prefix).
531
    """
532
    if isinstance(tx, Bytes):
533
        if tx[0] == 1:
534
            return rlp.decode_to(AccessListTransaction, tx[1:])
535
        elif tx[0] == 2:
536
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
537
        elif tx[0] == 3:
538
            return rlp.decode_to(BlobTransaction, tx[1:])
539
        elif tx[0] == 4:
540
            return rlp.decode_to(SetCodeTransaction, tx[1:])
503
        else:
504
            raise TransactionTypeError(tx[0])
541
        elif tx[0] >= 0xC0:
542
            assert tx[0] <= 0xFE
543
            return rlp.decode_to(LegacyTransaction, tx)
544
        else:
545
            raise TransactionTypeError(tx[0])
546
    else:
547
        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 intrinsicThis function takes a transaction and gas_limit as parameters and gas cost and the minimum calldata gas cost for the transaction afterreturns the intrinsic gas costs for the transaction after validation. validation. It throws an It throws an InsufficientTransactionGasError exception if exception if the the transaction does not provide enough gas to cover the intrinsic cost,transaction does not provide enough gas to cover the intrinsic cost, and a NonceOverflowError exception if the nonce is greater than exception if the nonce overflows. 2**64 - 2. It also raises an It also raises an InitCodeTooLargeError if the code size of if the code a contract creation transaction exceeds the maximum allowed size.size of a contract creation transaction exceeds the maximum allowed size.

def validate_transaction(tx: Transaction) -> Tuple[Uint, Uint]IntrinsicGasCost:
551
    """
552
    Verifies a transaction.
553
554
    The gas in a transaction gets used to pay for the intrinsic cost of
555
    operations, therefore if there is insufficient gas then it would not
556
    be possible to execute a transaction and it will be declared invalid.
557
558
    Additionally, the nonce of a transaction must not equal or exceed the
559
    limit defined in [EIP-2681].
560
    In practice, defining the limit as ``2**64-1`` has no impact because
561
    sending ``2**64-1`` transactions is improbable. It's not strictly
562
    impossible though, ``2**64-1`` transactions is the entire capacity of the
563
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
564
565
    Also, the code size of a contract creation transaction must be within
566
    limits of the protocol.
567
527
    This function takes a transaction as a parameter and returns the intrinsic
528
    gas cost and the minimum calldata gas cost for the transaction after
529
    validation. It throws an `InsufficientTransactionGasError` exception if
530
    the transaction does not provide enough gas to cover the intrinsic cost,
531
    and a `NonceOverflowError` exception if the nonce is greater than
532
    `2**64 - 2`. It also raises an `InitCodeTooLargeError` if the code size of
533
    a contract creation transaction exceeds the maximum allowed size.
568
    This function takes a transaction and gas_limit as parameters and
569
    returns the intrinsic gas costs for the transaction after validation.
570
    It throws an `InsufficientTransactionGasError` exception if the
571
    transaction does not provide enough gas to cover the intrinsic cost,
572
    and a `NonceOverflowError` exception if the nonce overflows.
573
    It also raises an `InitCodeTooLargeError` if the code
574
    size of a contract creation transaction exceeds the maximum allowed
575
    size.
576
577
    [EIP-2681]: https://eips.ethereum.org/EIPS/eip-2681
578
    [EIP-7623]: https://eips.ethereum.org/EIPS/eip-7623
579
    """
580
    from .vm.interpreter import MAX_INIT_CODE_SIZE
581
540
    intrinsic_gas, calldata_floor_gas_cost = calculate_intrinsic_cost(tx)
541
    if max(intrinsic_gas, calldata_floor_gas_cost) > tx.gas:
582
    intrinsic = calculate_intrinsic_cost(tx)
583
    intrinsic_gas = intrinsic.regular + intrinsic.state
584
    if max(intrinsic_gas, intrinsic.calldata_floor) > tx.gas:
585
        raise InsufficientTransactionGasError("Insufficient gas")
586
    if max(intrinsic.regular, intrinsic.calldata_floor) > TX_MAX_GAS_LIMIT:
587
        raise InsufficientTransactionGasError(
588
            "Intrinsic regular gas or calldata floor exceeds TX_MAX_GAS_LIMIT"
589
        )
590
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
591
        raise NonceOverflowError("Nonce too high")
592
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
593
        raise InitCodeTooLargeError("Code size too large")
547
    if tx.gas > TX_MAX_GAS_LIMIT:
548
        raise TransactionGasLimitExceededError("Gas limit too high")
594
550
    return intrinsic_gas, calldata_floor_gas_cost
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 intrinsicThis function takes a transaction and gas_limit as parameters and gas cost of the transaction and the minimum gas cost used by thereturns the intrinsic regular gas cost, intrinsic state gas cost, and the transaction based on the calldata size.minimum gas cost used by the transaction based on the calldata size.

def calculate_intrinsic_cost(tx: Transaction) -> Tuple[Uint, Uint]IntrinsicGasCost:
599
    """
600
    Calculates the gas that is charged before execution is started.
601
602
    The intrinsic cost of the transaction is charged before execution has
603
    begun. Functions/operations in the EVM cost money to execute so this
604
    intrinsic cost is for the operations that need to be paid for as part of
605
    the transaction. Data transfer, for example, is part of this intrinsic
606
    cost. It costs ether to send data over the wire and that ether is
607
    accounted for in the intrinsic cost calculated in this function. This
608
    intrinsic cost must be calculated and paid for before execution in order
609
    for all operations to be implemented.
610
611
    The intrinsic cost includes:
612
    1. Base cost (`TX_BASE`)
613
    2. Cost for data (zero and non-zero bytes)
614
    3. Cost for contract creation (if applicable)
615
    4. Cost for access list entries (if applicable)
616
    5. Cost for authorizations (if applicable)
617
618
574
    This function takes a transaction as a parameter and returns the intrinsic
575
    gas cost of the transaction and the minimum gas cost used by the
576
    transaction based on the calldata size.
619
    This function takes a transaction and gas_limit as parameters and
620
    returns the intrinsic regular gas cost, intrinsic state gas cost, and the
621
    minimum gas cost used by the transaction based on the calldata size.
622
    """
578
    from .vm.gas import GasCosts, init_code_cost
623
    from .vm.gas import (
624
        COST_PER_STATE_BYTE,
625
        PER_AUTH_BASE_COST,
626
        REGULAR_GAS_CREATE,
627
        STATE_BYTES_PER_AUTH_BASE,
628
        STATE_BYTES_PER_NEW_ACCOUNT,
629
        GasCosts,
630
        init_code_cost,
631
    )
632
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
    )
633
    tokens_in_calldata = count_tokens_in_data(tx.data)
634
635
    data_cost = tokens_in_calldata * GasCosts.TX_DATA_TOKEN_STANDARD
636
637
    create_regular_gas = Uint(0)
638
    create_state_gas = Uint(0)
639
    if tx.to == Bytes0(b""):
592
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
593
    else:
594
        create_cost = Uint(0)
640
        create_state_gas = STATE_BYTES_PER_NEW_ACCOUNT * COST_PER_STATE_BYTE
641
        create_regular_gas = REGULAR_GAS_CREATE + init_code_cost(ulen(tx.data))
642
596
    access_list_cost = Uint(0)
643
    access_list_gas = Uint(0)
644
    tokens_in_access_list = Uint(0)
645
    if has_access_list(tx):
646
        for access in tx.access_list:
599
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
600
            access_list_cost += (
647
            access_list_gas += GasCosts.TX_ACCESS_LIST_ADDRESS
648
            access_list_gas += (
649
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
650
            )
651
            tokens_in_access_list += ACCESS_LIST_ADDRESS_FLOOR_TOKENS
652
            tokens_in_access_list += (
653
                ulen(access.slots) * ACCESS_LIST_STORAGE_KEY_FLOOR_TOKENS
654
            )
655
604
    auth_cost = Uint(0)
656
    # Data token floor cost for access list bytes.
657
    access_list_gas += tokens_in_access_list * GasCosts.TX_DATA_TOKEN_FLOOR
658
659
    auth_regular_gas = Uint(0)
660
    auth_state_gas = Uint(0)
661
    if isinstance(tx, SetCodeTransaction):
606
        auth_cost += Uint(
607
            GasCosts.AUTH_PER_EMPTY_ACCOUNT * len(tx.authorizations)
608
        )
662
        auth_regular_gas = PER_AUTH_BASE_COST * ulen(tx.authorizations)
663
        auth_state_gas = (
664
            (STATE_BYTES_PER_NEW_ACCOUNT + STATE_BYTES_PER_AUTH_BASE)
665
            * COST_PER_STATE_BYTE
666
            * ulen(tx.authorizations)
667
        )
668
610
    return (
611
        Uint(
612
            GasCosts.TX_BASE
613
            + data_cost
614
            + create_cost
615
            + access_list_cost
616
            + auth_cost
617
        ),
618
        calldata_floor_gas_cost,
619
    )
669
    # EIP-7976 floor tokens: all calldata bytes count uniformly.
670
    floor_tokens_in_calldata = ulen(tx.data) * GasCosts.TX_DATA_TOKEN_STANDARD
671
672
    # Total floor tokens.
673
    total_floor_tokens = floor_tokens_in_calldata + tokens_in_access_list
674
675
    # Floor gas cost (EIP-7623: minimum gas for data-heavy transactions).
676
    data_floor_gas_cost = (
677
        total_floor_tokens * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
678
    )
679
680
    intrinsic_regular_gas = (
681
        GasCosts.TX_BASE
682
        + data_cost
683
        + create_regular_gas
684
        + access_list_gas
685
        + auth_regular_gas
686
    )
687
688
    intrinsic_state_gas = create_state_gas + auth_state_gas
689
690
    return IntrinsicGasCost(
691
        regular=intrinsic_regular_gas,
692
        state=intrinsic_state_gas,
693
        calldata_floor=data_floor_gas_cost,
694
    )

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:
698
    """
699
    Count the data tokens in arbitrary input bytes.
700
701
    Zero bytes count as 1 token; non-zero bytes count as 4 tokens.
702
    """
703
    num_zeros = Uint(data.count(0))
704
    num_non_zeros = ulen(data) - num_zeros
705
706
    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:
710
    """
711
    Extracts the sender address from a transaction.
712
713
    The v, r, and s values are the three parts that make up the signature
714
    of a transaction. In order to recover the sender of a transaction the two
715
    components needed are the signature (``v``, ``r``, and ``s``) and the
716
    signing hash of the transaction. The sender's public key can be obtained
717
    with these two values and therefore the sender address can be retrieved.
718
719
    This function takes chain_id and a transaction as parameters and returns
720
    the address of the sender of the transaction. It raises an
721
    `InvalidSignatureError` if the signature values (r, s, v) are invalid.
722
    """
723
    r, s = tx.r, tx.s
724
    if U256(0) >= r or r >= SECP256K1N:
725
        raise InvalidSignatureError("bad r")
726
    if U256(0) >= s or s > SECP256K1N // U256(2):
727
        raise InvalidSignatureError("bad s")
728
729
    if isinstance(tx, LegacyTransaction):
730
        v = tx.v
731
        if v == 27 or v == 28:
732
            public_key = secp256k1_recover(
733
                r, s, v - U256(27), signing_hash_pre155(tx)
734
            )
735
        else:
736
            chain_id_x2 = U256(chain_id) * U256(2)
737
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
738
                raise InvalidSignatureError("bad v")
739
            public_key = secp256k1_recover(
740
                r,
741
                s,
742
                v - U256(35) - chain_id_x2,
743
                signing_hash_155(tx, chain_id),
744
            )
745
    elif isinstance(tx, AccessListTransaction):
746
        if tx.y_parity not in (U256(0), U256(1)):
747
            raise InvalidSignatureError("bad y_parity")
748
        public_key = secp256k1_recover(
749
            r, s, tx.y_parity, signing_hash_2930(tx)
750
        )
751
    elif isinstance(tx, FeeMarketTransaction):
752
        if tx.y_parity not in (U256(0), U256(1)):
753
            raise InvalidSignatureError("bad y_parity")
754
        public_key = secp256k1_recover(
755
            r, s, tx.y_parity, signing_hash_1559(tx)
756
        )
757
    elif isinstance(tx, BlobTransaction):
758
        if tx.y_parity not in (U256(0), U256(1)):
759
            raise InvalidSignatureError("bad y_parity")
760
        public_key = secp256k1_recover(
761
            r, s, tx.y_parity, signing_hash_4844(tx)
762
        )
763
    elif isinstance(tx, SetCodeTransaction):
764
        if tx.y_parity not in (U256(0), U256(1)):
765
            raise InvalidSignatureError("bad y_parity")
766
        public_key = secp256k1_recover(
767
            r, s, tx.y_parity, signing_hash_7702(tx)
768
        )
769
770
    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:
774
    """
775
    Compute the hash of a transaction used in a legacy (pre [EIP-155])
776
    signature.
777
778
    This function takes a legacy transaction as a parameter and returns the
779
    signing hash of the transaction.
780
781
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
782
    """
783
    return keccak256(
784
        rlp.encode(
785
            (
786
                tx.nonce,
787
                tx.gas_price,
788
                tx.gas,
789
                tx.to,
790
                tx.value,
791
                tx.data,
792
            )
793
        )
794
    )

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:
798
    """
799
    Compute the hash of a transaction used in a [EIP-155] signature.
800
801
    This function takes a legacy transaction and a chain ID as parameters
802
    and returns the hash of the transaction used in an [EIP-155] signature.
803
804
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
805
    """
806
    return keccak256(
807
        rlp.encode(
808
            (
809
                tx.nonce,
810
                tx.gas_price,
811
                tx.gas,
812
                tx.to,
813
                tx.value,
814
                tx.data,
815
                chain_id,
816
                Uint(0),
817
                Uint(0),
818
            )
819
        )
820
    )

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:
824
    """
825
    Compute the hash of a transaction used in a [EIP-2930] signature.
826
827
    This function takes an access list transaction as a parameter
828
    and returns the hash of the transaction used in an [EIP-2930] signature.
829
830
    [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
831
    """
832
    return keccak256(
833
        b"\x01"
834
        + rlp.encode(
835
            (
836
                tx.chain_id,
837
                tx.nonce,
838
                tx.gas_price,
839
                tx.gas,
840
                tx.to,
841
                tx.value,
842
                tx.data,
843
                tx.access_list,
844
            )
845
        )
846
    )

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:
850
    """
851
    Compute the hash of a transaction used in an [EIP-1559] signature.
852
853
    This function takes a fee market transaction as a parameter
854
    and returns the hash of the transaction used in an [EIP-1559] signature.
855
856
    [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
857
    """
858
    return keccak256(
859
        b"\x02"
860
        + rlp.encode(
861
            (
862
                tx.chain_id,
863
                tx.nonce,
864
                tx.max_priority_fee_per_gas,
865
                tx.max_fee_per_gas,
866
                tx.gas,
867
                tx.to,
868
                tx.value,
869
                tx.data,
870
                tx.access_list,
871
            )
872
        )
873
    )

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:
877
    """
878
    Compute the hash of a transaction used in an [EIP-4844] signature.
879
880
    This function takes a transaction as a parameter and returns the
881
    signing hash of the transaction used in an [EIP-4844] signature.
882
883
    [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
884
    """
885
    return keccak256(
886
        b"\x03"
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.max_fee_per_blob_gas,
899
                tx.blob_versioned_hashes,
900
            )
901
        )
902
    )

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:
906
    """
907
    Compute the hash of a transaction used in a [EIP-7702] signature.
908
909
    This function takes a transaction as a parameter and returns the
910
    signing hash of the transaction used in a [EIP-7702] signature.
911
912
    [EIP-7702]: https://eips.ethereum.org/EIPS/eip-7702
913
    """
914
    return keccak256(
915
        b"\x04"
916
        + rlp.encode(
917
            (
918
                tx.chain_id,
919
                tx.nonce,
920
                tx.max_priority_fee_per_gas,
921
                tx.max_fee_per_gas,
922
                tx.gas,
923
                tx.to,
924
                tx.value,
925
                tx.data,
926
                tx.access_list,
927
                tx.authorizations,
928
            )
929
        )
930
    )

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:
934
    """
935
    Compute the hash of a transaction.
936
937
    This function takes a transaction as a parameter and returns the
938
    keccak256 hash of the transaction. It can handle both legacy transactions
939
    and typed transactions (`AccessListTransaction`, `FeeMarketTransaction`,
940
    etc.).
941
    """
942
    assert isinstance(tx, (LegacyTransaction, Bytes))
943
    if isinstance(tx, LegacyTransaction):
944
        return keccak256(rlp.encode(tx))
945
    else:
946
        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]:
952
    """
953
    Return whether the transaction has an [EIP-2930]-style access list.
954
955
    [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
956
    """
957
    return isinstance(
958
        tx,
959
        AccessListCapableTransaction,
960
    )