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

LegacyTransaction

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

32
@final
33
@slotted_freezable
34
@dataclass
class LegacyTransaction:

nonce

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

46
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

51
    gas_price: Uint

gas

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

56
    gas: Uint

to

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

61
    to: Bytes0 | Address

value

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

67
    value: U256

data

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

72
    data: Bytes

v

The recovery id of the signature.

78
    v: U256

r

The first part of the signature.

83
    r: U256

s

The second part of the signature.

88
    s: U256

Access

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

94
@final
95
@slotted_freezable
96
@dataclass
class Access:

account

The address of the account that is accessed.

103
    account: Address

slots

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

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

114
@final
115
@slotted_freezable
116
@dataclass
class AccessListTransaction:

chain_id

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

128
    chain_id: U64

nonce

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

133
    nonce: U256

gas_price

The price of gas for this transaction.

138
    gas_price: Uint

gas

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

143
    gas: Uint

to

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

148
    to: Bytes0 | Address

value

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

154
    value: U256

data

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

159
    data: Bytes

access_list

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

165
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

171
    y_parity: U256

r

The first part of the signature.

176
    r: U256

s

The second part of the signature.

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

187
@final
188
@slotted_freezable
189
@dataclass
class FeeMarketTransaction:

chain_id

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

200
    chain_id: U64

nonce

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

205
    nonce: U256

max_priority_fee_per_gas

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

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

215
    max_fee_per_gas: Uint

gas

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

221
    gas: Uint

to

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

226
    to: Bytes0 | Address

value

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

232
    value: U256

data

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

237
    data: Bytes

access_list

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

243
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

249
    y_parity: U256

r

The first part of the signature.

254
    r: U256

s

The second part of the signature.

259
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

265
@final
266
@slotted_freezable
267
@dataclass
class BlobTransaction:

chain_id

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

278
    chain_id: U64

nonce

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

283
    nonce: U256

max_priority_fee_per_gas

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

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

293
    max_fee_per_gas: Uint

gas

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

299
    gas: Uint

to

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

304
    to: Address

value

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

310
    value: U256

data

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

315
    data: Bytes

access_list

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

321
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

332
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

338
    y_parity: U256

r

The first part of the signature.

343
    r: U256

s

The second part of the signature.

348
    s: U256

Transaction

Union type representing any valid transaction type.

354
Transaction = (
355
    LegacyTransaction
356
    | AccessListTransaction
357
    | FeeMarketTransaction
358
    | BlobTransaction
359
)

FeeMarketCapableTransaction

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

See FeeMarketTransaction for more details.

365
FeeMarketCapableTransaction = FeeMarketTransaction | BlobTransaction

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:
377
    <snip>
384
    if isinstance(tx, LegacyTransaction):
385
        return tx
386
    elif isinstance(tx, AccessListTransaction):
387
        return b"\x01" + rlp.encode(tx)
388
    elif isinstance(tx, FeeMarketTransaction):
389
        return b"\x02" + rlp.encode(tx)
390
    elif isinstance(tx, BlobTransaction):
391
        return b"\x03" + rlp.encode(tx)
392
    else:
393
        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:
397
    <snip>
404
    if isinstance(tx, Bytes):
405
        if tx[0] == 1:
406
            return rlp.decode_to(AccessListTransaction, tx[1:])
407
        elif tx[0] == 2:
408
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
409
        elif tx[0] == 3:
410
            return rlp.decode_to(BlobTransaction, tx[1:])
411
        else:
412
            raise TransactionTypeError(tx[0])
413
    else:
414
        return tx

validate_transaction

Verifies a transaction.

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

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

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

This function takes a transaction as a parameter and returns the intrinsic gas cost of the transaction after validation. It throws an InsufficientTransactionGasError exception if the transaction does not provide enough gas to cover the intrinsic cost, and a NonceOverflowError exception if the nonce is greater than 2**64 - 2. It also raises an InitCodeTooLargeError if the code size of a contract creation transaction exceeds the maximum allowed size, 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) -> Uint:
418
    <snip>
447
    from .vm.interpreter import MAX_INIT_CODE_SIZE
448
449
    intrinsic_gas = calculate_intrinsic_cost(tx)
450
    if intrinsic_gas > tx.gas:
451
        raise InsufficientTransactionGasError("Insufficient gas")
452
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
453
        raise InitCodeTooLargeError("Code size too large")
454
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
455
        raise NonceOverflowError("Nonce too high")
456
    if isinstance(tx, FeeMarketCapableTransaction):
457
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
458
            raise PriorityFeeGreaterThanMaxFeeError(
459
                "priority fee greater than max fee"
460
            )
461
462
    return intrinsic_gas

calculate_intrinsic_cost

Calculates the gas that is charged before execution is started.

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

The intrinsic cost includes:

  1. Base cost (TX_BASE)

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

  3. Cost for contract creation (if applicable)

  4. Cost for access list entries (if applicable)

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

def calculate_intrinsic_cost(tx: Transaction) -> Uint:
466
    <snip>
487
    from .vm.gas import GasCosts, init_code_cost
488
489
    num_zeros = Uint(tx.data.count(0))
490
    num_non_zeros = ulen(tx.data) - num_zeros
