Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 184 additions & 26 deletions packages/testing/src/execution_testing/specs/blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@
ExecutionWitnessHeadersExpectation,
ExecutionWitnessStateExpectation,
)
from execution_testing.test_types.execution_witness.modifiers import (
PublicKeyModifier,
)

from .base import BaseTest, FillResult, OpMode, verify_result
from .debugging import print_traces
Expand Down Expand Up @@ -215,16 +218,17 @@ def with_execution_witness_implicit_codes(
return expectation.model_copy(update={"codes_present": codes_present})


def rerun_amsterdam_stateless_guest_with_witness(
def rerun_amsterdam_stateless_guest_with_overrides(
*,
fork: Fork,
block_number: int,
timestamp: int,
original_stateless_input_bytes: Bytes,
execution_witness: ExecutionWitness,
execution_witness: ExecutionWitness | None = None,
public_keys: Tuple[Bytes, ...] | None = None,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mainly adding public_keys as a new field in the execution witness that can be modified by tests to check if the guest program is correctly validating its correctness. (The execution_witness change is a simplification to make both potentially modified execution_witness and public_keys feel symmetrical at this method API design).

) -> tuple[Bytes, Bytes, bool]:
"""
Rebuild the stateless input with the emitted witness and rerun the guest.
Rebuild the stateless input with test overrides and rerun the guest.

Amsterdam is currently the only fork with stateless guest support in this
repository, so the rerun path is kept Amsterdam-specific.
Expand Down Expand Up @@ -254,23 +258,29 @@ def rerun_amsterdam_stateless_guest_with_witness(
original_input = deserialize_stateless_input(
AmsterdamBytes(bytes(original_stateless_input_bytes))
)
rebuilt_witness = AmsterdamExecutionWitness(
state=tuple(
AmsterdamBytes(bytes(node)) for node in execution_witness.state
),
codes=tuple(
AmsterdamBytes(bytes(code)) for code in execution_witness.codes
),
headers=tuple(
AmsterdamBytes(bytes(header))
for header in execution_witness.headers
),
)
rebuilt_witness = original_input.witness
if execution_witness is not None:
rebuilt_witness = AmsterdamExecutionWitness(
state=tuple(
AmsterdamBytes(bytes(node)) for node in execution_witness.state
),
codes=tuple(
AmsterdamBytes(bytes(code)) for code in execution_witness.codes
),
headers=tuple(
AmsterdamBytes(bytes(header))
for header in execution_witness.headers
),
)
rebuilt_input = AmsterdamStatelessInput(
new_payload_request=original_input.new_payload_request,
witness=rebuilt_witness,
chain_config=original_input.chain_config,
public_keys=original_input.public_keys,
public_keys=(
tuple(AmsterdamBytes(bytes(key)) for key in public_keys)
if public_keys is not None
else original_input.public_keys
),
)
rebuilt_input_bytes = serialize_stateless_input(rebuilt_input)
rebuilt_output_bytes = run_stateless_guest(rebuilt_input_bytes)
Expand All @@ -283,6 +293,83 @@ def rerun_amsterdam_stateless_guest_with_witness(
)


def get_amsterdam_stateless_input_public_key_data(
*,
fork: Fork,
block_number: int,
timestamp: int,
stateless_input_bytes: Bytes,
) -> tuple[Tuple[Bytes, ...], Tuple[Bytes, ...]]:
"""
Decode Amsterdam stateless input public keys and payload transactions.
"""
active_fork = fork.fork_at(block_number=block_number, timestamp=timestamp)
if active_fork.name() != "Amsterdam":
raise Exception(
"Stateless input public-key decoding is only supported for "
"Amsterdam"
)

from ethereum.forks.amsterdam.stateless_guest import (
deserialize_stateless_input,
)
from ethereum_types.bytes import Bytes as AmsterdamBytes

stateless_input = deserialize_stateless_input(
AmsterdamBytes(bytes(stateless_input_bytes))
)
public_keys = tuple(
Bytes(bytes(public_key)) for public_key in stateless_input.public_keys
)
payload_transactions = tuple(
Bytes(bytes(transaction))
for transaction in (
stateless_input.new_payload_request.execution_payload.transactions
)
)
return public_keys, payload_transactions


def verify_stateless_input_public_keys(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whenever a test is filled, we always check the public_keys generated by t8n matches an explicit list of public keys recovered with ecrecover.

This happens automatically for all tests and do not need an explicit signal from the test creator. This might be a bit harshish on the filler to check this always, but it feels way safer since it is an invariant that must always hold.

I filled locally and didn't notice any observable slowdown because of ecrecovers, so looks should be okay. Eventually if we conclude otherwise, we can avoid doing it always and expect the test writer to provide explicit signal to do this check for partiular cases. NBD.

public_keys: Tuple[Bytes, ...],
payload_transactions: Tuple[Bytes, ...],
chain_id: int,
) -> None:
"""
Verify that every payload transaction has its recovered public key.
"""
payload_transaction_count = len(payload_transactions)
if len(public_keys) != payload_transaction_count:
raise AssertionError(
"Stateless input public key count does not match payload "
f"transactions: got {len(public_keys)} public keys for "
f"{payload_transaction_count} transactions"
)

from ethereum.forks.amsterdam.transactions import (
decode_transaction,
recover_transaction_public_key,
)
from ethereum_types.bytes import Bytes as AmsterdamBytes
from ethereum_types.numeric import U64

for index, (public_key, payload_transaction) in enumerate(
zip(public_keys, payload_transactions, strict=True)
):
transaction = decode_transaction(
AmsterdamBytes(bytes(payload_transaction))
)
expected_public_key = recover_transaction_public_key(
U64(chain_id),
transaction,
)
if bytes(public_key) != bytes(expected_public_key):
raise AssertionError(
"Stateless input public key "
f"{index} does not match recovered transaction public key"
)


def decode_amsterdam_stateless_output(
*,
fork: Fork,
Expand Down Expand Up @@ -482,10 +569,18 @@ class Block(Header):
If set, the execution witness headers will be verified and potentially
modified for invalid tests.
"""
stateless_input_public_keys_modifier: PublicKeyModifier | None = Field(
default=None,
exclude=True,
)
"""
If set, mutate the stateless input transaction public keys before rerunning
the guest for invalid tests.
"""
expected_stateless_validation_success: bool | None = None
"""
If set, assert the stateless guest result matches this expectation. This
must be set explicitly for tests that mutate the emitted execution witness.
must be set explicitly for tests that mutate stateless validation input.
"""
exception: BLOCK_EXCEPTION_TYPE = None
# If set, the block is expected to be rejected by the client.
Expand Down Expand Up @@ -1012,13 +1107,18 @@ def generate_block_data(
or block.expected_execution_witness_codes is not None
or block.expected_execution_witness_headers is not None
)
public_keys_modifier = block.stateless_input_public_keys_modifier
has_public_keys_modifier = public_keys_modifier is not None
expected_success = block.expected_stateless_validation_success
if self.skip_stateless_validation and (
has_witness_expectation or expected_success is not None
has_witness_expectation
or has_public_keys_modifier
or expected_success is not None
):
raise AssertionError(
"skip_stateless_validation cannot be combined with "
"execution witness expectations or "
"execution witness expectations, stateless input public-key "
"modifiers, or "
"expected_stateless_validation_success"
)
state_expectation = block.expected_execution_witness_state
Expand Down Expand Up @@ -1096,8 +1196,50 @@ def generate_block_data(
"Mutated execution witness tests must set "
"expected_stateless_validation_success explicitly"
)
if has_public_keys_modifier and expected_success is None:
raise AssertionError(
"Mutated stateless input public-key tests must set "
"expected_stateless_validation_success explicitly"
)
public_keys: Tuple[Bytes, ...] | None = None
should_verify_stateless_input_public_keys = (
stateless_input_bytes is not None
# The block could be invalid because of invalid txs, thus
# the public keys might not be properly constructed given they
# can't be decoded and thus provided in the execution witness.
and block.exception is None
)
if stateless_input_bytes is not None and (
should_verify_stateless_input_public_keys
or has_public_keys_modifier
):
payload_transactions: Tuple[Bytes, ...]
(
public_keys,
payload_transactions,
) = get_amsterdam_stateless_input_public_key_data(
fork=fork,
block_number=int(env.number),
timestamp=int(env.timestamp),
stateless_input_bytes=stateless_input_bytes,
)
if should_verify_stateless_input_public_keys:
verify_stateless_input_public_keys(
public_keys,
payload_transactions,
self.chain_id,
)
elif has_public_keys_modifier:
raise Exception(
"Stateless input public-key mutation requires stateless "
"input bytes"
)
canonical_successful_validation: bool | None = None
if has_witness_modifier or expected_success is not None:
if (
has_witness_modifier
or has_public_keys_modifier
or expected_success is not None
):
if stateless_output_bytes is None:
raise Exception(
"Stateless guest verification requires stateless output "
Expand All @@ -1111,23 +1253,39 @@ def generate_block_data(
stateless_output.successful_validation
)

should_rerun_stateless_guest = has_witness_modifier
should_rerun_stateless_guest = (
has_witness_modifier or has_public_keys_modifier
)
if should_rerun_stateless_guest:
if execution_witness is None or stateless_input_bytes is None:
if stateless_input_bytes is None:
raise Exception(
"Stateless guest rerun requires execution witness and "
"stateless input bytes"
"Stateless guest rerun requires stateless input bytes"
)
if has_witness_modifier and execution_witness is None:
raise Exception(
"Stateless guest witness mutation rerun requires "
"execution witness"
)
modified_public_keys: Tuple[Bytes, ...] | None = None
if public_keys_modifier is not None:
if public_keys is None:
raise Exception(
"Stateless guest rerun requires public keys"
)
modified_public_keys = public_keys_modifier(public_keys)
(
stateless_input_bytes,
stateless_output_bytes,
successful_validation,
) = rerun_amsterdam_stateless_guest_with_witness(
) = rerun_amsterdam_stateless_guest_with_overrides(
fork=fork,
block_number=int(env.number),
timestamp=int(env.timestamp),
original_stateless_input_bytes=stateless_input_bytes,
execution_witness=execution_witness,
execution_witness=(
execution_witness if has_witness_modifier else None
),
public_keys=modified_public_keys,
)
stateless_output = decode_amsterdam_stateless_output(
fork=fork,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
execution witnesses for testing invalid block scenarios.
"""

from typing import Callable
from typing import Callable, Tuple

from execution_testing.base_types import Bytes

from .types import ExecutionWitness

PublicKeyModifier = Callable[[Tuple[Bytes, ...]], Tuple[Bytes, ...]]


def add_code(
code: Bytes,
Expand Down Expand Up @@ -206,10 +208,32 @@ def transform(
return transform


def replace_public_key_at(
index: int,
public_key: Bytes,
) -> PublicKeyModifier:
"""Replace the transaction public key at `index`."""

def transform(
public_keys: Tuple[Bytes, ...],
) -> Tuple[Bytes, ...]:
new_public_keys = list(public_keys)
try:
new_public_keys[index] = public_key
except IndexError as exc:
raise IndexError(
f"Public key index {index} out of range for stateless input"
) from exc
return tuple(new_public_keys)

return transform


__all__ = [
"add_state_node",
"add_code",
"clear_headers",
"PublicKeyModifier",
"remove_state_node",
"remove_code",
"remove_code_at",
Expand All @@ -219,4 +243,5 @@ def transform(
"remove_header_at",
"reverse_headers",
"replace_header_at",
"replace_public_key_at",
]
13 changes: 11 additions & 2 deletions src/ethereum/forks/amsterdam/execution_engine/new_payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Payload verification.
"""

from typing import Tuple
from typing import Optional, Tuple

from ethereum_rlp import rlp
from ethereum_types.bytes import Bytes

from ethereum.crypto.hash import keccak256
from ethereum.exceptions import InvalidBlock
Expand Down Expand Up @@ -71,6 +72,7 @@ def execute_new_payload_request(
new_payload_request: NewPayloadRequest,
pre_state: PreState,
chain_context: ChainContext,
transaction_public_keys: Optional[Tuple[Bytes, ...]] = None,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

execute_new_paylaod_request can receive an optional list of transaction_public_keys.

The call of this method from the guest program perspective always provide the values. But remember this method is also called from the "Engine API" context which is stateful, in that case it isn't passed.

) -> Tuple[BlockDiff, Block]:
"""
Validate and execute a payload against ``pre_state``.
Expand All @@ -88,6 +90,8 @@ def execute_new_payload_request(
Pre-execution state provider.
chain_context :
Chain context needed for block execution.
transaction_public_keys :
Optional transaction public keys in payload order.

Returns
-------
Expand Down Expand Up @@ -119,7 +123,12 @@ def execute_new_payload_request(
parent_beacon_block_root,
execution_requests,
)
block_diff = execute_block(block, pre_state, chain_context)
block_diff = execute_block(
block,
pre_state,
chain_context,
transaction_public_keys=transaction_public_keys,
)
return block_diff, block


Expand Down
Loading
Loading