Skip to content

Commit

Permalink
format ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
winsvega committed Jan 16, 2025
1 parent e077f1c commit 04d3ffd
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 61 deletions.
50 changes: 23 additions & 27 deletions src/ethereum_test_fixtures/schemas/blockchain/headers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Define genesisHeader schema for filled .json tests
"""
"""Define genesisHeader schema for filled .json tests."""

from typing import Any, Optional

Expand All @@ -18,20 +16,20 @@


class InvalidBlockRecord(BaseModel):
"""Invalid block rlp only provided"""
"""Invalid block rlp only provided."""

rlp: str
expectException: str # noqa: N815
rlp_decoded: Optional[dict] = None

class Config:
"""Forbids any extra fields that are not declared in the model"""
"""Forbids any extra fields that are not declared in the model."""

extra = "forbid"


class BlockRecord(BaseModel):
"""Block record in blockchain tests"""
"""Block record in blockchain tests."""

blockHeader: dict # noqa: N815
rlp: str
Expand All @@ -43,19 +41,19 @@ class BlockRecord(BaseModel):
)

class Config:
"""Forbids any extra fields that are not declared in the model"""
"""Forbids any extra fields that are not declared in the model."""

extra = "forbid"


class BlockRecordShanghai(BlockRecord):
"""Block record in blockchain tests"""
"""Block record in blockchain tests."""

withdrawals: list


class FrontierHeader(BaseModel):
"""Frontier block header in test json"""
"""Frontier block header in test json."""

bloom: FixedHash256
coinbase: FixedHash20
Expand All @@ -75,12 +73,12 @@ class FrontierHeader(BaseModel):
uncleHash: FixedHash32 # noqa: N815"

class Config:
"""Forbids any extra fields that are not declared in the model"""
"""Forbids any extra fields that are not declared in the model."""

extra = "forbid"

def get_field_rlp_order(self) -> dict[str, Any]:
"""The order fields are encoded into rlp"""
"""Order fields are encoded into rlp."""
rlp_order: dict[str, Any] = {
"parentHash": self.parentHash,
"uncleHash": self.uncleHash,
Expand All @@ -102,70 +100,68 @@ def get_field_rlp_order(self) -> dict[str, Any]:


class HomesteadHeader(FrontierHeader):
"""Homestead block header in test json"""
"""Homestead block header in test json."""


class ByzantiumHeader(HomesteadHeader):
"""Byzantium block header in test json"""
"""Byzantium block header in test json."""


class ConstantinopleHeader(ByzantiumHeader):
"""Constantinople block header in test json"""
"""Constantinople block header in test json."""


class IstanbulHeader(ConstantinopleHeader):
"""Istanbul block header in test json"""
"""Istanbul block header in test json."""


class BerlinHeader(IstanbulHeader):
"""Berlin block header in test json"""
"""Berlin block header in test json."""


class LondonHeader(BerlinHeader):
"""London block header in test json"""
"""London block header in test json."""

baseFeePerGas: PrefixedEvenHex # noqa: N815

def get_field_rlp_order(self) -> dict[str, Any]:
"""The order fields are encoded into rlp"""
"""Order fields are encoded into rlp."""
rlp_order: dict[str, Any] = super().get_field_rlp_order()
rlp_order["baseFeePerGas"] = self.baseFeePerGas
return rlp_order


class ParisHeader(LondonHeader):
"""Paris block header in test json"""
"""Paris block header in test json."""

@model_validator(mode="after")
def check_block_header(self):
"""
Validate Paris block header rules
"""
"""Validate Paris block header rules."""
if self.difficulty != "0x00":
raise ValueError("Starting from Paris, block difficulty must be 0x00")


class ShanghaiHeader(ParisHeader):
"""Shanghai block header in test json"""
"""Shanghai block header in test json."""

withdrawalsRoot: FixedHash32 # noqa: N815

def get_field_rlp_order(self) -> dict[str, Any]:
"""The order fields are encoded into rlp"""
"""Order fields are encoded into rlp."""
rlp_order: dict[str, Any] = super().get_field_rlp_order()
rlp_order["withdrawalsRoot"] = self.withdrawalsRoot
return rlp_order


class CancunHeader(ShanghaiHeader):
"""Cancun block header in test json"""
"""Cancun block header in test json."""

blobGasUsed: PrefixedEvenHex # noqa: N815
excessBlobGas: PrefixedEvenHex # noqa: N815
parentBeaconBlockRoot: FixedHash32 # noqa: N815

def get_field_rlp_order(self) -> dict[str, Any]:
"""The order fields are encoded into rlp"""
"""Order fields are encoded into rlp."""
rlp_order: dict[str, Any] = super().get_field_rlp_order()
rlp_order["blobGasUsed"] = self.blobGasUsed
rlp_order["excessBlobGas"] = self.excessBlobGas
Expand All @@ -174,7 +170,7 @@ def get_field_rlp_order(self) -> dict[str, Any]:


def verify_block_header_vs_rlp_string(header: FrontierHeader, rlp_string: str):
"""Check that rlp encoding of block header match header object"""
"""Check that rlp encoding of block header match header object."""
rlp = rlp_decode(bytes.fromhex(rlp_string[2:]))[0]
for rlp_index, (field_name, field) in enumerate(header.get_field_rlp_order().items()):
rlp_hex = rlp[rlp_index].hex()
Expand Down
14 changes: 4 additions & 10 deletions src/ethereum_test_fixtures/schemas/blockchain/test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Schema for filled Blockchain Test
"""
"""Schema for filled Blockchain Test."""