491
    data_cost = (
492
        num_zeros * GasCosts.TX_DATA_PER_ZERO
493
        + num_non_zeros * GasCosts.TX_DATA_PER_NON_ZERO
494
    )
495
496
    if tx.to == Bytes0(b""):
497
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
498
    else:
499
        create_cost = Uint(0)
500
501
    access_list_cost = Uint(0)
502
    if isinstance(
503
        tx, (AccessListTransaction, FeeMarketTransaction, BlobTransaction)
504
    ):
505
        for access in tx.access_list:
506
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
507
            access_list_cost += (
508
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
509
            )
510
511
    return GasCosts.TX_BASE + data_cost + create_cost + access_list_cost

chain_id

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

def chain_id(tx: Transaction) -> None | U64:
515
    <snip>
520
    if isinstance(tx, LegacyTransaction):
521
        if tx.v == 27 or tx.v == 28:
522
            return None
523
524
        if tx.v < U256(35):
525
            raise InvalidSignatureError("bad v")
526
527
        return U64((tx.v - U256(35)) >> U256(1))
528
    else:
529
        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:
533
    <snip>
546
    r, s = tx.r, tx.s
547
    if U256(0) >= r or r >= SECP256K1N:
548
        raise InvalidSignatureError("bad r")
549
    if U256(0) >= s or s > SECP256K1N // U256(2):
550
        raise InvalidSignatureError("bad s")
551
552
    if isinstance(tx, LegacyTransaction):
553
        v = tx.v
554
        if v == 27 or v == 28:
555
            public_key = secp256k1_recover(
556
                r, s, v - U256(27), signing_hash_pre155(tx)
557
            )
558
        else:
559
            assert v >= U256(35), "call chain_id before recover_sender"
560
            tx_chain_id = U64((v - U256(35)) >> U256(1))
561
            v = (v - U256(35)) & U256(1)
562
            public_key = secp256k1_recover(
563
                r,
564
                s,
565
                v,
566
                signing_hash_155(tx, tx_chain_id),
567
            )
568
    elif isinstance(tx, AccessListTransaction):
569
        if tx.y_parity not in (U256(0), U256(1)):
570
            raise InvalidSignatureError("bad y_parity")
571
        public_key = secp256k1_recover(
572
            r, s, tx.y_parity, signing_hash_2930(tx)
573
        )
574
    elif isinstance(tx, FeeMarketTransaction):
575
        if tx.y_parity not in (U256(0), U256(1)):
576
            raise InvalidSignatureError("bad y_parity")
577
        public_key = secp256k1_recover(
578
            r, s, tx.y_parity, signing_hash_1559(tx)
579
        )
580
    elif isinstance(tx, BlobTransaction):
581
        if tx.y_parity not in (U256(0), U256(1)):
582
            raise InvalidSignatureError("bad y_parity")
583
        public_key = secp256k1_recover(
584
            r, s, tx.y_parity, signing_hash_4844(tx)
585
        )
586
587
    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:
591
    <snip>
600
    return keccak256(
601
        rlp.encode(
602
            (
603
                tx.nonce,
604
                tx.gas_price,
605
                tx.gas,
606
                tx.to,
607
                tx.value,
608
                tx.data,
609
            )
610
        )
611
    )

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:
615
    <snip>
623
    return keccak256(
624
        rlp.encode(
625
            (
626
                tx.nonce,
627
                tx.gas_price,
628
                tx.gas,
629
                tx.to,
630
                tx.value,
631
                tx.data,
632
                chain_id,
633
                Uint(0),
634
                Uint(0),
635
            )
636
        )
637
    )

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:
641
    <snip>
649
    return keccak256(
650
        b"\x01"
651
        + rlp.encode(
652
            (
653
                tx.chain_id,
654
                tx.nonce,
655
                tx.gas_price,
656
                tx.gas,
657
                tx.to,
658
                tx.value,
659
                tx.data,
660
                tx.access_list,
661
            )
662
        )
663
    )

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:
667
    <snip>
675
    return keccak256(
676
        b"\x02"
677
        + rlp.encode(
678
            (
679
                tx.chain_id,
680
                tx.nonce,
681
                tx.max_priority_fee_per_gas,
682
                tx.max_fee_per_gas,
683
                tx.gas,
684
                tx.to,
685
                tx.value,
686
                tx.data,
687
                tx.access_list,
688
            )
689
        )
690
    )

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:
694
    <snip>
702
    return keccak256(
703
        b"\x03"
704
        + rlp.encode(
705
            (
706
                tx.chain_id,
707
                tx.nonce,
708
                tx.max_priority_fee_per_gas,
709
                tx.max_fee_per_gas,
710
                tx.gas,
711
                tx.to,
712
                tx.value,
713
                tx.data,
714
                tx.access_list,
715
                tx.max_fee_per_blob_gas,
716
                tx.blob_versioned_hashes,
717
            )
718
        )
719
    )

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:
723
    <snip>
731
    assert isinstance(tx, (LegacyTransaction, Bytes))
732
    if isinstance(tx, LegacyTransaction):
733
        return keccak256(rlp.encode(tx))
734
    else:
735
        return keccak256(tx)