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

27
@slotted_freezable
28
@dataclass
class LegacyTransaction:

nonce

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

38
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

43
    gas_price: Uint

gas

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

48
    gas: Uint

to

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

53
    to: Bytes0 | Address

value

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

59
    value: U256

data

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

64
    data: Bytes

v

The recovery id of the signature.

70
    v: U256

r

The first part of the signature.

75
    r: U256

s

The second part of the signature.

80
    s: U256

Access

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

86
@slotted_freezable
87
@dataclass
class Access:

account

The address of the account that is accessed.

94
    account: Address

slots

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

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

105
@slotted_freezable
106
@dataclass
class AccessListTransaction:

chain_id

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

118
    chain_id: U64

nonce

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

123
    nonce: U256

gas_price

The price of gas for this transaction.

128
    gas_price: Uint

gas

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

133
    gas: Uint

to

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

138
    to: Bytes0 | Address

value

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

144
    value: U256

data

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

149
    data: Bytes

access_list

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

155
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

161
    y_parity: U256

r

The first part of the signature.

166
    r: U256

s

The second part of the signature.

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

177
@slotted_freezable
178
@dataclass
class FeeMarketTransaction:

chain_id

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

189
    chain_id: U64

nonce

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

194
    nonce: U256

max_priority_fee_per_gas

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

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

204
    max_fee_per_gas: Uint

gas

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

210
    gas: Uint

to

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

215
    to: Bytes0 | Address

value

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

221
    value: U256

data

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

226
    data: Bytes

access_list

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

232
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

238
    y_parity: U256

r

The first part of the signature.

243
    r: U256

s

The second part of the signature.

248
    s: U256

Transaction

Union type representing any valid transaction type.

254
Transaction = LegacyTransaction | AccessListTransaction | FeeMarketTransaction

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:
261
    """
262
    Encode a transaction into its RLP or typed transaction format.
263
    Needed because non-legacy transactions aren't RLP.
264
265
    Legacy transactions are returned as-is, while other transaction types
266
    are prefixed with their type identifier and RLP encoded.
267
    """
268
    if isinstance(tx, LegacyTransaction):
269
        return tx
270
    elif isinstance(tx, AccessListTransaction):
271
        return b"\x01" + rlp.encode(tx)
272
    elif isinstance(tx, FeeMarketTransaction):
273
        return b"\x02" + rlp.encode(tx)
274
    else:
275
        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:
279
    """
280
    Decode a transaction from its RLP or typed transaction format.
281
    Needed because non-legacy transactions aren't RLP.
282
283
    Legacy transactions are returned as-is, while other transaction types
284
    are decoded based on their type identifier prefix.
285
    """
286
    if isinstance(tx, Bytes):
287
        if tx[0] == 1:
288
            return rlp.decode_to(AccessListTransaction, tx[1:])
289
        elif tx[0] == 2:
290
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
291
        else:
292
            raise TransactionTypeError(tx[0])
293
    else:
294
        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:
298
    """
299
    Verifies a transaction.
300
301
    The gas in a transaction gets used to pay for the intrinsic cost of
302
    operations, therefore if there is insufficient gas then it would not
303
    be possible to execute a transaction and it will be declared invalid.
304
305
    Additionally, the nonce of a transaction must not equal or exceed the
306
    limit defined in [EIP-2681].
307
    In practice, defining the limit as ``2**64-1`` has no impact because
308
    sending ``2**64-1`` transactions is improbable. It's not strictly
309
    impossible though, ``2**64-1`` transactions is the entire capacity of the
310
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
311
312
    Also, the code size of a contract creation transaction must be within
313
    limits of the protocol.
314
315
    This function takes a transaction as a parameter and returns the intrinsic
316
    gas cost of the transaction after validation. It throws an
317
    `InsufficientTransactionGasError` exception if the transaction does not
318
    provide enough gas to cover the intrinsic cost, and a `NonceOverflowError`
319
    exception if the nonce is greater than `2**64 - 2`. It also raises an
320
    `InitCodeTooLargeError` if the code size of a contract creation transaction
321
    exceeds the maximum allowed size.
322
323
    [EIP-2681]: https://eips.ethereum.org/EIPS/eip-2681
324
    """
325
    from .vm.interpreter import MAX_INIT_CODE_SIZE
326
327
    intrinsic_gas = calculate_intrinsic_cost(tx)
328
    if intrinsic_gas > tx.gas:
329
        raise InsufficientTransactionGasError("Insufficient gas")
330
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
331
        raise NonceOverflowError("Nonce too high")
332
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
333
        raise InitCodeTooLargeError("Code size too large")
334
335
    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:
339
    """
340
    Calculates the gas that is charged before execution is started.
341
342
    The intrinsic cost of the transaction is charged before execution has
343
    begun. Functions/operations in the EVM cost money to execute so this
344
    intrinsic cost is for the operations that need to be paid for as part of
345
    the transaction. Data transfer, for example, is part of this intrinsic
346
    cost. It costs ether to send data over the wire and that ether is
347
    accounted for in the intrinsic cost calculated in this function. This
348
    intrinsic cost must be calculated and paid for before execution in order
349
    for all operations to be implemented.
350
351
    The intrinsic cost includes:
352
    1. Base cost (`TX_BASE`)
353
    2. Cost for data (zero and non-zero bytes)
354
    3. Cost for contract creation (if applicable)
355
    4. Cost for access list entries (if applicable)
356
357
    This function takes a transaction as a parameter and returns the intrinsic
358
    gas cost of the transaction.
359
    """
360
    from .vm.gas import GasCosts, init_code_cost