from typing import Tuple

Expand All @@ -25,9 +23,7 @@


class BlockchainTestFixtureModel(BaseModel):
"""
Blockchain test file
"""
"""Blockchain test file."""

info: dict = Field(alias="_info")
network: str
Expand All @@ -40,15 +36,13 @@ class BlockchainTestFixtureModel(BaseModel):
sealEngine: str # noqa: N815

class Config:
"""Forbids any extra fields that are not declared in the model"""
"""Forbids any extra fields that are not declared in the model."""

extra = "forbid"

@model_validator(mode="after")
def check_block_headers(self):
"""
Validate genesis header fields based by fork
"""
"""Validate genesis header fields based by fork."""
# TODO str to Fork class comparison
allowed_networks: dict[str, Tuple[FrontierHeader, BlockRecord]] = {
"Frontier": (FrontierHeader, BlockRecord),
Expand Down
20 changes: 7 additions & 13 deletions src/ethereum_test_fixtures/schemas/common/types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Base types for Pydantic json test fixtures
"""
"""Base types for Pydantic json test fixtures."""

import re

Expand All @@ -14,9 +12,7 @@ class FixedHash(RootModel[str]):

@model_validator(mode="after")
def validate_hex_hash(self):
"""
Validate that the field is a 0x-prefixed hash of specified byte length.
"""
"""Validate that the field is a 0x-prefixed hash of specified byte length."""
expected_length = 2 + 2 * self._length_in_bytes # 2 for '0x' + 2 hex chars per byte
if not self.root.startswith("0x"):
raise ValueError("The hash must start with '0x'.")
Expand All @@ -34,25 +30,25 @@ def validate_hex_hash(self):


class FixedHash32(FixedHash):
"""FixedHash32 type (32 bytes)"""
"""FixedHash32 type (32 bytes)."""

_length_in_bytes = 32


class FixedHash20(FixedHash):
"""FixedHash20 type (20 bytes)"""
"""FixedHash20 type (20 bytes)."""

_length_in_bytes = 20


class FixedHash8(FixedHash):
"""FixedHash8 type (8 bytes)"""
"""FixedHash8 type (8 bytes)."""

_length_in_bytes = 8


class FixedHash256(FixedHash):
"""FixedHash256 type (256 bytes)"""
"""FixedHash256 type (256 bytes)."""

_length_in_bytes = 256

Expand All @@ -61,9 +57,7 @@ class PrefixedEvenHex(RootModel[str]):
"""Class to validate a hexadecimal integer encoding in test files."""

def __eq__(self, other):
"""
For python str comparison
"""
"""For python str comparison."""
if isinstance(other, str):
return self.root == other
return NotImplemented
Expand Down
2 changes: 1 addition & 1 deletion src/ethereum_test_fixtures/verify.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Ethereum test fixture verifyer abstract class."""
"""Ethereum test fixture verifier abstract class."""

from abc import ABC, abstractmethod
from pathlib import Path
Expand Down
15 changes: 5 additions & 10 deletions src/ethereum_test_fixtures/verify_format.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,25 @@
"""
Verify the sanity of fixture .json format
"""
"""Verify the sanity of fixture .json format."""

from pydantic import ValidationError

from .schemas.blockchain.test import BlockchainTestFixtureModel


class VerifyFixtureJson:
"""
Class to verify the correctness of a fixture JSON.
"""
"""Class to verify the correctness of a fixture JSON."""

def __init__(self, name: str, fixture_json: dict):
"""Verify generated fixture .json file format."""
self.fixture_json = fixture_json
self.fixture_name = name
if self.fixture_json.get("network") and not self.fixture_json.get("engineNewPayloads"):
self.verify_blockchain_fixture_json()

def verify_blockchain_fixture_json(self):
"""
Function to verify blockchain json fixture
"""
"""Verify blockchain json test format."""
try:
BlockchainTestFixtureModel(**self.fixture_json)
except ValidationError as e:
raise Exception(
f"Error in generated blockchain test json ({self.fixture_name})" + e.json()
)
) from ValidationError

0 comments on commit 04d3ffd

Please sign in to comment.