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.

28
@slotted_freezable
29
@dataclass
class LegacyTransaction:

nonce

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

41
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

46
    gas_price: Uint

gas

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

51
    gas: Uint

to

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

56
    to: Bytes0 | Address

value

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

62
    value: U256

data

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

67
    data: Bytes

v

The recovery id of the signature.

73
    v: U256

r

The first part of the signature.

78
    r: U256

s

The second part of the signature.

83
    s: U256

Access

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

89
@slotted_freezable
90
@dataclass
class Access:

account

The address of the account that is accessed.

97
    account: Address

slots

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

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

108
@slotted_freezable
109
@dataclass
class AccessListTransaction:

chain_id

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

121
    chain_id: U64

nonce

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

126
    nonce: U256

gas_price

The price of gas for this transaction.

131
    gas_price: Uint

gas

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

136
    gas: Uint

to

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

141
    to: Bytes0 | Address

value

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

147
    value: U256

data

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

152
    data: Bytes

access_list

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

158
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

164
    y_parity: U256

r

The first part of the signature.

169
    r: U256

s

The second part of the signature.

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

180
@slotted_freezable
181
@dataclass
class FeeMarketTransaction:

chain_id

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

192
    chain_id: U64

nonce

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

197
    nonce: U256

max_priority_fee_per_gas

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

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

207
    max_fee_per_gas: Uint

gas

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

213
    gas: Uint

to

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

218
    to: Bytes0 | Address

value

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

224
    value: U256

data

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

229
    data: Bytes

access_list

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

235
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

241
    y_parity: U256

r

The first part of the signature.

246
    r: U256

s

The second part of the signature.

251
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

257
@slotted_freezable
258
@dataclass
class BlobTransaction:

chain_id

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

269
    chain_id: U64

nonce

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

274
    nonce: U256

max_priority_fee_per_gas

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

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

284
    max_fee_per_gas: Uint

gas

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

290
    gas: Uint

to

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

295
    to: Address

value

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

301
    value: U256

data

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

306
    data: Bytes

access_list

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

312
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

323
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

329
    y_parity: U256

r

The first part of the signature.

334
    r: U256

s

The second part of the signature.

339
    s: U256

Transaction

Union type representing any valid transaction type.

345
Transaction = (
346
    LegacyTransaction
347
    | AccessListTransaction
348
    | FeeMarketTransaction
349
    | BlobTransaction
350
)

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:
357
    """
358
    Encode a transaction into its RLP or typed transaction format.
359
    Needed because non-legacy transactions aren't RLP.
360
361
    Legacy transactions are returned as-is, while other transaction types
362
    are prefixed with their type identifier and RLP encoded.
363
    """
364
    if isinstance(tx, LegacyTransaction):
365
        return tx
366
    elif isinstance(tx, AccessListTransaction):
367
        return b"\x01" + rlp.encode(tx)
368
    elif isinstance(tx, FeeMarketTransaction):
369
        return b"\x02" + rlp.encode(tx)
370
    elif isinstance(tx, BlobTransaction):
371
        return b"\x03" + rlp.encode(tx)
372
    else:
373
        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:
377
    """
378
    Decode a transaction from its RLP or typed transaction format.
379
    Needed because non-legacy transactions aren't RLP.
380
381
    Legacy transactions are returned as-is, while other transaction types
382
    are decoded based on their type identifier prefix.
383
    """
384
    if isinstance(tx, Bytes):
385
        if tx[0] == 1:
386
            return rlp.decode_to(AccessListTransaction, tx[1:])
387
        elif tx[0] == 2:
388
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
389
        elif tx[0] == 3:
390
            return rlp.decode_to(BlobTransaction, tx[1:])
391
        else:
392
            raise TransactionTypeError(tx[0])
393
    else:
394
        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:
398
    """
399
    Verifies a transaction.
400
401
    The gas in a transaction gets used to pay for the intrinsic cost of
402
    operations, therefore if there is insufficient gas then it would not
403
    be possible to execute a transaction and it will be declared invalid.
404
405
    Additionally, the nonce of a transaction must not equal or exceed the
406
    limit defined in [EIP-2681].
407
    In practice, defining the limit as ``2**64-1`` has no impact because
408
    sending ``2**64-1`` transactions is improbable. It's not strictly
409
    impossible though, ``2**64-1`` transactions is the entire capacity of the
410
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
411
412
    Also, the code size of a contract creation transaction must be within
413
    limits of the protocol.
414
415
    This function takes a transaction as a parameter and returns the intrinsic
416
    gas cost of the transaction after validation. It throws an
417
    `InsufficientTransactionGasError` exception if the transaction does not
418
    provide enough gas to cover the intrinsic cost, and a `NonceOverflowError`
419
    exception if the nonce is greater than `2**64 - 2`. It also raises an
420
    `InitCodeTooLargeError` if the code size of a contract creation transaction
421
    exceeds the maximum allowed size.
422
423
    [EIP-2681]: https://eips.ethereum.org/EIPS/eip-2681
424
    """
425
    from .vm.interpreter import MAX_INIT_CODE_SIZE
426
427
    intrinsic_gas = calculate_intrinsic_cost(tx)
428
    if intrinsic_gas > tx.gas:
429
        raise InsufficientTransactionGasError("Insufficient gas")
430
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
431
        raise NonceOverflowError("Nonce too high")
432
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
433
        raise InitCodeTooLargeError("Code size too large")
434
435
    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:
439
    """
440
    Calculates the gas that is charged before execution is started.
441
442
    The intrinsic cost of the transaction is charged before execution has
443
    begun. Functions/operations in the EVM cost money to execute so this
444
    intrinsic cost is for the operations that need to be paid for as part of
445
    the transaction. Data transfer, for example, is part of this intrinsic
446
    cost. It costs ether to send data over the wire and that ether is
447
    accounted for in the intrinsic cost calculated in this function. This
448
    intrinsic cost must be calculated and paid for before execution in order
449
    for all operations to be implemented.
450
451
    The intrinsic cost includes:
452
    1. Base cost (`TX_BASE`)
453
    2. Cost for data (zero and non-zero bytes)
454
    3. Cost for contract creation (if applicable)
455
    4. Cost for access list entries (if applicable)
456
457
    This function takes a transaction as a parameter and returns the intrinsic
458
    gas cost of the transaction.
459
    """
460
    from .vm.gas import GasCosts, init_code_cost
461
462
    num_zeros = Uint(tx.data.count(0))
463
    num_non_zeros = ulen(tx.data) - num_zeros
464
    data_cost = (
465
        num_zeros * GasCosts.TX_DATA_PER_ZERO
466
        + num_non_zeros * GasCosts.TX_DATA_PER_NON_ZERO
467
    )
468
469
    if tx.to == Bytes0(b""):
470
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
471
    else:
472
        create_cost = Uint(0)
473
474
    access_list_cost = Uint(0)
475
    if isinstance(
476
        tx, (AccessListTransaction, FeeMarketTransaction, BlobTransaction)
477
    ):
478
        for access in tx.access_list:
479
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
480
            access_list_cost += (
481
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
482
            )
483
484
    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:
488
    """
489
    Extracts the sender address from a transaction.
490
491
    The v, r, and s values are the three parts that make up the signature
492
    of a transaction. In order to recover the sender of a transaction the two
493
    components needed are the signature (``v``, ``r``, and ``s``) and the
494
    signing hash of the transaction. The sender's public key can be obtained
495
    with these two values and therefore the sender address can be retrieved.
496
497
    This function takes chain_id and a transaction as parameters and returns
498
    the address of the sender of the transaction. It raises an
499
    `InvalidSignatureError` if the signature values (r, s, v) are invalid.
500
    """
501
    r, s = tx.r, tx.s
502
    if U256(0) >= r or r >= SECP256K1N:
503
        raise InvalidSignatureError("bad r")
504
    if U256(0) >= s or s > SECP256K1N // U256(2):
505
        raise InvalidSignatureError("bad s")
506
507
    if isinstance(tx, LegacyTransaction):
508
        v = tx.v
509
        if v == 27 or v == 28:
510
            public_key = secp256k1_recover(
511
                r, s, v - U256(27), signing_hash_pre155(tx)
512
            )
513
        else:
514
            chain_id_x2 = U256(chain_id) * U256(2)
515
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
516
                raise InvalidSignatureError("bad v")
517
            public_key = secp256k1_recover(
518
                r,
519
                s,
520
                v - U256(35) - chain_id_x2,
521
                signing_hash_155(tx, chain_id),
522
            )
523
    elif isinstance(tx, AccessListTransaction):
524
        if tx.y_parity not in (U256(0), U256(1)):
525
            raise InvalidSignatureError("bad y_parity")
