ethereum.forks.shanghai.transactionsethereum.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, and , EIP-2930, and EIP-4844.

28
@final
29
@slotted_freezable
30
@dataclass
class LegacyTransaction:

nonce

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

42
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

47
    gas_price: Uint

gas

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

52
    gas: Uint

to

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

57
    to: Bytes0 | Address

value

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

63
    value: U256

data

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

68
    data: Bytes

v

The recovery id of the signature.

74
    v: U256

r

The first part of the signature.

79
    r: U256

s

The second part of the signature.

84
    s: U256

Access

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

90
@final
91
@slotted_freezable
92
@dataclass
class Access:

account

The address of the account that is accessed.

99
    account: Address

slots

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

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

110
@final
111
@slotted_freezable
112
@dataclass
class AccessListTransaction:

chain_id

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

124
    chain_id: U64

nonce

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

129
    nonce: U256

gas_price

The price of gas for this transaction.

134
    gas_price: Uint

gas

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

139
    gas: Uint

to

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

144
    to: Bytes0 | Address

value

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

150
    value: U256

data

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

155
    data: Bytes

access_list

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

161
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

167
    y_parity: U256

r

The first part of the signature.

172
    r: U256

s

The second part of the signature.

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

183
@final
184
@slotted_freezable
185
@dataclass
class FeeMarketTransaction:

chain_id

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

196
    chain_id: U64

nonce

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

201
    nonce: U256

max_priority_fee_per_gas

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

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

211
    max_fee_per_gas: Uint

gas

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

217
    gas: Uint

to

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

222
    to: Bytes0 | Address

value

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

228
    value: U256

data

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

233
    data: Bytes

access_list

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

239
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

245
    y_parity: U256

r

The first part of the signature.

250
    r: U256

s

The second part of the signature.

255
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

261
@final
262
@slotted_freezable
263
@dataclass
class BlobTransaction:

chain_id

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

274
    chain_id: U64

nonce

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

279
    nonce: U256

max_priority_fee_per_gas

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

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

289
    max_fee_per_gas: Uint

gas

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

295
    gas: Uint

to

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

300
    to: Address

value

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

306
    value: U256

data

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

311
    data: Bytes

access_list

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

317
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

328
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

334
    y_parity: U256

r

The first part of the signature.

339
    r: U256

s

The second part of the signature.

344
    s: U256

Transaction

Union type representing any valid transaction type.

258
Transaction = LegacyTransaction | AccessListTransaction | FeeMarketTransaction
350
Transaction = (
351
    LegacyTransaction
352
    | AccessListTransaction
353
    | FeeMarketTransaction
354
    | BlobTransaction
355
)

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:
362
    <snip>
369
    if isinstance(tx, LegacyTransaction):
370
        return tx
371
    elif isinstance(tx, AccessListTransaction):
372
        return b"\x01" + rlp.encode(tx)
373
    elif isinstance(tx, FeeMarketTransaction):
374
        return b"\x02" + rlp.encode(tx)
278
    else:
279
        raise Exception(f"Unable to encode transaction of type {type(tx)}")
375
    elif isinstance(tx, BlobTransaction):
376
        return b"\x03" + rlp.encode(tx)
377
    else:
378
        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:
382
    <snip>
389
    if isinstance(tx, Bytes):
390
        if tx[0] == 1:
391
            return rlp.decode_to(AccessListTransaction, tx[1:])
392
        elif tx[0] == 2:
393
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
295
        else:
296
            raise TransactionTypeError(tx[0])
394
        elif tx[0] == 3:
395
            return rlp.decode_to(BlobTransaction, tx[1:])
396
        else:
397
            raise TransactionTypeError(tx[0])
398
    else:
399
        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.

def validate_transaction(tx: Transaction) -> Uint:
403
    <snip>
430
    from .vm.interpreter import MAX_INIT_CODE_SIZE
431
432
    intrinsic_gas = calculate_intrinsic_cost(tx)
433
    if intrinsic_gas > tx.gas:
434
        raise InsufficientTransactionGasError("Insufficient gas")
435
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
436
        raise NonceOverflowError("Nonce too high")
437
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
438
        raise InitCodeTooLargeError("Code size too large")
439
440
    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:
444
    <snip>
465
    from .vm.gas import GasCosts, init_code_cost
466
467
    num_zeros = Uint(tx.data.count(0))
468
    num_non_zeros = ulen(tx.data) - num_zeros
469
    data_cost = (
470
        num_zeros * GasCosts.TX_DATA_PER_ZERO
471
        + num_non_zeros * GasCosts.TX_DATA_PER_NON_ZERO
472
    )