361
362
    num_zeros = Uint(tx.data.count(0))
363
    num_non_zeros = ulen(tx.data) - num_zeros
364
    data_cost = (
365
        num_zeros * GasCosts.TX_DATA_PER_ZERO
366
        + num_non_zeros * GasCosts.TX_DATA_PER_NON_ZERO
367
    )
368
369
    if tx.to == Bytes0(b""):
370
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
371
    else:
372
        create_cost = Uint(0)
373
374
    access_list_cost = Uint(0)
375
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
376
        for access in tx.access_list:
377
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
378
            access_list_cost += (
379
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
380
            )
381
382
    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:
386
    """
387
    Extracts the sender address from a transaction.
388
389
    The v, r, and s values are the three parts that make up the signature
390
    of a transaction. In order to recover the sender of a transaction the two
391
    components needed are the signature (``v``, ``r``, and ``s``) and the
392
    signing hash of the transaction. The sender's public key can be obtained
393
    with these two values and therefore the sender address can be retrieved.
394
395
    This function takes chain_id and a transaction as parameters and returns
396
    the address of the sender of the transaction. It raises an
397
    `InvalidSignatureError` if the signature values (r, s, v) are invalid.
398
    """
399
    r, s = tx.r, tx.s
400
    if U256(0) >= r or r >= SECP256K1N:
401
        raise InvalidSignatureError("bad r")
402
    if U256(0) >= s or s > SECP256K1N // U256(2):
403
        raise InvalidSignatureError("bad s")
404
405
    if isinstance(tx, LegacyTransaction):
406
        v = tx.v
407
        if v == 27 or v == 28:
408
            public_key = secp256k1_recover(
409
                r, s, v - U256(27), signing_hash_pre155(tx)
410
            )
411
        else:
412
            chain_id_x2 = U256(chain_id) * U256(2)
413
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
414
                raise InvalidSignatureError("bad v")
415
            public_key = secp256k1_recover(
416
                r,
417
                s,
418
                v - U256(35) - chain_id_x2,
419
                signing_hash_155(tx, chain_id),
420
            )
421
    elif isinstance(tx, AccessListTransaction):
422
        if tx.y_parity not in (U256(0), U256(1)):
423
            raise InvalidSignatureError("bad y_parity")
424
        public_key = secp256k1_recover(
425
            r, s, tx.y_parity, signing_hash_2930(tx)
426
        )
427
    elif isinstance(tx, FeeMarketTransaction):
428
        if tx.y_parity not in (U256(0), U256(1)):
429
            raise InvalidSignatureError("bad y_parity")
430
        public_key = secp256k1_recover(
431
            r, s, tx.y_parity, signing_hash_1559(tx)
432
        )
433
434
    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:
438
    """
439
    Compute the hash of a transaction used in a legacy (pre [EIP-155])
440
    signature.
441
442
    This function takes a legacy transaction as a parameter and returns the
443
    signing hash of the transaction.
444
445
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
446
    """
447
    return keccak256(
448
        rlp.encode(
449
            (
450
                tx.nonce,
451
                tx.gas_price,
452
                tx.gas,
453
                tx.to,
454
                tx.value,
455
                tx.data,
456
            )
457
        )
458
    )

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:
462
    """
463
    Compute the hash of a transaction used in a [EIP-155] signature.
464
465
    This function takes a legacy transaction and a chain ID as parameters
466
    and returns the hash of the transaction used in an [EIP-155] signature.
467
468
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
469
    """
470
    return keccak256(
471
        rlp.encode(
472
            (
473
                tx.nonce,
474
                tx.gas_price,
475
                tx.gas,
476
                tx.to,
477
                tx.value,
478
                tx.data,
479
                chain_id,
480
                Uint(0),
481
                Uint(0),
482
            )
483
        )
484
    )

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:
488
    """
489
    Compute the hash of a transaction used in a [EIP-2930] signature.
490
491
    This function takes an access list transaction as a parameter
492
    and returns the hash of the transaction used in an [EIP-2930] signature.
493
494
    [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
495
    """
496
    return keccak256(
497
        b"\x01"
498
        + rlp.encode(
499
            (
500
                tx.chain_id,
501
                tx.nonce,
502
                tx.gas_price,
503
                tx.gas,
504
                tx.to,
505
                tx.value,
506
                tx.data,
507
                tx.access_list,
508
            )
509
        )
510
    )

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:
514
    """
515
    Compute the hash of a transaction used in an [EIP-1559] signature.
516
517
    This function takes a fee market transaction as a parameter
518
    and returns the hash of the transaction used in an [EIP-1559] signature.
519
520
    [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
521
    """
522
    return keccak256(
523
        b"\x02"
524
        + rlp.encode(
525
            (
526
                tx.chain_id,
527
                tx.nonce,
528
                tx.max_priority_fee_per_gas,
529
                tx.max_fee_per_gas,
530
                tx.gas,
531
                tx.to,
532
                tx.value,
533
                tx.data,
534
                tx.access_list,
535
            )
536
        )
537
    )

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:
541
    """
542
    Compute the hash of a transaction.
543
544
    This function takes a transaction as a parameter and returns the
545
    keccak256 hash of the transaction. It can handle both legacy transactions
546
    and typed transactions (`AccessListTransaction`, `FeeMarketTransaction`,
547
    etc.).
548
    """
549
    assert isinstance(tx, (LegacyTransaction, Bytes))
550
    if isinstance(tx, LegacyTransaction):
551
        return keccak256(rlp.encode(tx))
552
    else:
553
        return keccak256(tx)