526
        public_key = secp256k1_recover(
527
            r, s, tx.y_parity, signing_hash_2930(tx)
528
        )
529
    elif isinstance(tx, FeeMarketTransaction):
530
        if tx.y_parity not in (U256(0), U256(1)):
531
            raise InvalidSignatureError("bad y_parity")
532
        public_key = secp256k1_recover(
533
            r, s, tx.y_parity, signing_hash_1559(tx)
534
        )
535
    elif isinstance(tx, BlobTransaction):
536
        if tx.y_parity not in (U256(0), U256(1)):
537
            raise InvalidSignatureError("bad y_parity")
538
        public_key = secp256k1_recover(
539
            r, s, tx.y_parity, signing_hash_4844(tx)
540
        )
541
542
    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:
546
    """
547
    Compute the hash of a transaction used in a legacy (pre [EIP-155])
548
    signature.
549
550
    This function takes a legacy transaction as a parameter and returns the
551
    signing hash of the transaction.
552
553
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
554
    """
555
    return keccak256(
556
        rlp.encode(
557
            (
558
                tx.nonce,
559
                tx.gas_price,
560
                tx.gas,
561
                tx.to,
562
                tx.value,
563
                tx.data,
564
            )
565
        )
566
    )

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:
570
    """
571
    Compute the hash of a transaction used in a [EIP-155] signature.
572
573
    This function takes a legacy transaction and a chain ID as parameters
574
    and returns the hash of the transaction used in an [EIP-155] signature.
575
576
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
577
    """
578
    return keccak256(
579
        rlp.encode(
580
            (
581
                tx.nonce,
582
                tx.gas_price,
583
                tx.gas,
584
                tx.to,
585
                tx.value,
586
                tx.data,
587
                chain_id,
588
                Uint(0),
589
                Uint(0),
590
            )
591
        )
592
    )

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:
596
    """
597
    Compute the hash of a transaction used in a [EIP-2930] signature.
598
599
    This function takes an access list transaction as a parameter
600
    and returns the hash of the transaction used in an [EIP-2930] signature.
601
602
    [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
603
    """
604
    return keccak256(
605
        b"\x01"
606
        + rlp.encode(
607
            (
608
                tx.chain_id,
609
                tx.nonce,
610
                tx.gas_price,
611
                tx.gas,
612
                tx.to,
613
                tx.value,
614
                tx.data,
615
                tx.access_list,
616
            )
617
        )
618
    )

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:
622
    """
623
    Compute the hash of a transaction used in an [EIP-1559] signature.
624
625
    This function takes a fee market transaction as a parameter
626
    and returns the hash of the transaction used in an [EIP-1559] signature.
627
628
    [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
629
    """
630
    return keccak256(
631
        b"\x02"
632
        + rlp.encode(
633
            (
634
                tx.chain_id,
635
                tx.nonce,
636
                tx.max_priority_fee_per_gas,
637
                tx.max_fee_per_gas,
638
                tx.gas,
639
                tx.to,
640
                tx.value,
641
                tx.data,
642
                tx.access_list,
643
            )
644
        )
645
    )

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:
649
    """
650
    Compute the hash of a transaction used in an [EIP-4844] signature.
651
652
    This function takes a transaction as a parameter and returns the
653
    signing hash of the transaction used in an [EIP-4844] signature.
654
655
    [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
656
    """
657
    return keccak256(
658
        b"\x03"
659
        + rlp.encode(
660
            (
661
                tx.chain_id,
662
                tx.nonce,
663
                tx.max_priority_fee_per_gas,
664
                tx.max_fee_per_gas,
665
                tx.gas,
666
                tx.to,
667
                tx.value,
668
                tx.data,
669
                tx.access_list,
670
                tx.max_fee_per_blob_gas,
671
                tx.blob_versioned_hashes,
672
            )
673
        )
674
    )

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:
678
    """
679
    Compute the hash of a transaction.
680
681
    This function takes a transaction as a parameter and returns the
682
    keccak256 hash of the transaction. It can handle both legacy transactions
683
    and typed transactions (`AccessListTransaction`, `FeeMarketTransaction`,
684
    etc.).
685
    """
686
    assert isinstance(tx, (LegacyTransaction, Bytes))
687
    if isinstance(tx, LegacyTransaction):
688
        return keccak256(rlp.encode(tx))
689
    else:
690
        return keccak256(tx)