473
474
    if tx.to == Bytes0(b""):
475
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
476
    else:
477
        create_cost = Uint(0)
478
479
    access_list_cost = Uint(0)
379
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
480
    if isinstance(
481
        tx, (AccessListTransaction, FeeMarketTransaction, BlobTransaction)
482
    ):
483
        for access in tx.access_list:
484
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
485
            access_list_cost += (
486
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
487
            )
488
489
    return GasCosts.TX_BASE + data_cost + create_cost + access_list_cost

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:
493
    <snip>
506
    r, s = tx.r, tx.s
507
    if U256(0) >= r or r >= SECP256K1N:
508
        raise InvalidSignatureError("bad r")
509
    if U256(0) >= s or s > SECP256K1N // U256(2):
510
        raise InvalidSignatureError("bad s")
511
512
    if isinstance(tx, LegacyTransaction):
513
        v = tx.v
514
        if v == 27 or v == 28:
515
            public_key = secp256k1_recover(
516
                r, s, v - U256(27), signing_hash_pre155(tx)
517
            )
518
        else:
519
            chain_id_x2 = U256(chain_id) * U256(2)
520
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
521
                raise InvalidSignatureError("bad v")
522
            public_key = secp256k1_recover(
523
                r,
524
                s,
525
                v - U256(35) - chain_id_x2,
526
                signing_hash_155(tx, chain_id),
527
            )
528
    elif isinstance(tx, AccessListTransaction):
529
        if tx.y_parity not in (U256(0), U256(1)):
530
            raise InvalidSignatureError("bad y_parity")
531
        public_key = secp256k1_recover(
532
            r, s, tx.y_parity, signing_hash_2930(tx)
533
        )
534
    elif isinstance(tx, FeeMarketTransaction):
535
        if tx.y_parity not in (U256(0), U256(1)):
536
            raise InvalidSignatureError("bad y_parity")
537
        public_key = secp256k1_recover(
538
            r, s, tx.y_parity, signing_hash_1559(tx)
436
        )
539
        )
540
    elif isinstance(tx, BlobTransaction):
541
        if tx.y_parity not in (U256(0), U256(1)):
542
            raise InvalidSignatureError("bad y_parity")
543
        public_key = secp256k1_recover(
544
            r, s, tx.y_parity, signing_hash_4844(tx)
545
        )
546
547
    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:
551
    <snip>
560
    return keccak256(
561
        rlp.encode(
562
            (
563
                tx.nonce,
564
                tx.gas_price,
565
                tx.gas,
566
                tx.to,
567
                tx.value,
568
                tx.data,
569
            )
570
        )
571
    )

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:
575
    <snip>
583
    return keccak256(
584
        rlp.encode(
585
            (
586
                tx.nonce,
587
                tx.gas_price,
588
                tx.gas,
589
                tx.to,
590
                tx.value,
591
                tx.data,
592
                chain_id,
593
                Uint(0),
594
                Uint(0),
595
            )
596
        )
597
    )

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:
601
    <snip>
609
    return keccak256(
610
        b"\x01"
611
        + rlp.encode(
612
            (
613
                tx.chain_id,
614
                tx.nonce,
615
                tx.gas_price,
616
                tx.gas,
617
                tx.to,
618
                tx.value,
619
                tx.data,
620
                tx.access_list,
621
            )
622
        )
623
    )

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:
627
    <snip>
635
    return keccak256(
636
        b"\x02"
637
        + rlp.encode(
638
            (
639
                tx.chain_id,
640
                tx.nonce,
641
                tx.max_priority_fee_per_gas,
642
                tx.max_fee_per_gas,
643
                tx.gas,
644
                tx.to,
645
                tx.value,
646
                tx.data,
647
                tx.access_list,
648
            )
649
        )
650
    )

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:
654
    <snip>
662
    return keccak256(
663
        b"\x03"
664
        + rlp.encode(
665
            (
666
                tx.chain_id,
667
                tx.nonce,
668
                tx.max_priority_fee_per_gas,
669
                tx.max_fee_per_gas,
670
                tx.gas,
671
                tx.to,
672
                tx.value,
673
                tx.data,
674
                tx.access_list,
675
                tx.max_fee_per_blob_gas,
676
                tx.blob_versioned_hashes,
677
            )
678
        )
679
    )

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:
683
    <snip>
691
    assert isinstance(tx, (LegacyTransaction, Bytes))
692
    if isinstance(tx, LegacyTransaction):
693
        return keccak256(rlp.encode(tx))
694
    else:
695
        return keccak256(tx)