Skip to content
Closed
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
3 changes: 2 additions & 1 deletion docs/running_tests/execute/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ When executing tests with many transactions (e.g., benchmark tests), the `execut
- Transactions are sent in batches of up to 750 transactions by default
- Each batch is sent and confirmed before the next batch begins
- Progress logging shows batch number and transaction ranges
- The same limit caps every other batched JSON-RPC request (receipts, balances, code, account state)

**CLI Configuration:**

Expand All @@ -73,7 +74,7 @@ execute --max-tx-per-batch 1000 tests/

**Safety Threshold:**

A warning is logged when `max_transactions_per_batch` exceeds 1000, as this may cause RPC service instability or failures depending on the RPC endpoint's capacity.
A warning is logged when `max_batch_size` exceeds 1000, as this may cause RPC service instability or failures depending on the RPC endpoint's capacity.

**Use Cases:**

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def pytest_html_report_title(report: Any) -> None:


# NOTE: ``transactions_per_block``, ``default_gas_price``, ``dry_run``,
# ``max_transactions_per_batch``, ``use_testing_build_block``,
# ``max_batch_size``, ``use_testing_build_block``,
# ``default_max_fee_per_gas``, ``default_max_priority_fee_per_gas``,
# ``default_max_fee_per_blob_gas``, ``max_priority_fee_per_gas``,
# ``max_fee_per_gas``, ``max_fee_per_blob_gas``, ``gas_price``, and
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Pre-allocation fixtures used for test filling."""

from collections.abc import Sequence
from dataclasses import dataclass
from itertools import count
from pathlib import Path
Expand Down Expand Up @@ -224,6 +225,67 @@ class _DeferredFundAddress:
minimum_balance: bool


@dataclass
class _DeferredAccountAssertion:
"""
Deferred assertion on a predeployed account.

Verified at start_block before the benchmark runs.
Uses primitives only to stay independent of test expectations.
"""

address: Address
is_existing_account: bool
is_contract: bool
min_balance: int | None
code_prefix: bytes | None
label: str | None


class DeployedAccountVerificationError(AssertionError):
"""Raised when predeployed benchmark targets fail verification."""


def _check_account_assertion(
d: _DeferredAccountAssertion,
account: Account | None,
code: Bytes | None,
) -> list[str]:
"""Return human-readable failures for one account assertion (may be []."""
who = f"{d.label or '<target>'} at {d.address}"
if account is None:
return [f"{who}: no account data returned from the client"]
balance = int(account.balance)
nonce = int(account.nonce)
errors: list[str] = []
if not d.is_existing_account:
if balance != 0 or nonce != 0:
errors.append(
f"{who}: expected NON-existent, got balance={balance} "
f"nonce={nonce}"
)
return errors
if d.is_contract and nonce < 1:
errors.append(
f"{who}: expected a deployed contract (nonce>=1) but got "
f"nonce={nonce}, balance={balance} — likely NOT deployed on the "
"snapshot; the benchmark would silently hit an empty account"
)
if d.min_balance is not None and balance < d.min_balance:
errors.append(
f"{who}: expected balance>={d.min_balance} but got {balance}"
)
if d.code_prefix is not None:
actual = bytes(code) if code is not None else b""
if not actual.startswith(d.code_prefix):
errors.append(
f"{who}: expected code to start with "
f"0x{d.code_prefix.hex()} (e.g. a delegated account) but "
f"got 0x{actual.hex()}"
)
return errors


def _compute_deploy_gas_limit(
fork: Fork,
*,
Expand Down Expand Up @@ -319,8 +381,12 @@ class Alloc(SharedAlloc):
_deferred_fund_addresses: List[_DeferredFundAddress] = PrivateAttr(
default_factory=list
)
_deferred_account_assertions: List[_DeferredAccountAssertion] = (
PrivateAttr(default_factory=list)
)
_block_number: int = PrivateAttr()
_timestamp: int = PrivateAttr()
_verify_full: bool = PrivateAttr(default=False)

def __init__(
self,
Expand All @@ -334,6 +400,7 @@ def __init__(
block_number: int = 0,
timestamp: int = 0,
funding_gas_limit: int = 200_000,
verify_full: bool = False,
**kwargs: Any,
) -> None:
"""Initialize the pre-alloc with the given parameters."""
Expand All @@ -347,6 +414,7 @@ def __init__(
self._block_number = block_number
self._timestamp = timestamp
self._funding_gas_limit = funding_gas_limit
self._verify_full = verify_full

def code_pre_processor(self, code: Bytecode) -> Bytecode:
"""Pre-processes the code before setting it."""
Expand Down Expand Up @@ -825,6 +893,103 @@ def _nonexistent_account(self) -> Address:
logger.debug(f"Returning unused address {eoa} (nonexistent account)")
return Address(eoa)

def expect_account_state(
self,
addresses: Address | Sequence[Address],
*,
is_existing_account: bool = True,
is_contract: bool = False,
min_balance: int | None = None,
code_prefix: bytes | None = None,
) -> None:
"""
Register deferred assertion(s) on predeployed account(s).

Verified at start_block (fill-stateful only). For a range, only the
first and last are checked unless ``--verify-full-accounts`` is set;
each assertion's label is taken from the address itself.
"""
if isinstance(addresses, Address):
targets: Sequence[Address] = (addresses,)
elif self._verify_full or len(addresses) <= 2:
targets = addresses
else:
targets = (addresses[0], addresses[-1])
for address in targets:
self._deferred_account_assertions.append(
_DeferredAccountAssertion(
address=address,
is_existing_account=is_existing_account,
is_contract=is_contract,
min_balance=min_balance,
code_prefix=code_prefix,
label=address.label,
)
)

def verify_deployed_accounts(self, block_number: int) -> None:
"""
Verify registered predeployed-account assertions at block_number.

Batches eth_getBalance and eth_getTransactionCount queries.
Fetches code only for assertions with code_prefix (e.g., EIP-7702
designation). Collects all failures before raising.
"""
deferred = self._deferred_account_assertions
self._deferred_account_assertions = []
if not deferred:
return

chunk, max_reported, verified = 2000, 20, 0
for i in range(0, len(deferred), chunk):
batch = deferred[i : i + chunk]

query = BaseAlloc(root={d.address: Account() for d in batch})
accounts = self._eth_rpc.get_alloc(
query, block_number=block_number, skip_code=True
).root

code_targets = [
d.address for d in batch if d.code_prefix is not None
]
codes: dict[Address, Bytes] = dict(
zip(
code_targets,
self._eth_rpc.get_codes(
code_targets, block_number=block_number
),
strict=True,
)
)

errors: list[str] = []
failed = 0
for d in batch:
errs = _check_account_assertion(
d, accounts.get(d.address), codes.get(d.address)
)
if errs:
failed += 1
errors.extend(errs)

if errors:
shown = errors[:max_reported]
omitted = len(errors) - len(shown)
suffix = f"\n ... and {omitted} more" if omitted else ""
raise DeployedAccountVerificationError(
f"{failed} predeployed benchmark target(s) failed "
f"verification at start_block (after checking "
f"{verified + len(batch)}):\n "
+ "\n ".join(shown)
+ suffix
)
verified += len(batch)

logger.info(
f"Verified {verified} predeployed benchmark target(s) at "
f"block {block_number}"
)

def resolve_deferred_checks(self) -> None:
"""
Resolve all deferred on-chain checks using batched RPC calls.
Expand Down Expand Up @@ -1155,6 +1320,9 @@ def pre(
node_id=request.node.nodeid,
address_stubs=address_stubs,
funding_gas_limit=sender_fund_refund_gas_limit,
verify_full=getattr(
request.config.option, "verify_full_accounts", False
),
)

# Yield the pre-alloc for usage during the test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ def __init__(
get_payload_wait_time: float,
initial_forkchoice_update_retries: int = 5,
transaction_wait_timeout: int = 60,
max_transactions_per_batch: int | None = None,
max_batch_size: int | None = None,
request_timeout: TimeoutType = DEFAULT_REQUEST_TIMEOUT,
testing_rpc: TestingRPC | None = None,
):
"""Initialize the Ethereum RPC client for the hive simulator."""
super().__init__(
rpc_endpoint,
transaction_wait_timeout=transaction_wait_timeout,
max_transactions_per_batch=max_transactions_per_batch,
max_batch_size=max_batch_size,
request_timeout=request_timeout,
)
self.fork = fork
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ def eth_rpc(
engine_rpc: EngineRPC,
session_fork: Fork | TransitionFork,
session_temp_folder: Path,
max_transactions_per_batch: int | None,
max_batch_size: int | None,
use_testing_build_block: bool,
) -> EthRPC:
"""Initialize ethereum RPC client for the execution client under test."""
Expand All @@ -451,6 +451,6 @@ def eth_rpc(
session_temp_folder=session_temp_folder,
get_payload_wait_time=get_payload_wait_time,
transaction_wait_timeout=tx_wait_timeout,
max_transactions_per_batch=max_transactions_per_batch,
max_batch_size=max_batch_size,
testing_rpc=testing_rpc,
)
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def eth_rpc(
engine_rpc: EngineRPC | None,
session_fork: Fork | TransitionFork,
session_temp_folder: Path,
max_transactions_per_batch: int | None,
max_batch_size: int | None,
use_testing_build_block: bool,
) -> EthRPC:
"""Initialize ethereum RPC client for the execution client under test."""
Expand All @@ -189,7 +189,7 @@ def eth_rpc(
return EthRPC(
rpc_endpoint,
transaction_wait_timeout=tx_wait_timeout,
max_transactions_per_batch=max_transactions_per_batch,
max_batch_size=max_batch_size,
)
get_payload_wait_time = request.config.getoption("get_payload_wait_time")
testing_rpc = None
Expand All @@ -205,6 +205,6 @@ def eth_rpc(
else session_temp_folder,
get_payload_wait_time=get_payload_wait_time,
transaction_wait_timeout=tx_wait_timeout,
max_transactions_per_batch=max_transactions_per_batch,
max_batch_size=max_batch_size,
testing_rpc=testing_rpc,
)
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def chain_builder_eth_rpc(
session_temp_folder=session_temp_folder,
get_payload_wait_time=1,
transaction_wait_timeout=20,
max_transactions_per_batch=10,
max_batch_size=10,
testing_rpc=TestingRPC(rpc_endpoint),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
)
from execution_testing.client_clis import ClientBackend
from execution_testing.client_clis.cli_types import EnginePayloadMetadata
from execution_testing.client_clis.client_backend import (
DEFAULT_OPCODE_COUNT_TRACE_TIMEOUT,
)
from execution_testing.fixtures import FixtureFillingPhase
from execution_testing.fixtures.blockchain import (
StatefulPreRunFixture,
Expand Down Expand Up @@ -147,6 +150,30 @@ def pytest_addoption(parser: pytest.Parser) -> None:
"opt-in."
),
)
group.addoption(
"--opcode-count-trace-timeout",
action="store",
dest="opcode_count_trace_timeout",
default=DEFAULT_OPCODE_COUNT_TRACE_TIMEOUT,
type=str,
help=(
"Per-transaction bound for the --extract-opcode-count trace, as "
"a Go duration (e.g. 30s, 5m, 1h). Without it the client applies "
"its own (5s on geth), which a benchmark block's trace outruns; "
"the abandoned transaction is then tallied as zero."
),
)
group.addoption(
"--verify-full-accounts",
action="store_true",
dest="verify_full_accounts",
default=False,
help=(
"Verify all predeployed targets instead of sampling. "
"By default, only first and last accounts per range are checked. "
"This flag checks every account at start_block.)"
),
)


def _resolve_session_fork(
Expand Down Expand Up @@ -473,7 +500,7 @@ def max_gas_limit_per_test(
return fork_at_genesis.transaction_gas_limit_cap()


# Other live-client fixtures (``max_transactions_per_batch``,
# Other live-client fixtures (``max_batch_size``,
# ``default_*``, fee fields, ``dry_run``, ...) come from
# ``shared.live_client_flags``. ``skip_cleanup`` from ``execute.pre_alloc``;
# we force it on in ``pytest_configure``.
Expand All @@ -496,11 +523,18 @@ def extract_opcode_count(request: pytest.FixtureRequest) -> bool:
return request.config.getoption("extract_opcode_count")


@pytest.fixture(scope="session")
def opcode_count_trace_timeout(request: pytest.FixtureRequest) -> str:
"""The --opcode-count-trace-timeout bound sent with each trace."""
return request.config.getoption("opcode_count_trace_timeout")


@pytest.fixture(scope="session")
def client_backend(
eth_rpc: ChainBuilderEthRPC,
debug_rpc: DebugRPC,
extract_opcode_count: bool,
opcode_count_trace_timeout: str,
session_fork: Fork | TransitionFork,
default_gas_price: int | None,
default_max_fee_per_gas: int | None,
Expand All @@ -526,6 +560,7 @@ def client_backend(
fork=session_fork,
debug_rpc=debug_rpc,
extract_opcode_count=extract_opcode_count,
opcode_count_trace_timeout=opcode_count_trace_timeout,
)

priority_fee = default_max_priority_fee_per_gas
Expand Down
Loading
Loading