From 89649f90b347e8812fd9e0d5bb4cd56c5fc3c862 Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 20 Aug 2026 14:13:56 +0200 Subject: [PATCH 01/13] feat(BACK-12243): generate calldata descriptors for ERC-7730 v2 EIP-712 messages --- src/erc7730/common/abi.py | 19 ++ .../convert_erc7730_v2_input_to_calldata.py | 201 +++++++++++++++-- .../convert/calldata/v1/eip712_path.py | 166 ++++++++++++++ .../convert/calldata/v1/eip712_schema.py | 188 ++++++++++++++++ src/erc7730/convert/calldata/v1/map.py | 27 +-- src/erc7730/convert/calldata/v1/path.py | 9 + src/erc7730/convert/calldata/v1/tlv.py | 190 +++++++++++++++- src/erc7730/lint/v2/lint_validate_map_keys.py | 9 +- src/erc7730/model/calldata/__init__.py | 19 +- src/erc7730/model/calldata/descriptor.py | 9 +- src/erc7730/model/calldata/v1/descriptor.py | 66 ++++++ src/erc7730/model/calldata/v1/eip712.py | 108 ++++++++++ src/erc7730/model/calldata/v1/instruction.py | 50 ++++- src/erc7730/model/calldata/v1/value.py | 87 +++++++- .../convert/calldata/test_convert_eip712.py | 202 ++++++++++++++++++ 15 files changed, 1289 insertions(+), 61 deletions(-) create mode 100644 src/erc7730/convert/calldata/v1/eip712_path.py create mode 100644 src/erc7730/convert/calldata/v1/eip712_schema.py create mode 100644 src/erc7730/model/calldata/v1/eip712.py create mode 100644 tests/v2/convert/calldata/test_convert_eip712.py diff --git a/src/erc7730/common/abi.py b/src/erc7730/common/abi.py index 1c496725..84a6aa1c 100644 --- a/src/erc7730/common/abi.py +++ b/src/erc7730/common/abi.py @@ -187,6 +187,25 @@ def parse_encode_type(encode_type: str) -> tuple[str, dict[str, list[tuple[str, return primary_type, types +def to_encode_type(primary_type: str, types: dict[str, list[tuple[str, str]]]) -> str: + """Build the canonical EIP-712 ``encodeType`` string for a primary type. + + Per EIP-712, the primary type is encoded first, followed by all referenced struct types sorted alphabetically by + name. This is the inverse of :func:`parse_encode_type` and normalizes the ordering of the input. + + :param primary_type: the primary (root) struct type name + :param types: struct name -> ordered list of (type, name) field tuples, including the primary type + :return: the canonical ``encodeType`` string + :raises KeyError: if ``primary_type`` is not present in ``types`` + """ + + def encode_one(name: str) -> str: + return f"{name}(" + ",".join(f"{typ} {field_name}" for typ, field_name in types[name]) + ")" + + dependencies = sorted(name for name in types if name != primary_type) + return encode_one(primary_type) + "".join(encode_one(name) for name in dependencies) + + class ABIDataType(StrEnum): """Solidity data type.""" diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index c769958c..372acaca 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -22,10 +22,13 @@ from erc7730.common.ledger import ledger_network_id from erc7730.common.options import first_not_none from erc7730.common.output import ConsoleOutputAdder, OutputAdder, exception_to_output -from erc7730.convert.calldata.v1.abi import ABITree, function_to_abi_tree +from erc7730.convert.calldata.v1.abi import function_to_abi_tree +from erc7730.convert.calldata.v1.eip712_path import convert_eip712_data_path +from erc7730.convert.calldata.v1.eip712_schema import ReconstructedSchema, reconstruct_schema from erc7730.convert.calldata.v1.enum import convert_enums from erc7730.convert.calldata.v1.map import MapEntries from erc7730.convert.calldata.v1.path import ( + DataPathConverter, convert_container_path, convert_data_path, ) @@ -36,12 +39,17 @@ from erc7730.model.abi import Function from erc7730.model.calldata.descriptor import ( CalldataDescriptor, + CalldataDescriptorEIP712V1, CalldataDescriptorV1, ) from erc7730.model.calldata.types import TrustedNameSource, TrustedNameType +from erc7730.model.calldata.v1.eip712 import ( + CalldataDescriptorInstructionEIP712SchemaV1, +) from erc7730.model.calldata.v1.instruction import ( MAX_FIELD_CONSTRAINTS, CalldataDescriptorFieldVisibilityV1, + CalldataDescriptorInstructionEIP712MessageInfoV1, CalldataDescriptorInstructionFieldV1, CalldataDescriptorInstructionTransactionInfoV1, ) @@ -71,7 +79,7 @@ CalldataDescriptorValueV1, ) from erc7730.model.display import AddressNameType -from erc7730.model.input.v2.context import InputContractContext +from erc7730.model.input.v2.context import InputContractContext, InputEIP712Context from erc7730.model.input.v2.descriptor import InputERC7730Descriptor from erc7730.model.input.v2.format import DateEncoding, FieldFormat from erc7730.model.paths import ContainerField, ContainerPath, DataPath @@ -80,6 +88,7 @@ from erc7730.model.resolved.v2.context import ( ResolvedContractContext, ResolvedDeployment, + ResolvedEIP712Context, ) from erc7730.model.resolved.v2.descriptor import ResolvedERC7730Descriptor from erc7730.model.resolved.v2.display import ( @@ -139,6 +148,9 @@ def erc7730_v2_descriptor_to_calldata_descriptors( out = ConsoleOutputAdder() if out is None else out try: + if isinstance(input_descriptor.context, InputEIP712Context): + return _convert_eip712_descriptors(input_descriptor, source, chain_id, out) + if not isinstance(input_descriptor.context, InputContractContext): return [] @@ -236,6 +248,9 @@ def _convert_v2_selector( """ abi_tree = function_to_abi_tree(abi) + def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorValuePathV1 | None: + return convert_data_path(data_path, abi_tree, out) + creator_legal_name: str | None = None creator_url: str | None = None deploy_date: str | None = None @@ -256,7 +271,9 @@ def _convert_v2_selector( fields: list[CalldataDescriptorInstructionFieldV1] = [] for input_field in format.fields: if ( - output_fields := _convert_v2_field(abi=abi_tree, field=input_field, enums=enums_by_id, maps=maps, out=out) + output_fields := _convert_v2_field( + convert_path=convert_path, field=input_field, enums=enums_by_id, maps=maps, out=out + ) ) is None: return None fields.extend(output_fields) @@ -295,7 +312,7 @@ def _convert_v2_selector( def _convert_v2_field( - abi: ABITree, + convert_path: DataPathConverter, field: ResolvedFieldDescription | ResolvedFieldGroup, enums: dict[str, int], maps: MapEntries, @@ -313,7 +330,7 @@ def _convert_v2_field( matches no constraint). Only the ``RAW`` and ``TRUSTED_NAME`` parameter types honour these tags, so they are rejected on any other format rather than emitted and ignored by the device. - :param abi: function ABI tree + :param convert_path: strategy converting a resolved data path to a calldata value (ABI or EIP-712 navigation) :param field: v2 resolved field :param enums: mapping of source descriptor enum ids to calldata descriptor enum ids :param maps: device side maps of the descriptor, map lookups are registered in it @@ -345,7 +362,9 @@ def _convert_v2_field( ) name = field.id or "constraint" - if (param := _convert_v2_param(abi=abi, field=field, enums=enums, maps=maps, out=out)) is None: + if ( + param := _convert_v2_param(convert_path=convert_path, field=field, enums=enums, maps=maps, out=out) + ) is None: return None # Constraints are compared by the parameter formatter, so they are encoded against the type @@ -387,11 +406,15 @@ def _convert_v2_field( CalldataDescriptorInstructionFieldV1(name=name, param=param, visibility=visibility, constraints=constraints) ] elif isinstance(field, ResolvedFieldGroup): - # In v1 protocol, nested fields are flattened + # TODO the protocol defines a PARAM_GROUP struct (with ITERATION_TYPE) for nested fields; for now nested + # fields are flattened, matching the existing v1 contract behavior. Revisit once PARAM_GROUP device + # semantics (notably BUNDLED iteration) are finalized in the Ethereum app specifications. instructions: list[CalldataDescriptorInstructionFieldV1] = [] for nested_field in field.fields: if ( - nested_instructions := _convert_v2_field(abi=abi, field=nested_field, enums=enums, maps=maps, out=out) + nested_instructions := _convert_v2_field( + convert_path=convert_path, field=nested_field, enums=enums, maps=maps, out=out + ) ) is None: return None instructions.extend(nested_instructions) @@ -613,7 +636,7 @@ def _convert_v2_value( path_str: str | None, value: ScalarType | None, format_type: FieldFormat | None, - abi: ABITree, + convert_path: DataPathConverter, out: OutputAdder, ) -> CalldataDescriptorValueV1 | None: """ @@ -625,7 +648,7 @@ def _convert_v2_value( :param path_str: v2 resolved path string (e.g. "#.amount", "@.from") :param value: v2 resolved constant value :param format_type: field format type - :param abi: function ABI tree + :param convert_path: strategy converting a resolved data path to a calldata value :param out: error handler :return: calldata protocol value or None on error """ @@ -641,7 +664,7 @@ def _convert_v2_value( if isinstance(parsed_path, ContainerPath): return convert_container_path(parsed_path, out) elif isinstance(parsed_path, DataPath): - return convert_data_path(parsed_path, abi, out) + return convert_path(parsed_path, out) else: return out.error( title="Unsupported path type", @@ -695,7 +718,7 @@ def _format_to_abi_type(format_type: FieldFormat | None) -> ABIDataType: def _convert_v2_param( - abi: ABITree, + convert_path: DataPathConverter, field: ResolvedFieldDescription, enums: dict[str, int], maps: MapEntries, @@ -706,7 +729,7 @@ def _convert_v2_param( This mirrors the v1 convert_param logic but works with v2 resolved types. - :param abi: function ABI tree + :param convert_path: strategy converting a resolved data path to a calldata value (ABI or EIP-712 navigation) :param field: v2 resolved field description :param enums: mapping of source descriptor enum ids to calldata descriptor enum ids :param maps: device side maps of the descriptor, map lookups the device has to do are registered in it @@ -714,7 +737,7 @@ def _convert_v2_param( :return: calldata protocol field parameter or None on error """ path_str = str(field.path) if field.path is not None else None - if (value := _convert_v2_value(path_str, field.value, field.format, abi, out)) is None: + if (value := _convert_v2_value(path_str, field.value, field.format, convert_path, out)) is None: return None def _deployment_map_key(value_map: ResolvedValueMap) -> str | None: @@ -767,12 +790,12 @@ def _convert_resolved_value( # contract address resolves to a constant, other keys are only known when the transaction is signed and # the device looks the value up in the map entries provided with the descriptor if (key := _deployment_map_key(resolved_value)) is None: - return maps.map_ref(resolved_value, abi_type, abi, out) + return maps.map_ref(resolved_value, abi_type, convert_path, out) if (map_value := _lookup_deployment_value(resolved_value, key)) is None: return None resolved_value = map_value if isinstance(resolved_value, ResolvedValuePath): - return _convert_v2_value(str(resolved_value.path), None, None, abi, out) + return _convert_v2_value(str(resolved_value.path), None, None, convert_path, out) if isinstance(resolved_value, ResolvedValueConstant): raw = encode_value(resolved_value.value, abi_type, out) if raw is None: @@ -1001,3 +1024,149 @@ def _convert_resolved_value( title="Unsupported format", message=f"Field format '{field.format}' is not supported for calldata conversion.", ) + + +# --- EIP-712 message conversion ("EIP712 v2" in the Ethereum app specifications) --- + + +def _convert_eip712_descriptors( + input_descriptor: InputERC7730Descriptor, + source: HttpUrl | None, + chain_id: int | None, + out: OutputAdder, +) -> list[CalldataDescriptor]: + """ + Generate calldata descriptors for a v2 input ERC-7730 descriptor with EIP-712 context. + + Unlike the contract binding (which navigates serialized calldata via the ABI), the EIP-712 binding reconstructs + the message schema from the ``display.formats`` encodeType keys and navigates the message value tree. + + :param input_descriptor: deserialized v2 input ERC-7730 descriptor with EIP-712 context + :param source: source of the descriptor file + :param chain_id: if set, only emit descriptors for the given chain id + :param out: error handler + :return: output calldata descriptors (1 per chain + message primary type) + """ + context = input_descriptor.context + if not isinstance(context, InputEIP712Context): + return [] + + if chain_id is not None: + deployment_chain_ids = {d.chainId for d in context.eip712.deployments} + if chain_id not in deployment_chain_ids: + return [] + + if (resolved_descriptor := ERC7730InputToResolved().convert(input_descriptor, out)) is None: + return [] + + resolved_context = cast(ResolvedEIP712Context, resolved_descriptor.context) + domain = resolved_context.eip712.domain + has_deployments = len(resolved_context.eip712.deployments) > 0 + + output_descriptors: list[CalldataDescriptor] = [] + + for deployment in resolved_context.eip712.deployments: + if chain_id is not None and chain_id != deployment.chainId: + continue + + if ledger_network_id(deployment.chainId) is None: + out.warning(f"Chain id {deployment.chainId} is not known, skipping it") + continue + + for encode_type_key, format in resolved_descriptor.display.formats.items(): + schema = reconstruct_schema(str(encode_type_key), domain, has_deployments, out) + if schema is None: + continue + + descriptor = _convert_eip712_message( + descriptor=resolved_descriptor, + deployment=deployment, + schema=schema, + format=format, + source=source, + out=out, + ) + + if descriptor is not None: + output_descriptors.append(descriptor) + + return output_descriptors + + +def _convert_eip712_message( + descriptor: ResolvedERC7730Descriptor, + deployment: ResolvedDeployment, + schema: ReconstructedSchema, + format: ResolvedFormat, + source: HttpUrl | None, + out: OutputAdder, +) -> CalldataDescriptor | None: + """ + Generate a calldata descriptor for a single EIP-712 message primary type. + + :param descriptor: resolved v2 source ERC-7730 descriptor + :param deployment: chain id / verifying contract address for which the descriptor is generated + :param schema: reconstructed EIP-712 schema (structs + primary type hash) + :param format: v2 resolved format for the message + :param source: source of the descriptor file + :param out: error handler + :return: output calldata descriptor or None if invalid + """ + + def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorValuePathV1 | None: + return convert_eip712_data_path(data_path, schema.primary_type, schema.types, out) + + creator_legal_name: str | None = None + creator_url: str | None = None + deploy_date: str | None = None + if descriptor.metadata.info is not None: + creator_legal_name = descriptor.metadata.owner + creator_url = str(descriptor.metadata.info.url) if descriptor.metadata.info.url else None + deploy_date = ( + descriptor.metadata.info.deploymentDate.strftime("%Y-%m-%dT%H:%M:%SZ") + if descriptor.metadata.info.deploymentDate + else None + ) + + # TODO the ENUM_VALUE struct carries a SELECTOR tag whose meaning for EIP-712 messages is not defined in the + # specification; a zeroed selector is used until it is clarified. + enum_selector = Selector("0x00000000") + enums = convert_enums(deployment, enum_selector, descriptor.metadata.enums) # type: ignore[arg-type] + enums_by_id = {enum.enum_id: enum.id for enum in enums} + + fields: list[CalldataDescriptorInstructionFieldV1] = [] + for input_field in format.fields: + if (output_fields := _convert_v2_field(convert_path, input_field, enums_by_id, out)) is None: + return None + fields.extend(output_fields) + + hash = hashlib.sha3_256() + for field in fields: + hash.update(from_hex(field.descriptor)) + + schema_info = CalldataDescriptorInstructionEIP712SchemaV1(structs=schema.structs) + + message_info = CalldataDescriptorInstructionEIP712MessageInfoV1( + chain_id=deployment.chainId, + address=deployment.address, + primary_type_hash=schema.primary_type_hash, + hash=hash.digest().hex(), + operation_type=first_not_none(format.intent, format.id, schema.primary_type), # type: ignore[arg-type] + creator_name=descriptor.metadata.owner, + creator_legal_name=creator_legal_name, + creator_url=creator_url, + contract_name=descriptor.metadata.contractName or descriptor.context.id, + deploy_date=deploy_date, + ) + + return CalldataDescriptorEIP712V1( + source=source, + network=cast(str, ledger_network_id(deployment.chainId)), + chain_id=deployment.chainId, + address=deployment.address, + primary_type_hash=schema.primary_type_hash, + schema_info=schema_info, + message_info=message_info, + enums=enums, + fields=fields, + ) diff --git a/src/erc7730/convert/calldata/v1/eip712_path.py b/src/erc7730/convert/calldata/v1/eip712_path.py new file mode 100644 index 00000000..4af27ba2 --- /dev/null +++ b/src/erc7730/convert/calldata/v1/eip712_path.py @@ -0,0 +1,166 @@ +""" +Conversion of ERC-7730 v2 EIP-712 data paths to calldata descriptor EIP712_PATH binary paths. + +Unlike DATA_PATH (which navigates serialized calldata by byte offsets using the ABI), EIP712_PATH navigates the +EIP-712 value tree by struct field index and array slices, using the reconstructed schema. Referred to as +"EIP712 v2" in the Ethereum app specifications. +""" + +from erc7730.common.output import OutputAdder +from erc7730.convert.calldata.v1.eip712_schema import ParsedSolidityType, parse_solidity_type +from erc7730.model.calldata.v1.eip712 import CalldataDescriptorEIP712SolType +from erc7730.model.calldata.v1.value import ( + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementStructFieldV1, + CalldataDescriptorEIP712PathElementV1, + CalldataDescriptorEIP712PathV1, + CalldataDescriptorTypeFamily, + CalldataDescriptorValuePathV1, +) +from erc7730.model.paths import ( + Array, + ArrayElement, + ArraySlice, + DataPath, + Field, +) + +_SOL_TYPE_TO_FAMILY: dict[CalldataDescriptorEIP712SolType, CalldataDescriptorTypeFamily] = { + CalldataDescriptorEIP712SolType.UINT: CalldataDescriptorTypeFamily.UINT, + CalldataDescriptorEIP712SolType.INT: CalldataDescriptorTypeFamily.INT, + CalldataDescriptorEIP712SolType.ADDRESS: CalldataDescriptorTypeFamily.ADDRESS, + CalldataDescriptorEIP712SolType.BOOL: CalldataDescriptorTypeFamily.BOOL, + CalldataDescriptorEIP712SolType.STRING: CalldataDescriptorTypeFamily.STRING, + CalldataDescriptorEIP712SolType.BYTES_FIX: CalldataDescriptorTypeFamily.BYTES, + CalldataDescriptorEIP712SolType.BYTES_DYN: CalldataDescriptorTypeFamily.BYTES, +} + + +def _leaf_type_family_size(parsed: ParsedSolidityType) -> tuple[CalldataDescriptorTypeFamily, int | None]: + """Determine the VALUE type family and size (in bytes) from the leaf Solidity type.""" + match parsed.sol_type: + case CalldataDescriptorEIP712SolType.ADDRESS: + return CalldataDescriptorTypeFamily.ADDRESS, 20 + case CalldataDescriptorEIP712SolType.BOOL: + return CalldataDescriptorTypeFamily.BOOL, 1 + case CalldataDescriptorEIP712SolType.UINT | CalldataDescriptorEIP712SolType.INT: + return _SOL_TYPE_TO_FAMILY[parsed.sol_type], parsed.type_size + case CalldataDescriptorEIP712SolType.BYTES_FIX: + return CalldataDescriptorTypeFamily.BYTES, parsed.type_size + case CalldataDescriptorEIP712SolType.BYTES_DYN | CalldataDescriptorEIP712SolType.STRING: + return _SOL_TYPE_TO_FAMILY[parsed.sol_type], None + case _: + return CalldataDescriptorTypeFamily.BYTES, None + + +def convert_eip712_data_path( + data_path: DataPath, + primary_type: str, + types: dict[str, list[tuple[str, str]]], + out: OutputAdder, +) -> CalldataDescriptorValuePathV1 | None: + """ + Convert an EIP-712 data path to a calldata descriptor EIP712_PATH value. + + :param data_path: resolved data path (referencing the EIP-712 value tree) + :param primary_type: the message primary type (root struct the path starts from) + :param types: struct name -> ordered list of (type string, field name) + :param out: error handler + :return: calldata value, or None on error + """ + elements: list[CalldataDescriptorEIP712PathElementV1] = [] + current_struct: str = primary_type + current_parsed: ParsedSolidityType | None = None + remaining_dims = 0 + + for element in data_path.elements: + match element: + case Field(identifier=name): + if current_parsed is not None: + if remaining_dims != 0: + return out.error( + title="Invalid EIP-712 path", + message=f'Array of "{current_struct}" not fully indexed before descending into "{name}".', + ) + if current_parsed.sol_type != CalldataDescriptorEIP712SolType.STRUCT or ( + current_parsed.struct_name is None + ): + return out.error( + title="Invalid EIP-712 path", + message=f'Cannot descend into field "{name}" of a non-struct type.', + ) + current_struct = current_parsed.struct_name + + struct_fields = types.get(current_struct) + if struct_fields is None: + return out.error( + title="Invalid EIP-712 path", + message=f'Unknown struct type "{current_struct}" in EIP-712 schema.', + ) + + index = next((i for i, (_, field_name) in enumerate(struct_fields) if field_name == name), None) + if index is None: + return out.error( + title="Invalid EIP-712 path", + message=f'Field "{name}" not found in struct "{current_struct}".', + ) + + elements.append(CalldataDescriptorEIP712PathElementStructFieldV1(index=index)) + current_parsed = parse_solidity_type(struct_fields[index][0]) + remaining_dims = len(current_parsed.array_dimensions) + + case Array(): + if remaining_dims <= 0: + return out.error( + title="Invalid EIP-712 path", + message="Array selector applied to a non-array value.", + ) + elements.append(CalldataDescriptorEIP712PathElementArraySliceV1()) + remaining_dims -= 1 + + case ArrayElement(index=array_index): + if remaining_dims <= 0: + return out.error( + title="Invalid EIP-712 path", + message="Array index applied to a non-array value.", + ) + # a single element [i] is a slice [i, i+1); for i == -1, end defaults to the array length + end = None if array_index == -1 else array_index + 1 + elements.append(CalldataDescriptorEIP712PathElementArraySliceV1(start=array_index, end=end)) + remaining_dims -= 1 + + case ArraySlice(start=start, end=end): + if remaining_dims <= 0: + return out.error( + title="Invalid EIP-712 path", + message="Array slice applied to a non-array value.", + ) + elements.append(CalldataDescriptorEIP712PathElementArraySliceV1(start=start, end=end)) + remaining_dims -= 1 + + if current_parsed is None: + return out.error( + title="Invalid EIP-712 path", + message="EIP-712 path does not reference any field.", + ) + + if remaining_dims != 0: + return out.error( + title="Invalid EIP-712 path", + message="EIP-712 path ends on an incompletely indexed array; a scalar leaf is required.", + ) + + if current_parsed.sol_type == CalldataDescriptorEIP712SolType.STRUCT: + return out.error( + title="Invalid EIP-712 path", + message=f'EIP-712 path ends on struct "{current_parsed.struct_name}"; a scalar leaf is required.', + ) + + type_family, type_size = _leaf_type_family_size(current_parsed) + + return CalldataDescriptorValuePathV1( + type_family=type_family, + type_size=type_size, + abi_path=data_path, + binary_path=CalldataDescriptorEIP712PathV1(elements=elements), + ) diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py new file mode 100644 index 00000000..7b15e1ce --- /dev/null +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -0,0 +1,188 @@ +""" +Reconstruction of EIP-712 schema (EIP712_SCHEMA struct) from ERC-7730 v2 ``display.formats`` keys. + +In ERC-7730 v2, the ``display.formats`` keys are EIP-712 ``encodeType`` strings (e.g. +``Order(address owner,Bridge bridge)Bridge(bytes4 sel,uint256 chainId)``) from which the whole schema can be +rebuilt. The ``EIP712Domain`` type is reconstructed separately from the descriptor domain / deployment information. + +Referred to as "EIP712 v2" in the Ethereum app specifications (https://github.com/LedgerHQ/app-ethereum). +""" + +import re +from dataclasses import dataclass, field + +from eth_utils import keccak + +from erc7730.common.abi import parse_encode_type, to_encode_type +from erc7730.common.output import OutputAdder +from erc7730.model.calldata.v1.eip712 import ( + CalldataDescriptorEIP712FieldV1, + CalldataDescriptorEIP712SolType, + CalldataDescriptorEIP712StructV1, +) +from erc7730.model.resolved.v2.context import ResolvedDomain +from erc7730.model.types import HexStr + + +@dataclass(frozen=True) +class ParsedSolidityType: + """A Solidity type parsed into its base type, size and array dimensions.""" + + sol_type: CalldataDescriptorEIP712SolType + type_size: int | None + array_dimensions: list[int | None] # innermost first, None = dynamic dimension + struct_name: str | None + + +@dataclass(frozen=True) +class ReconstructedSchema: + """A reconstructed EIP-712 schema for a single message primary type.""" + + primary_type: str + primary_type_hash: HexStr + # struct name -> ordered list of (type string, field name), including EIP712Domain + types: dict[str, list[tuple[str, str]]] = field(default_factory=dict) + structs: list[CalldataDescriptorEIP712StructV1] = field(default_factory=list) + + +def parse_solidity_type(type_str: str) -> ParsedSolidityType: + """ + Parse a Solidity type string into base type, size and array dimensions. + + :param type_str: a Solidity type (e.g. ``uint256``, ``bytes32``, ``address[3][]``, ``Person``) + :return: the parsed type + """ + base = type_str + dimensions: list[int | None] = [] + while base.endswith("]"): + open_index = base.rfind("[") + inner = base[open_index + 1 : -1] + dimensions.append(int(inner) if inner else None) + base = base[:open_index] + # collected outermost first, but the spec wants innermost first + dimensions.reverse() + + sol_type: CalldataDescriptorEIP712SolType + type_size: int | None = None + struct_name: str | None = None + + if (match := re.fullmatch(r"uint(\d*)", base)) is not None: + sol_type = CalldataDescriptorEIP712SolType.UINT + type_size = (int(match.group(1)) if match.group(1) else 256) // 8 + elif (match := re.fullmatch(r"int(\d*)", base)) is not None: + sol_type = CalldataDescriptorEIP712SolType.INT + type_size = (int(match.group(1)) if match.group(1) else 256) // 8 + elif base == "address": + sol_type = CalldataDescriptorEIP712SolType.ADDRESS + elif base == "bool": + sol_type = CalldataDescriptorEIP712SolType.BOOL + elif base == "string": + sol_type = CalldataDescriptorEIP712SolType.STRING + elif base == "bytes": + sol_type = CalldataDescriptorEIP712SolType.BYTES_DYN + elif (match := re.fullmatch(r"bytes(\d+)", base)) is not None: + sol_type = CalldataDescriptorEIP712SolType.BYTES_FIX + type_size = int(match.group(1)) + else: + # TODO fixed/ufixed Solidity types are not handled (rare in EIP-712); anything else is treated as a struct + sol_type = CalldataDescriptorEIP712SolType.STRUCT + struct_name = base + + return ParsedSolidityType( + sol_type=sol_type, type_size=type_size, array_dimensions=dimensions, struct_name=struct_name + ) + + +def _reconstruct_domain_fields(domain: ResolvedDomain | None, has_deployments: bool) -> list[tuple[str, str]]: + """ + Reconstruct the ``EIP712Domain`` type fields, in canonical EIP-712 order. + + :param domain: the resolved domain, or None + :param has_deployments: whether the descriptor declares deployments (implying chainId + verifyingContract) + :return: ordered list of (type string, field name) + """ + # append order is load-bearing: it must follow the canonical EIP-712 domain field order + # (name, version, chainId, verifyingContract, salt), as it determines the reconstructed EIP712Domain type hash. + fields: list[tuple[str, str]] = [] + if domain is not None and domain.name is not None: + fields.append(("string", "name")) + if domain is not None and domain.version is not None: + fields.append(("string", "version")) + # chainId / verifyingContract belong to the domain type when the domain declares them explicitly; when it omits + # them but deployments are declared, they are still part of the signed domain (implied by the deployment). + if (domain is not None and domain.chainId is not None) or has_deployments: + fields.append(("uint256", "chainId")) + if (domain is not None and domain.verifyingContract is not None) or has_deployments: + fields.append(("address", "verifyingContract")) + if domain is not None and domain.salt is not None: + fields.append(("bytes32", "salt")) + return fields + + +def _build_struct(name: str, type_fields: list[tuple[str, str]]) -> CalldataDescriptorEIP712StructV1: + """Build an EIP712_STRUCT descriptor from a struct name and its (type, name) fields.""" + fields: list[CalldataDescriptorEIP712FieldV1] = [] + for type_str, field_name in type_fields: + parsed = parse_solidity_type(type_str) + fields.append( + CalldataDescriptorEIP712FieldV1( + name=field_name, + sol_type=parsed.sol_type, + type_size=parsed.type_size, + array_dimensions=parsed.array_dimensions, + struct_name=parsed.struct_name, + ) + ) + return CalldataDescriptorEIP712StructV1(name=name, fields=fields) + + +def reconstruct_schema( + encode_type_key: str, + domain: ResolvedDomain | None, + has_deployments: bool, + out: OutputAdder, +) -> ReconstructedSchema | None: + """ + Reconstruct an EIP-712 schema from an ``encodeType`` format key and the descriptor domain / deployment info. + + :param encode_type_key: an ``encodeType`` string from ``display.formats`` + :param domain: the resolved EIP-712 domain + :param has_deployments: whether the descriptor declares deployments + :param out: error handler + :return: the reconstructed schema, or None on error + """ + if encode_type_key.startswith("0x"): + return out.error( + title="Unsupported format key", + message=f"Format key '{encode_type_key}' is already a hash, cannot reconstruct EIP-712 schema.", + ) + + try: + primary_type, raw_types = parse_encode_type(encode_type_key) + except ValueError as e: + return out.error( + title="Invalid encodeType", + message=f"Failed to parse format key as encodeType: {e}", + ) + + types: dict[str, list[tuple[str, str]]] = {} + structs: list[CalldataDescriptorEIP712StructV1] = [] + + domain_fields = _reconstruct_domain_fields(domain, has_deployments) + types["EIP712Domain"] = domain_fields + structs.append(_build_struct("EIP712Domain", domain_fields)) + + for type_name, type_fields in raw_types.items(): + types[type_name] = type_fields + structs.append(_build_struct(type_name, type_fields)) + + # PRIMARY_TYPE_HASH = keccak256(encodeType(primaryType)); normalize to canonical order so the hash does not + # depend on the ordering of the source format key + primary_type_hash = HexStr("0x" + keccak(text=to_encode_type(primary_type, raw_types)).hex()) + + return ReconstructedSchema( + primary_type=primary_type, + primary_type_hash=primary_type_hash, + types=types, + structs=structs, + ) diff --git a/src/erc7730/convert/calldata/v1/map.py b/src/erc7730/convert/calldata/v1/map.py index ea4136cd..b7d85d91 100644 --- a/src/erc7730/convert/calldata/v1/map.py +++ b/src/erc7730/convert/calldata/v1/map.py @@ -18,8 +18,7 @@ from erc7730.common.abi import ABIDataType from erc7730.common.binary import from_hex from erc7730.common.output import OutputAdder -from erc7730.convert.calldata.v1.abi import ABITree -from erc7730.convert.calldata.v1.path import convert_container_path, convert_data_path +from erc7730.convert.calldata.v1.path import DataPathConverter, convert_container_path from erc7730.convert.calldata.v1.tlv import tlv_value from erc7730.model.calldata.v1.instruction import MAX_MAP_ENTRY_SIZE, CalldataDescriptorInstructionMapEntryV1 from erc7730.model.calldata.v1.value import ( @@ -78,7 +77,7 @@ def map_ref( self, value_map: ResolvedValueMap, abi_type: ABIDataType, - abi: ABITree, + convert_path: DataPathConverter, out: OutputAdder, ) -> CalldataDescriptorValueMapRefV1 | None: """ @@ -86,13 +85,13 @@ def map_ref( :param value_map: resolved map lookup :param abi_type: data type the map values are encoded with - :param abi: function ABI tree + :param convert_path: strategy converting the key data path to a calldata value :param out: error handler :return: MAP_REF value, or None on error """ map_name = str(value_map.map) - if (encoded_keys := encode_map_keys(value_map, abi, out)) is None: + if (encoded_keys := encode_map_keys(value_map, convert_path, out)) is None: return None key, keys_bytes = encoded_keys @@ -142,20 +141,20 @@ def map_ref( def encode_map_keys( - value_map: ResolvedValueMap, abi: ABITree, out: OutputAdder + value_map: ResolvedValueMap, convert_path: DataPathConverter, out: OutputAdder ) -> tuple[CalldataDescriptorValuePathV1, dict[str, bytes]] | None: """ Convert the key path of a map lookup to the value the device reads the key from, and encode the map keys the way the device reads that value. :param value_map: resolved map lookup - :param abi: function ABI tree + :param convert_path: strategy converting the key data path to a calldata value :param out: error handler :return: value the device reads the key from, and encoded keys indexed by source key, or None on error """ map_name = str(value_map.map) - if (key := _convert_key_path(value_map, abi, out)) is None: + if (key := _convert_key_path(value_map, convert_path, out)) is None: return None if len(tlv_value(key)) > MAP_REF_KEY_MAX_SIZE: @@ -188,7 +187,7 @@ def encode_map_keys( def _convert_key_path( - value_map: ResolvedValueMap, abi: ABITree, out: OutputAdder + value_map: ResolvedValueMap, convert_path: DataPathConverter, out: OutputAdder ) -> CalldataDescriptorValuePathV1 | None: """Convert the key path of a map lookup to the value the device reads the key from.""" match value_map.keyPath: @@ -196,10 +195,14 @@ def _convert_key_path( return convert_container_path(container_path, out) case DataPath() as data_path: - if (key := convert_data_path(data_path, abi, out)) is None: + if (key := convert_path(data_path, out)) is None: return None - assert isinstance(key.binary_path, CalldataDescriptorDataPathV1) # nosec B101 - data path converts to one - + if not isinstance(key.binary_path, CalldataDescriptorDataPathV1): + return out.error( + title="Unsupported map key", + message=f"Path {data_path} used as key of map {value_map.map} cannot be looked up by the " + "device: maps are only supported on transaction fields.", + ) # the device looks up a single key: it rejects a path reading several values for element in key.binary_path.elements: if isinstance(element, CalldataDescriptorPathElementArrayV1) and not _is_single_element(element): diff --git a/src/erc7730/convert/calldata/v1/path.py b/src/erc7730/convert/calldata/v1/path.py index a90b5b9f..e2b319bd 100644 --- a/src/erc7730/convert/calldata/v1/path.py +++ b/src/erc7730/convert/calldata/v1/path.py @@ -2,6 +2,7 @@ Conversion of ERC-7730 ABI paths to calldata descriptor binary paths. """ +from collections.abc import Callable from typing import Any, assert_never from erc7730.common.binary import from_hex @@ -18,6 +19,7 @@ CalldataDescriptorContainerPathV1, CalldataDescriptorContainerPathValueV1, CalldataDescriptorDataPathV1, + CalldataDescriptorEIP712PathV1, CalldataDescriptorPathElementArrayV1, CalldataDescriptorPathElementLeafV1, CalldataDescriptorPathElementRefV1, @@ -150,6 +152,11 @@ def convert_container_path( ) +# Converts a resolved data path to a calldata protocol value; contract binding navigates the ABI tree, EIP-712 +# binding navigates the reconstructed message value tree. +DataPathConverter = Callable[[DataPath, OutputAdder], CalldataDescriptorValuePathV1 | None] + + def convert_data_path( path: DataPath, abi: ABITree, @@ -345,6 +352,8 @@ def apply_path(calldata: HexStr, path: CalldataDescriptorValuePathV1) -> Any: match path.binary_path: case CalldataDescriptorContainerPathV1(): raise ValueError("This function only supports data paths") + case CalldataDescriptorEIP712PathV1(): + raise ValueError("This function only supports data paths, not EIP-712 message paths") case CalldataDescriptorDataPathV1(): raw_value = apply_path_raw(calldata, path.binary_path) case _: diff --git a/src/erc7730/convert/calldata/v1/tlv.py b/src/erc7730/convert/calldata/v1/tlv.py index 672220c6..48333030 100644 --- a/src/erc7730/convert/calldata/v1/tlv.py +++ b/src/erc7730/convert/calldata/v1/tlv.py @@ -11,11 +11,18 @@ from erc7730.common.binary import from_hex, tlv from erc7730.common.pydantic import pydantic_enum_by_name from erc7730.model.calldata.types import TrustedNameSource, TrustedNameType +from erc7730.model.calldata.v1.eip712 import ( + CalldataDescriptorEIP712FieldV1, + CalldataDescriptorEIP712StructV1, + CalldataDescriptorInstructionEIP712SchemaV1, +) from erc7730.model.calldata.v1.instruction import ( CalldataDescriptorFieldVisibilityV1, + CalldataDescriptorInstructionEIP712MessageInfoV1, CalldataDescriptorInstructionEnumValueV1, CalldataDescriptorInstructionFieldV1, CalldataDescriptorInstructionMapEntryV1, + CalldataDescriptorInstructionTransactionInfoBaseV1, CalldataDescriptorInstructionTransactionInfoV1, ) from erc7730.model.calldata.v1.param import ( @@ -37,6 +44,10 @@ CalldataDescriptorContainerPathV1, CalldataDescriptorDataPathV1, CalldataDescriptorMapRefV1, + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementStructFieldV1, + CalldataDescriptorEIP712PathElementV1, + CalldataDescriptorEIP712PathV1, CalldataDescriptorPathElementArrayV1, CalldataDescriptorPathElementLeafV1, CalldataDescriptorPathElementRefV1, @@ -52,6 +63,8 @@ @pydantic_enum_by_name class CalldataDescriptorTransactionInfoTag(IntEnum): + # TRANSACTION_INFO and EIP712_MESSAGE_INFO share this structure; tag 0x03 is context-dependent, carrying a + # SELECTOR (SignTx) or a PRIMARY_TYPE_HASH (EIP-712 message, see CalldataDescriptorEIP712MessageInfoTag). VERSION = 0x00 CHAIN_ID = 0x01 CONTRACT_ADDR = 0x02 @@ -66,6 +79,48 @@ class CalldataDescriptorTransactionInfoTag(IntEnum): SIGNATURE = 0xFF +@pydantic_enum_by_name +class CalldataDescriptorEIP712MessageInfoTag(IntEnum): + # EIP712_MESSAGE_INFO reuses the TRANSACTION_INFO tags; only tag 0x03 differs (same value as SELECTOR). + PRIMARY_TYPE_HASH = 0x03 + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712SchemaTag(IntEnum): + VERSION = 0x00 + EIP712_STRUCT = 0x01 + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712StructTag(IntEnum): + VERSION = 0x00 + NAME = 0x01 + EIP712_FIELD = 0x02 + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712FieldTag(IntEnum): + VERSION = 0x00 + NAME = 0x01 + TYPE = 0x02 + TYPE_SIZE = 0x03 + ARRAY_DIM = 0x04 + STRUCT_NAME = 0x05 + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712PathTag(IntEnum): + VERSION = 0x00 + EIP712_STRUCT_FIELD = 0x01 + EIP712_ARRAY_SLICE = 0x02 + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712ArraySliceTag(IntEnum): + START = 0x01 + END = 0x02 + + @pydantic_enum_by_name class CalldataDescriptorEnumValueTag(IntEnum): VERSION = 0x00 @@ -231,18 +286,27 @@ class CalldataDescriptorPathSliceElementTag(IntEnum): END = 0x02 -def tlv_transaction_info(obj: CalldataDescriptorInstructionTransactionInfoV1) -> bytes: +def _tlv_transaction_info_base( + obj: CalldataDescriptorInstructionTransactionInfoBaseV1, + target_tag: CalldataDescriptorTransactionInfoTag | CalldataDescriptorEIP712MessageInfoTag, + target_value: bytes, +) -> bytes: """ - Encode a struct of type TRANSACTION_INFO. + Encode the structure shared by TRANSACTION_INFO and EIP712_MESSAGE_INFO. + + The two structs share every tag but tag 0x03, which identifies what the descriptor applies to (a function + selector or an EIP-712 message primary type), passed by the caller. @param obj: object representation of struct + @param target_tag: tag 0x03 (SELECTOR or PRIMARY_TYPE_HASH) + @param target_value: payload for tag 0x03 @return: encoded struct TLV """ out = bytearray() out += tlv(CalldataDescriptorTransactionInfoTag.VERSION, obj.version.to_bytes(1)) out += tlv(CalldataDescriptorTransactionInfoTag.CHAIN_ID, obj.chain_id.to_bytes(8)) out += tlv(CalldataDescriptorTransactionInfoTag.CONTRACT_ADDR, from_hex(obj.address)) - out += tlv(CalldataDescriptorTransactionInfoTag.SELECTOR, from_hex(obj.selector)) + out += tlv(target_tag, target_value) out += tlv(CalldataDescriptorTransactionInfoTag.FIELDS_HASH, from_hex(obj.hash)) out += tlv(CalldataDescriptorTransactionInfoTag.OPERATION_TYPE, obj.operation_type) @@ -265,6 +329,91 @@ def tlv_transaction_info(obj: CalldataDescriptorInstructionTransactionInfoV1) -> return out +def tlv_transaction_info(obj: CalldataDescriptorInstructionTransactionInfoV1) -> bytes: + """ + Encode a struct of type TRANSACTION_INFO. + + @param obj: object representation of struct + @return: encoded struct TLV + """ + return _tlv_transaction_info_base(obj, CalldataDescriptorTransactionInfoTag.SELECTOR, from_hex(obj.selector)) + + +def tlv_eip712_message_info(obj: CalldataDescriptorInstructionEIP712MessageInfoV1) -> bytes: + """ + Encode a struct of type EIP712_MESSAGE_INFO. + + Same wire structure as TRANSACTION_INFO, except tag 0x03 carries the primary type hash (32 bytes) instead of a + function selector. + + @param obj: object representation of struct + @return: encoded struct TLV + """ + return _tlv_transaction_info_base( + obj, CalldataDescriptorEIP712MessageInfoTag.PRIMARY_TYPE_HASH, from_hex(obj.primary_type_hash) + ) + + +def tlv_eip712_schema(obj: CalldataDescriptorInstructionEIP712SchemaV1) -> bytes: + """ + Encode a struct of type EIP712_SCHEMA (all EIP712_STRUCT entries nested). + + @param obj: object representation of struct + @return: encoded struct TLV + """ + out = bytearray() + out += tlv(CalldataDescriptorEIP712SchemaTag.VERSION, obj.version.to_bytes(1)) + for struct in obj.structs: + out += tlv(CalldataDescriptorEIP712SchemaTag.EIP712_STRUCT, tlv_eip712_struct(struct)) + return out + + +def tlv_eip712_struct(obj: CalldataDescriptorEIP712StructV1) -> bytes: + """ + Encode a struct of type EIP712_STRUCT. + + @param obj: object representation of struct + @return: encoded struct TLV + """ + out = bytearray() + out += tlv(CalldataDescriptorEIP712StructTag.VERSION, (0).to_bytes(1)) + out += tlv(CalldataDescriptorEIP712StructTag.NAME, obj.name) + for field in obj.fields: + out += tlv(CalldataDescriptorEIP712StructTag.EIP712_FIELD, tlv_eip712_field(field)) + return out + + +def tlv_eip712_field(obj: CalldataDescriptorEIP712FieldV1) -> bytes: + """ + Encode a struct of type EIP712_FIELD. + + @param obj: object representation of struct + @return: encoded struct TLV + """ + out = bytearray() + out += tlv(CalldataDescriptorEIP712FieldTag.VERSION, (0).to_bytes(1)) + out += tlv(CalldataDescriptorEIP712FieldTag.NAME, obj.name) + out += tlv(CalldataDescriptorEIP712FieldTag.TYPE, obj.sol_type.value.to_bytes(1)) + + if (type_size := obj.type_size) is not None: + out += tlv(CalldataDescriptorEIP712FieldTag.TYPE_SIZE, type_size.to_bytes(1)) + + for dimension in obj.array_dimensions: + if dimension is None: + # empty payload marks a dynamic dimension + out += tlv(CalldataDescriptorEIP712FieldTag.ARRAY_DIM) + else: + # TODO spec declares ARRAY_DIM as uint32 but examples encode it minimally (T[2] -> 04 01 02); encoded + # here as minimal big-endian (>= 1 byte) to match the spec examples, pending clarification + length = max(1, (dimension.bit_length() + 7) // 8) + out += tlv(CalldataDescriptorEIP712FieldTag.ARRAY_DIM, dimension.to_bytes(length)) + + if (struct_name := obj.struct_name) is not None: + out += tlv(CalldataDescriptorEIP712FieldTag.STRUCT_NAME, struct_name) + + return out + + def tlv_enum_value(obj: CalldataDescriptorInstructionEnumValueV1) -> bytes: """ Encode a struct of type ENUM_VALUE. @@ -610,6 +759,13 @@ def tlv_value(obj: CalldataDescriptorValueV1) -> bytes: for element in data_path.elements: out_path += tlv_data_path_element(element) out += tlv(CalldataDescriptorValueTag.DATA_PATH, out_path) + case CalldataDescriptorEIP712PathV1() as eip712_path: + # tag 0x03 is context-dependent (DATA_PATH for calldata, EIP712_PATH for EIP-712 messages) + out_path = bytearray() + out_path += tlv(CalldataDescriptorEIP712PathTag.VERSION, path.version.to_bytes(1)) + for eip712_element in eip712_path.elements: + out_path += tlv_eip712_path_element(eip712_element) + out += tlv(CalldataDescriptorValueTag.DATA_PATH, out_path) case _: assert_never(path.binary_path) case CalldataDescriptorValueConstantV1() as constant: @@ -680,3 +836,31 @@ def tlv_data_path_element(obj: CalldataDescriptorPathElementV1) -> bytes: case _: assert_never(obj) return out + + +def tlv_eip712_path_element(obj: CalldataDescriptorEIP712PathElementV1) -> bytes: + """ + Encode an element of an EIP712_PATH (either a struct field index or an array slice). + + @param obj: object representation of struct + @return: encoded struct TLV + """ + out = bytearray() + match obj: + case CalldataDescriptorEIP712PathElementStructFieldV1() as struct_field: + out += tlv(CalldataDescriptorEIP712PathTag.EIP712_STRUCT_FIELD, struct_field.index.to_bytes(1)) + + case CalldataDescriptorEIP712PathElementArraySliceV1() as array_slice: + slice_out = bytearray() + + if (start := array_slice.start) is not None: + slice_out += tlv(CalldataDescriptorEIP712ArraySliceTag.START, start.to_bytes(2, signed=True)) + + if (end := array_slice.end) is not None: + slice_out += tlv(CalldataDescriptorEIP712ArraySliceTag.END, end.to_bytes(2, signed=True)) + + out += tlv(CalldataDescriptorEIP712PathTag.EIP712_ARRAY_SLICE, bytes(slice_out)) + + case _: + assert_never(obj) + return out diff --git a/src/erc7730/lint/v2/lint_validate_map_keys.py b/src/erc7730/lint/v2/lint_validate_map_keys.py index b64573f0..be63a12b 100644 --- a/src/erc7730/lint/v2/lint_validate_map_keys.py +++ b/src/erc7730/lint/v2/lint_validate_map_keys.py @@ -10,10 +10,13 @@ from erc7730.common.output import OutputAdder from erc7730.convert.calldata.v1.abi import function_to_abi_tree from erc7730.convert.calldata.v1.map import encode_map_keys +from erc7730.convert.calldata.v1.path import convert_data_path from erc7730.convert.resolved.v2.values import is_deployment_key from erc7730.lint.v2 import ERC7730Linter from erc7730.lint.v2.lint_validate_display_fields import parse_declared_abis +from erc7730.model.calldata.v1.value import CalldataDescriptorValuePathV1 from erc7730.model.input.v2.descriptor import InputERC7730Descriptor +from erc7730.model.paths import DataPath from erc7730.model.resolved.v2.context import ResolvedContractContext, ResolvedEIP712Context from erc7730.model.resolved.v2.descriptor import ResolvedERC7730Descriptor from erc7730.model.resolved.v2.display import ( @@ -50,8 +53,12 @@ def lint( continue # only built when needed: some ABI types (fixed point numbers) cannot be converted to a tree abi_tree = function_to_abi_tree(abi) + + def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorValuePathV1 | None: + return convert_data_path(data_path, abi_tree, out) + for value_map in value_maps: - encode_map_keys(value_map, abi_tree, out) + encode_map_keys(value_map, convert_path, out) case _: assert_never(descriptor.context) diff --git a/src/erc7730/model/calldata/__init__.py b/src/erc7730/model/calldata/__init__.py index 044da652..28f260ab 100644 --- a/src/erc7730/model/calldata/__init__.py +++ b/src/erc7730/model/calldata/__init__.py @@ -9,13 +9,12 @@ from abc import ABC from enum import StrEnum, auto -from typing import Literal from pydantic import Field from pydantic_string_url import HttpUrl from erc7730.model.base import Model -from erc7730.model.types import Address, Id, Selector +from erc7730.model.types import Address, Id class CalldataDescriptorVersion(StrEnum): @@ -26,19 +25,14 @@ class CalldataDescriptorVersion(StrEnum): class CalldataDescriptorBase(Model, ABC): """ - A clear signing descriptor for a smart contract function calldata. + A clear signing descriptor for a smart contract function calldata or an EIP-712 message. - Note a calldata descriptor is bound to a single deployment (single chain id/contract address) and a single function. + Note a calldata descriptor is bound to a single deployment (single chain id/contract address) and a single function + (contract calldata) or message primary type (EIP-712). Also referred to as a "generic parser descriptor". """ - type: Literal["calldata"] = Field( - default="calldata", - title="Descriptor type", - description="Type of the descriptor", - ) - source: HttpUrl | None = Field( default=None, title="Descriptor source URL", @@ -60,8 +54,3 @@ class CalldataDescriptorBase(Model, ABC): title="Contract address", description="The contract deployment address.", ) - - selector: Selector = Field( - title="Function selector", - description="The 4-bytes function selector this descriptor applies to.", - ) diff --git a/src/erc7730/model/calldata/descriptor.py b/src/erc7730/model/calldata/descriptor.py index 42c08236..3067daa8 100644 --- a/src/erc7730/model/calldata/descriptor.py +++ b/src/erc7730/model/calldata/descriptor.py @@ -12,15 +12,16 @@ from pydantic import Field from erc7730.model.calldata.v1.descriptor import ( + CalldataDescriptorEIP712V1, CalldataDescriptorV1, ) CalldataDescriptor = Annotated[ - CalldataDescriptorV1, + CalldataDescriptorV1 | CalldataDescriptorEIP712V1, Field( title="Calldata descriptor", - description="A clear signing descriptor for a smart contract function calldata. Also referred to as a " - """"generic parser descriptor".""", - discriminator="version", + description="A clear signing descriptor for a smart contract function calldata (or an EIP-712 message). Also " + """referred to as a "generic parser descriptor".""", + discriminator="type", ), ] diff --git a/src/erc7730/model/calldata/v1/descriptor.py b/src/erc7730/model/calldata/v1/descriptor.py index dc1d9da5..4aadea67 100644 --- a/src/erc7730/model/calldata/v1/descriptor.py +++ b/src/erc7730/model/calldata/v1/descriptor.py @@ -7,12 +7,17 @@ from pydantic import Field from erc7730.model.calldata import CalldataDescriptorBase +from erc7730.model.calldata.v1.eip712 import ( + CalldataDescriptorInstructionEIP712SchemaV1, +) from erc7730.model.calldata.v1.instruction import ( + CalldataDescriptorInstructionEIP712MessageInfoV1, CalldataDescriptorInstructionEnumValueV1, CalldataDescriptorInstructionFieldV1, CalldataDescriptorInstructionMapEntryV1, CalldataDescriptorInstructionTransactionInfoV1, ) +from erc7730.model.types import HexStr, Selector class CalldataDescriptorV1(CalldataDescriptorBase): @@ -22,6 +27,17 @@ class CalldataDescriptorV1(CalldataDescriptorBase): Also referred to as a "generic parser descriptor". """ + type: Literal["calldata"] = Field( + default="calldata", + title="Descriptor type", + description="Type of the descriptor (contract calldata).", + ) + + selector: Selector = Field( + title="Function selector", + description="The 4-bytes function selector this descriptor applies to.", + ) + version: Literal["v1"] = Field( default="v1", title="Descriptor type version", @@ -50,3 +66,53 @@ class CalldataDescriptorV1(CalldataDescriptorBase): title="FIELD instructions descriptors", description="Descriptor and metadata to craft FIELD APDUs.", ) + + +class CalldataDescriptorEIP712V1(CalldataDescriptorBase): + """ + A clear signing descriptor for an EIP-712 typed message. + + Reuses the calldata (generic parser) v1 FIELD / PARAM_* / ENUM_VALUE structs, adding the EIP712_SCHEMA and + EIP712_MESSAGE_INFO structs and the EIP712_PATH value source. Referred to as "EIP712 v2" in the Ethereum app + specifications. + """ + + type: Literal["eip712"] = Field( + default="eip712", + title="Descriptor type", + description="Type of the descriptor (EIP-712 message).", + ) + + version: Literal["v1"] = Field( + default="v1", + title="Descriptor type version", + description="Version of the descriptor type (not the version of this specific descriptor, the version of the " + "descriptor specification)", + ) + + primary_type_hash: HexStr = Field( + title="Primary type hash", + description="keccak256(encodeType(primaryType)) of the EIP-712 message primary type.", + min_length=64, + max_length=66, + ) + + schema_info: CalldataDescriptorInstructionEIP712SchemaV1 = Field( + title="EIP712_SCHEMA instruction descriptor", + description="Descriptor and metadata to craft an EIP712_SCHEMA APDU.", + ) + + message_info: CalldataDescriptorInstructionEIP712MessageInfoV1 = Field( + title="EIP712_MESSAGE_INFO instruction descriptor", + description="Descriptor and metadata to craft an EIP712_MESSAGE_INFO APDU.", + ) + + enums: list[CalldataDescriptorInstructionEnumValueV1] = Field( + title="ENUM_VALUE instructions descriptors", + description="Descriptor and metadata to craft ENUM APDUs.", + ) + + fields: list[CalldataDescriptorInstructionFieldV1] = Field( + title="EIP712_FIELD_DESCRIPTOR instructions descriptors", + description="Descriptor and metadata to craft EIP712_FIELD_DESCRIPTOR APDUs.", + ) diff --git a/src/erc7730/model/calldata/v1/eip712.py b/src/erc7730/model/calldata/v1/eip712.py new file mode 100644 index 00000000..77a71654 --- /dev/null +++ b/src/erc7730/model/calldata/v1/eip712.py @@ -0,0 +1,108 @@ +""" +Data model for the EIP712_SCHEMA calldata descriptor struct and its nested structs. + +These model classes represent the exact same data fields that are serialized into TLV structs. Referred to as +"EIP712 v2" in the Ethereum app specifications (https://github.com/LedgerHQ/app-ethereum), but part of the calldata +(generic parser) v1 descriptor format. +""" + +from enum import IntEnum +from functools import cached_property +from typing import Literal + +from pydantic import Field, computed_field + +from erc7730.common.pydantic import pydantic_enum_by_name +from erc7730.model.base import Model +from erc7730.model.calldata.v1.instruction import ( + CalldataDescriptorInstructionBaseV1, + CalldataDescriptorInstructionHex, +) + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712SolType(IntEnum): + """Solidity base type of an EIP-712 struct field (EIP712_FIELD TYPE / SolType enum).""" + + STRUCT = 0x00 + INT = 0x01 + UINT = 0x02 + ADDRESS = 0x03 + BOOL = 0x04 + STRING = 0x05 + BYTES_FIX = 0x06 + BYTES_DYN = 0x07 + + +class CalldataDescriptorEIP712FieldV1(Model): + """Descriptor for the EIP712_FIELD struct (one field of an EIP-712 struct type).""" + + name: str = Field( + title="Field name", + description="Field name (ASCII)", + min_length=1, + ) + + sol_type: CalldataDescriptorEIP712SolType = Field( + title="Solidity type", + description="Solidity base type of the field", + ) + + type_size: int | None = Field( + default=None, + title="Type size", + description="Size in bytes, for INT/UINT/BYTES_FIX (1..32).", + ge=1, + le=32, + ) + + # innermost dimension first; None entry means a dynamic dimension, int means a fixed dimension size + array_dimensions: list[int | None] = Field( + default_factory=list, + title="Array dimensions", + description="One entry per array dimension, innermost first. None means dynamic dimension, an integer means " + "the fixed dimension size.", + ) + + struct_name: str | None = Field( + default=None, + title="Struct name", + description="Referenced struct name, only set if the type is STRUCT.", + ) + + +class CalldataDescriptorEIP712StructV1(Model): + """Descriptor for the EIP712_STRUCT struct (one EIP-712 struct type declaration).""" + + name: str = Field( + title="Struct name", + description="Struct name (ASCII). 'EIP712Domain' identifies the domain struct.", + min_length=1, + ) + + fields: list[CalldataDescriptorEIP712FieldV1] = Field( + title="Fields", + description="One entry per declared field, in declaration order.", + ) + + +class CalldataDescriptorInstructionEIP712SchemaV1(CalldataDescriptorInstructionBaseV1): + """Instruction descriptor for the EIP712_SCHEMA struct (whole schema, all struct types nested).""" + + version: Literal[1] = Field( + default=1, + title="Struct version", + description="Version of the EIP712_SCHEMA struct", + ) + + structs: list[CalldataDescriptorEIP712StructV1] = Field( + title="Structs", + description="One entry per declared struct type.", + ) + + @computed_field(title="Descriptor", description="Hex encoded EIP712_SCHEMA TLV struct") # type: ignore[misc] + @cached_property + def descriptor(self) -> CalldataDescriptorInstructionHex: + from erc7730.convert.calldata.v1.tlv import tlv_eip712_schema + + return tlv_eip712_schema(self).hex() diff --git a/src/erc7730/model/calldata/v1/instruction.py b/src/erc7730/model/calldata/v1/instruction.py index 8e2631c9..251d074e 100644 --- a/src/erc7730/model/calldata/v1/instruction.py +++ b/src/erc7730/model/calldata/v1/instruction.py @@ -69,13 +69,18 @@ class CalldataDescriptorInstructionBaseV1(CalldataDescriptorStructV1, ABC, extra """Base class for calldata descriptor instructions.""" -class CalldataDescriptorInstructionTransactionInfoV1(CalldataDescriptorInstructionBaseV1): - """Instruction descriptor for the TRANSACTION_INFO struct.""" +class CalldataDescriptorInstructionTransactionInfoBaseV1(CalldataDescriptorInstructionBaseV1, ABC): + """ + Common fields for the TRANSACTION_INFO / EIP712_MESSAGE_INFO structs. + + These two structs share the same wire structure and are handled as a single structure in the Ethereum app; they + differ only by tag 0x03 (SELECTOR for calldata, PRIMARY_TYPE_HASH for EIP-712 messages). + """ version: Literal[1] = Field( default=1, title="Struct version", - description="Version of the TRANSACTION_INFO struct", + description="Version of the struct", ) chain_id: int = Field( @@ -89,11 +94,6 @@ class CalldataDescriptorInstructionTransactionInfoV1(CalldataDescriptorInstructi description="The contract deployment address.", ) - selector: Selector = Field( - title="Function selector", - description="The 4-bytes function selector this descriptor applies to.", - ) - hash: str = Field( title="Structs hash", description="Hash of all the FIELD structs", @@ -147,6 +147,15 @@ class CalldataDescriptorInstructionTransactionInfoV1(CalldataDescriptorInstructi description="Displayed in review first screens", ) + +class CalldataDescriptorInstructionTransactionInfoV1(CalldataDescriptorInstructionTransactionInfoBaseV1): + """Instruction descriptor for the TRANSACTION_INFO struct.""" + + selector: Selector = Field( + title="Function selector", + description="The 4-bytes function selector this descriptor applies to.", + ) + @computed_field(title="Descriptor", description="Hex encoded TRANSACTION_INFO TLV struct") # type: ignore[misc] @cached_property def descriptor(self) -> CalldataDescriptorInstructionHex: @@ -157,6 +166,31 @@ def descriptor(self) -> CalldataDescriptorInstructionHex: return tlv_transaction_info(self).hex() +class CalldataDescriptorInstructionEIP712MessageInfoV1(CalldataDescriptorInstructionTransactionInfoBaseV1): + """ + Instruction descriptor for the EIP712_MESSAGE_INFO struct. + + Same wire structure as TRANSACTION_INFO, except tag 0x03 carries the EIP-712 primary type hash (32 bytes) instead + of a function selector (4 bytes). Referred to as "EIP712 v2" in the Ethereum app specifications. + """ + + primary_type_hash: HexStr = Field( + title="Primary type hash", + description="keccak256(encodeType(primaryType)) of the EIP-712 message primary type.", + min_length=64, + max_length=66, + ) + + @computed_field(title="Descriptor", description="Hex encoded EIP712_MESSAGE_INFO TLV struct") # type: ignore[misc] + @cached_property + def descriptor(self) -> CalldataDescriptorInstructionHex: + from erc7730.convert.calldata.v1.tlv import ( + tlv_eip712_message_info, + ) + + return tlv_eip712_message_info(self).hex() + + class CalldataDescriptorInstructionEnumValueV1(CalldataDescriptorInstructionBaseV1): """Instruction descriptor for the ENUM_VALUE struct.""" diff --git a/src/erc7730/model/calldata/v1/value.py b/src/erc7730/model/calldata/v1/value.py index 26be1370..1d65cfd3 100644 --- a/src/erc7730/model/calldata/v1/value.py +++ b/src/erc7730/model/calldata/v1/value.py @@ -224,11 +224,94 @@ class CalldataDescriptorDataPathV1(CalldataDescriptorStructV1): ) +class CalldataDescriptorEIP712PathElementStructFieldV1(Model): + """Descriptor for the EIP712_STRUCT_FIELD path element (descend into a struct field by declaration index).""" + + type: Literal["struct_field"] = Field( + default="struct_field", + title="Element type", + description="Type of the EIP-712 path element", + ) + + index: int = Field( + title="Field index", + description="Index of the field in the struct declaration order", + ge=0, + le=255, + ) + + +class CalldataDescriptorEIP712PathElementArraySliceV1(Model): + """Descriptor for the EIP712_ARRAY_SLICE path element (select an array segment).""" + + type: Literal["array_slice"] = Field( + default="array_slice", + title="Element type", + description="Type of the EIP-712 path element", + ) + + start: int | None = Field( + default=None, + title="Start", + description="Start index in array (inclusive). If not provided, lower bound is array start.", + ge=-32768, + le=32767, + ) + + end: int | None = Field( + default=None, + title="End", + description="End index in array (exclusive). If not provided, upper bound is array end.", + ge=-32768, + le=32767, + ) + + +CalldataDescriptorEIP712PathElementV1 = Annotated[ + CalldataDescriptorEIP712PathElementStructFieldV1 | CalldataDescriptorEIP712PathElementArraySliceV1, + Field( + title="EIP-712 path element", + description="Path element to reach the target value in the EIP-712 value tree", + discriminator="type", + ), +] + + +class CalldataDescriptorEIP712PathV1(CalldataDescriptorStructV1): + """ + Descriptor for the EIP712_PATH struct. + + Path into the EIP-712 value tree, navigated by struct field index and array slices (as opposed to DATA_PATH which + navigates serialized transaction calldata by byte offsets). Referred to as "EIP712 v2" in the Ethereum app + specifications. + """ + + version: Literal[1] = Field( + default=1, + title="Struct version", + description="Version of the EIP712_PATH struct", + ) + + type: Literal["EIP712"] = Field( + default="EIP712", + title="Path type", + description="Type of the path", + ) + + elements: list[CalldataDescriptorEIP712PathElementV1] = Field( + title="Elements", + description="Interleaved struct field / array slice elements to reach the target value in the value tree", + min_length=1, + max_length=256, + ) + + CalldataDescriptorPathV1 = Annotated[ - CalldataDescriptorContainerPathV1 | CalldataDescriptorDataPathV1, + CalldataDescriptorContainerPathV1 | CalldataDescriptorDataPathV1 | CalldataDescriptorEIP712PathV1, Field( title="Path", - description="Data or container path to reach the target value in the serialized transaction", + description="Data, container or EIP-712 path to reach the target value in the serialized transaction or " + "message value tree", discriminator="type", ), ] diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py new file mode 100644 index 00000000..3bb719f2 --- /dev/null +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -0,0 +1,202 @@ +import json +from typing import Any + +from eth_utils import keccak + +from erc7730.convert.calldata.convert_erc7730_v2_input_to_calldata import ( + erc7730_v2_descriptor_to_calldata_descriptors, +) +from erc7730.convert.calldata.v1.tlv import tlv_eip712_field, tlv_eip712_path_element +from erc7730.model.calldata.v1.descriptor import CalldataDescriptorEIP712V1 +from erc7730.model.calldata.v1.eip712 import CalldataDescriptorEIP712FieldV1, CalldataDescriptorEIP712SolType +from erc7730.model.calldata.v1.value import ( + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementStructFieldV1, + CalldataDescriptorEIP712PathV1, + CalldataDescriptorValuePathV1, +) +from erc7730.model.input.v2.descriptor import InputERC7730Descriptor + +DEFAULT_CHAIN_ID = 1 +DEFAULT_ADDRESS = "0x000000000000000000000000000000000000dEaD" + + +def _eip712_path(descriptor: CalldataDescriptorEIP712V1, index: int) -> CalldataDescriptorEIP712PathV1: + """Return the EIP-712 binary path of the given field, asserting its type.""" + value = descriptor.fields[index].param.value + assert isinstance(value, CalldataDescriptorValuePathV1) + path = value.binary_path + assert isinstance(path, CalldataDescriptorEIP712PathV1) + return path + + +def _convert( + encode_type: str, + fields: list[dict[str, Any]], + *, + domain: dict[str, Any] | None = None, + chain_id: int = DEFAULT_CHAIN_ID, +) -> CalldataDescriptorEIP712V1: + """Build a minimal EIP-712 v2 descriptor and return the single converted calldata descriptor.""" + descriptor = InputERC7730Descriptor.model_validate_json( + json.dumps( + { + "$schema": "specs/erc7730-v2.schema.json", + "context": { + "$id": "test", + "eip712": { + "deployments": [{"chainId": chain_id, "address": DEFAULT_ADDRESS}], + "domain": domain if domain is not None else {"name": "Test", "version": "1"}, + }, + }, + "metadata": {"owner": "Test Owner"}, + "display": {"formats": {encode_type: {"intent": "Test intent", "fields": fields}}}, + } + ) + ) + + descriptors = erc7730_v2_descriptor_to_calldata_descriptors(descriptor, chain_id=chain_id) + assert len(descriptors) == 1 + descriptor_out = descriptors[0] + assert isinstance(descriptor_out, CalldataDescriptorEIP712V1) + return descriptor_out + + +PERMIT_TYPE = "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" + + +def test_eip712_binding_and_primary_type_hash() -> None: + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + ) + + assert descriptor.type == "eip712" + assert descriptor.version == "v1" + assert descriptor.primary_type_hash == "0x" + keccak(text=PERMIT_TYPE).hex() + assert descriptor.message_info.primary_type_hash == descriptor.primary_type_hash + + +def test_eip712_schema_reconstruction_includes_domain_and_message_types() -> None: + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + domain={"name": "Test", "version": "1"}, + ) + + structs = {struct.name: struct for struct in descriptor.schema_info.structs} + assert set(structs) == {"EIP712Domain", "Permit"} + + # domain: name, version present; deployments imply chainId + verifyingContract + domain_fields = [(f.name, f.sol_type) for f in structs["EIP712Domain"].fields] + assert domain_fields == [ + ("name", CalldataDescriptorEIP712SolType.STRING), + ("version", CalldataDescriptorEIP712SolType.STRING), + ("chainId", CalldataDescriptorEIP712SolType.UINT), + ("verifyingContract", CalldataDescriptorEIP712SolType.ADDRESS), + ] + + permit_fields = [(f.name, f.sol_type) for f in structs["Permit"].fields] + assert permit_fields == [ + ("owner", CalldataDescriptorEIP712SolType.ADDRESS), + ("spender", CalldataDescriptorEIP712SolType.ADDRESS), + ("value", CalldataDescriptorEIP712SolType.UINT), + ("nonce", CalldataDescriptorEIP712SolType.UINT), + ("deadline", CalldataDescriptorEIP712SolType.UINT), + ] + + +def test_eip712_field_path_uses_struct_field_indices() -> None: + descriptor = _convert( + PERMIT_TYPE, + [ + {"path": "owner", "label": "Owner", "format": "addressName", "params": {"types": ["wallet"]}}, + {"path": "value", "label": "Value", "format": "amount"}, + {"path": "deadline", "label": "Deadline", "format": "date", "params": {"encoding": "timestamp"}}, + ], + ) + + assert len(descriptor.fields) == 3 + + # owner -> field 0, value -> field 2, deadline -> field 4 of Permit + assert _eip712_path(descriptor, 0).elements == [CalldataDescriptorEIP712PathElementStructFieldV1(index=0)] + assert _eip712_path(descriptor, 1).elements == [CalldataDescriptorEIP712PathElementStructFieldV1(index=2)] + assert _eip712_path(descriptor, 2).elements == [CalldataDescriptorEIP712PathElementStructFieldV1(index=4)] + + +def test_eip712_nested_struct_and_array_path() -> None: + descriptor = _convert( + "Batch(Transfer[] transfers)Transfer(address to,uint256 amount)", + [ + {"path": "transfers.[].to", "label": "To", "format": "addressName", "params": {"types": ["wallet"]}}, + {"path": "transfers.[].amount", "label": "Amount", "format": "amount"}, + ], + ) + + structs = {struct.name: struct for struct in descriptor.schema_info.structs} + assert set(structs) == {"EIP712Domain", "Batch", "Transfer"} + + # transfers is a dynamic array of Transfer structs + transfers_field = structs["Batch"].fields[0] + assert transfers_field.sol_type == CalldataDescriptorEIP712SolType.STRUCT + assert transfers_field.struct_name == "Transfer" + assert transfers_field.array_dimensions == [None] + + to_path = _eip712_path(descriptor, 0) + assert to_path.elements == [ + CalldataDescriptorEIP712PathElementStructFieldV1(index=0), # transfers + CalldataDescriptorEIP712PathElementArraySliceV1(), # wildcard over array + CalldataDescriptorEIP712PathElementStructFieldV1(index=0), # to + ] + + amount_path = _eip712_path(descriptor, 1) + assert amount_path.elements == [ + CalldataDescriptorEIP712PathElementStructFieldV1(index=0), # transfers + CalldataDescriptorEIP712PathElementArraySliceV1(), # wildcard over array + CalldataDescriptorEIP712PathElementStructFieldV1(index=1), # amount + ] + + +def test_eip712_descriptor_serializes_to_tlv_and_json() -> None: + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + ) + + # computed TLV descriptor fields must be non-empty hex + assert bytes.fromhex(descriptor.message_info.descriptor) + assert bytes.fromhex(descriptor.schema_info.descriptor) + for field in descriptor.fields: + assert bytes.fromhex(field.descriptor) + + assert descriptor.model_dump_json() + + +def _uint_field(dimensions: list[int | None]) -> CalldataDescriptorEIP712FieldV1: + return CalldataDescriptorEIP712FieldV1( + name="x", sol_type=CalldataDescriptorEIP712SolType.UINT, type_size=1, array_dimensions=dimensions + ) + + +def test_eip712_array_dim_tlv_matches_spec_examples() -> None: + # ARRAY_DIM encoding, per the app-ethereum spec: T[2] -> 040102, T[0] -> 040100, T[] -> 0400 + assert tlv_eip712_field(_uint_field([2])).hex().endswith("040102") + assert tlv_eip712_field(_uint_field([0])).hex().endswith("040100") + assert tlv_eip712_field(_uint_field([None])).hex().endswith("0400") + + +def test_eip712_path_element_tlv_encoding() -> None: + # EIP712_STRUCT_FIELD: tag 0x01, uint8 index + assert tlv_eip712_path_element(CalldataDescriptorEIP712PathElementStructFieldV1(index=1)).hex() == "010101" + + # EIP712_ARRAY_SLICE: tag 0x02 wrapping START (0x01) / END (0x02), each a fixed-width 2-byte signed int + assert ( + tlv_eip712_path_element(CalldataDescriptorEIP712PathElementArraySliceV1(start=2, end=3)).hex() + == "02080102000202020003" + ) + + # negative index sign-extends across the full 2 bytes (0xffff), not minimal length + assert tlv_eip712_path_element(CalldataDescriptorEIP712PathElementArraySliceV1(start=-1)).hex() == "02040102ffff" + + # wildcard slice (no START/END) is an empty payload + assert tlv_eip712_path_element(CalldataDescriptorEIP712PathElementArraySliceV1()).hex() == "0200" From 92883038c10fc6fc823913047453462c5d22f37d Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 20 Aug 2026 16:18:39 +0200 Subject: [PATCH 02/13] feat(BACK-12243): encode TLV tag/length as multi-byte DER to support payloads over 255 bytes --- src/erc7730/common/binary.py | 104 +++++++++++++++++++++++++++++++---- tests/common/test_binary.py | 83 +++++++++++++++++++++++++--- 2 files changed, 167 insertions(+), 20 deletions(-) diff --git a/src/erc7730/common/binary.py b/src/erc7730/common/binary.py index 1f106d42..5a8a4da0 100644 --- a/src/erc7730/common/binary.py +++ b/src/erc7730/common/binary.py @@ -13,53 +13,133 @@ def from_hex(value: str) -> bytes: return bytes.fromhex(value.removeprefix("0x")) -def tlv(tag: int | IntEnum, value: bytes | str | None = None) -> bytes: +def tlv( + tag: int | IntEnum, + value: bytes | bytearray | str | int | None = None, + max_length: int | None = None, + optional: bool = False, +) -> bytes: """ Encode a value in TLV format (Tag-Length-Value) - Tag and length are DER encoded. If tag value or length exceed 255, an OverflowError is raised. + Tag and length are DER encoded. If value is not encoded, it will be encoded as ASCII. - If input string is not ASCII, a UnicodeEncodeError is raised. + If value is an integer, it will be encoded as smallest variable-length integer. + + If input string is not ASCII, and UnicodeEncodeError is raised. + If encoded value is longer than max_length, OverflowError is raised. + + @param tag: the tag (can be an enum) + @param value: the value (can be already encoded, a string or an integer) + @param max_length: the maximum length of the value (if None, no limit) + @param optional: if True, the TLV will be omitted if value is None, else it will be encoded as 0-length. + @return: encoded TLV + """ + if optional and value is None: + return b"" + + return der_encode_int(tag.value if isinstance(tag, IntEnum) else tag) + length_value( + value, max_length, der_encode_length=True + ) + + +def fixed_tlv(tag: int | IntEnum, length: int, value: int | bytes | None, optional: bool = False) -> bytes: + """ + Encode a value in TLV format (Tag-Length-Value) with a fixed length for the value. + + Tag and length are DER encoded. + + If encoded value is longer than length, OverflowError is raised. If smaller, it will be padded with zeros. @param tag: the tag (can be an enum) - @param value: the value (can be already encoded, a string or None) + @param length: the length of the value + @param value: the value (can be already encoded or an integer) + @param optional: if True, the TLV will be omitted if value is None, else it will be encoded as 0-length. @return: encoded TLV """ - return der_encode_int(tag.value if isinstance(tag, IntEnum) else tag) + length_value(value) + if optional and value is None: + return b"" + return der_encode_int(tag.value if isinstance(tag, IntEnum) else tag) + encode_fixed(value, length) def length_value( - value: bytes | bytearray | str | None, + value: bytes | bytearray | str | int | None, max_length: int | None = None, der_encode_length: bool = False ) -> bytes: """ Prepend the length (DER encoded) of the value encoded to the value itself. - If length exceeds 255 bytes, an OverflowError is raised. If value is not encoded, it will be encoded as ASCII. - If input string is not ASCII, a UnicodeEncodeError is raised. + + If input string is not ASCII, and UnicodeEncodeError is raised. + If encoded value is longer than max_length, OverflowError is raised @param value: the value (can be already encoded, or a string) + @param max_length: the maximum length of the value (if None, no limit) @return: encoded TLV """ if value is None: return (0).to_bytes(1, "big") match value: + case int(): + value_encoded = encode_variable_int(value) case bytes() | bytearray(): value_encoded = bytes(value) case str(): value_encoded = value.encode("ascii", errors="strict") - return der_encode_int(len(value_encoded)) + value_encoded + if max_length is not None and len(value_encoded) > max_length: + raise OverflowError(f"Value length {len(value_encoded)} exceeds maximum length {max_length}") + if der_encode_length: + return der_encode_int(len(value_encoded)) + value_encoded + else: # This will raise OverflowError if value_encoded is longer than 255 bytes + return (len(value_encoded)).to_bytes(1, "big") + value_encoded def der_encode_int(value: int) -> bytes: """ Encode an integer in DER format. - If value exceeds 255, an OverflowError is raised. @param value: the integer to encode @return: DER encoded byte array """ - value_bytes = value.to_bytes(1, "big") # raises OverflowError if value >= 256 - return (0x81).to_bytes(1, "big") + value_bytes if value >= 0x80 else value_bytes + value_bytes = encode_variable_int(value) + if value >= 0x80: + value_bytes = (0x80 | len(value_bytes)).to_bytes(1, "big") + value_bytes + return value_bytes + + +def encode_variable_int(value: int | None) -> bytes: + """ + Encode an integer in variable-length format. + + @param value: the integer to encode + @return: variable-length encoded byte array + """ + if value is None: + return (0).to_bytes(1, "big") + return value.to_bytes(max(1, (value.bit_length() + 7) // 8), "big") + + +def encode_fixed(value: int | bytes | None, length: int) -> bytes: + """ + Encode an integer in fixed-length format. + + If encoded value is longer than length, OverflowError is raised. If smaller, it will be padded with zeros. + + @param value: the integer to encode + @param length: the length of the encoded value in bytes + @return: fixed-length encoded byte array + """ + if value is None: + return (0).to_bytes(1, "big") + match value: + case int(): + value_encoded = value.to_bytes(length, "big") + case bytes(): + original_length = len(value) + if original_length > length: + raise OverflowError(f"Value length {original_length} exceeds fixed length {length}") + padding = max(0, length - original_length) + value_encoded = (b"\0" * padding) + value + return der_encode_int(length) + value_encoded diff --git a/tests/common/test_binary.py b/tests/common/test_binary.py index 35843e17..8b0926d4 100644 --- a/tests/common/test_binary.py +++ b/tests/common/test_binary.py @@ -2,7 +2,7 @@ import pytest -from erc7730.common.binary import tlv +from erc7730.common.binary import der_encode_int, encode_fixed, length_value, tlv class _Tag(IntEnum): @@ -14,24 +14,91 @@ class _Tag(IntEnum): [ (1, None, b"\x01\x00"), (1, b"\xab", b"\x01\x01\xab"), + (1, bytearray(b"\xab"), b"\x01\x01\xab"), (1, "hi", b"\x01\x02hi"), (_Tag.FIELD, b"\xff", b"\x05\x01\xff"), (0x80, None, b"\x81\x80\x00"), (1, b"\x00" * 128, b"\x01\x81\x80" + b"\x00" * 128), + # DER long-form tag / length beyond 255 + (256, None, b"\x82\x01\x00\x00"), + (1, b"\x00" * 256, b"\x01\x82\x01\x00" + b"\x00" * 256), ], ) def test_tlv(tag: int | IntEnum, value: bytes | str | None, expected: bytes) -> None: assert tlv(tag, value) == expected +def test_tlv_encode_error() -> None: + with pytest.raises(UnicodeEncodeError): + tlv(1, "là-haut") + + +@pytest.mark.parametrize( + "input,expected", + [ + (None, b"\x00"), + (b"", b"\x00"), + ("", b"\x00"), + (b"FOO", b"\x03FOO"), + ("FOO", b"\x03FOO"), + (b"a" * 255, b"\x81\xff" + b"a" * 255), + (0, b"\x01\x00"), + (123, b"\x01\x7b"), + (123456789, b"\x04\x07\x5b\xcd\x15"), + (12345678901234567890, b"\x08\xab\x54\xa9\x8c\xeb\x1f\x0a\xd2"), + ], +) +def test_length_value_der_encoded_length(input: bytes | str | int | None, expected: bytes) -> None: + assert length_value(input, der_encode_length=True) == expected + + +def test_length_value_overflow() -> None: + with pytest.raises(OverflowError): + length_value(b"a" * 256) + + +def test_length_value_max_length_error() -> None: + with pytest.raises(OverflowError): + length_value("a" * 50, max_length=10) + + +def test_length_value_encode_error() -> None: + with pytest.raises(UnicodeEncodeError): + length_value("😈") + + +@pytest.mark.parametrize( + "input,expected", + [ + (1, b"\x01"), + (255, b"\x81\xff"), + (65535, b"\x82\xff\xff"), + ], +) +def test_der_encode_int(input: int, expected: bytes) -> None: + assert der_encode_int(input) == expected + + @pytest.mark.parametrize( - "tag, value, exc", + "input,length,expected", [ - (256, None, OverflowError), - (1, b"\x00" * 256, OverflowError), - (1, "là-haut", UnicodeEncodeError), + (None, 32, b"\x00"), + (0x42, 1, b"\x01\x42"), + (0x42, 2, b"\x02\x00\x42"), + (0x42, 8, b"\x08\x00\x00\x00\x00\x00\x00\x00\x42"), + (b"\x42", 1, b"\x01\x42"), + (b"\x42", 2, b"\x02\x00\x42"), ], ) -def test_tlv_errors(tag: int, value: bytes | str | None, exc: type[Exception]) -> None: - with pytest.raises(exc): - tlv(tag, value) +def test_encode_fixed(input: int, length: int, expected: bytes) -> None: + assert encode_fixed(input, length) == expected + + +def test_encode_fixed_int_too_big() -> None: + with pytest.raises(OverflowError): + encode_fixed(0x1234567890, 4) + + +def test_encode_fixed_bytes_too_long() -> None: + with pytest.raises(OverflowError): + encode_fixed(b"\x12\x34\x56\x78\x90", 4) From 7253cd89882f330682f0f9a853704c06634ba619 Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 20 Aug 2026 16:18:54 +0200 Subject: [PATCH 03/13] test(BACK-12243): add calldata registry integration test, consolidating the resolve one --- .../calldata/test_convert_registry_files.py | 28 +++++++++++++++++++ .../resolved/test_convert_registry_files.py | 19 ------------- tests/files.py | 9 +++++- 3 files changed, 36 insertions(+), 20 deletions(-) create mode 100644 tests/convert/calldata/test_convert_registry_files.py delete mode 100644 tests/convert/resolved/test_convert_registry_files.py diff --git a/tests/convert/calldata/test_convert_registry_files.py b/tests/convert/calldata/test_convert_registry_files.py new file mode 100644 index 00000000..56c6fa35 --- /dev/null +++ b/tests/convert/calldata/test_convert_registry_files.py @@ -0,0 +1,28 @@ +from pathlib import Path + +import pytest + +from erc7730.convert.calldata.convert_erc7730_v2_input_to_calldata import ( + erc7730_v2_descriptor_to_calldata_descriptors, +) +from erc7730.model.input.v2.descriptor import InputERC7730Descriptor +from tests.cases import path_id +from tests.files import ERC7730_DESCRIPTORS, ERC7730_EXPECTED_EMPTY_CALLDATA + +pytestmark = pytest.mark.integration + + +@pytest.mark.parametrize("input_file", ERC7730_DESCRIPTORS, ids=path_id) +def test_registry_files(input_file: Path) -> None: + """ + Test generating calldata descriptors for ERC-7730 registry files (also exercises resolution). + """ + descriptors = erc7730_v2_descriptor_to_calldata_descriptors(InputERC7730Descriptor.load(input_file)) + + if input_file.name in ERC7730_EXPECTED_EMPTY_CALLDATA: + return + + assert descriptors + # model_dump_json evaluates every computed TLV .descriptor field, exercising the full TLV encoding + for descriptor in descriptors: + assert descriptor.model_dump_json() diff --git a/tests/convert/resolved/test_convert_registry_files.py b/tests/convert/resolved/test_convert_registry_files.py deleted file mode 100644 index b79a4ebd..00000000 --- a/tests/convert/resolved/test_convert_registry_files.py +++ /dev/null @@ -1,19 +0,0 @@ -from pathlib import Path - -import pytest - -from erc7730.convert.convert import convert_and_raise_errors -from erc7730.convert.resolved.v2.convert_erc7730_input_to_resolved import ERC7730InputToResolved -from erc7730.model.input.v2.descriptor import InputERC7730Descriptor -from tests.cases import path_id -from tests.files import ERC7730_DESCRIPTORS - -pytestmark = pytest.mark.integration - - -@pytest.mark.parametrize("input_file", ERC7730_DESCRIPTORS, ids=path_id) -def test_registry_files(input_file: Path) -> None: - """ - Test converting ERC-7730 registry files from input to resolved form. - """ - convert_and_raise_errors(InputERC7730Descriptor.load(input_file), ERC7730InputToResolved()) diff --git a/tests/files.py b/tests/files.py index 626b423f..e90a393e 100644 --- a/tests/files.py +++ b/tests/files.py @@ -32,7 +32,7 @@ def _is_registry_descriptor(path: Path) -> bool: [ path for path in ERC7730_REGISTRY.rglob(f"{ERC_7730_REGISTRY_CALLDATA_PREFIX}*.json") - if _is_registry_descriptor(path) and path.name not in ["calldata-lpv2.json", "calldata-stETH.json"] + if _is_registry_descriptor(path) ] ) ERC7730_EIP712_DESCRIPTORS = sorted( @@ -49,6 +49,13 @@ def _is_registry_descriptor(path: Path) -> bool: ] ) ERC7730_DESCRIPTORS = sorted(ERC7730_CALLDATA_DESCRIPTORS + ERC7730_EIP712_DESCRIPTORS) + +# Registry descriptors that legitimately generate no calldata descriptor: conversion is still run on them (exercising +# resolution), but the non-empty calldata assertion is skipped. +ERC7730_EXPECTED_EMPTY_CALLDATA = { + "calldata-KasExitBridge.json", # only deployed on chain 38833 (Igra), which is not a Ledger-supported network + "calldata-PftNft.json", # enum keyed by "True"/"False" instead of integer field values (not encodable as uint8) +} ERC7730_V2_SCHEMA_PATH = ERC7730_REGISTRY_ROOT / "specs" / "erc7730-v2.schema.json" ERC7730_V2_SCHEMA = load_json_file(ERC7730_V2_SCHEMA_PATH) From c9c81f329c5a214f53029506bb80e75b3276fcda Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 12 Nov 2026 12:08:20 +0100 Subject: [PATCH 04/13] feat(BACK-12243): align EIP-712 calldata descriptors with latest V2 spec - bind EIP712_MESSAGE_INFO, ENUM_VALUE and MAP_ENTRY with DOMAIN_SEPARATOR and PRIMARY_TYPE_HASH - compute the domain separator per deployment (or use the given one) - struct/field versions set to 1, add EIP712_LEAF_SLICE and 17 elements path limit - support map lookups and key encoding for EIP-712 - validate EIP-712 schema, normalize constraints, reject @.value - fix map keys linter path converter - add tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../convert_erc7730_v2_input_to_calldata.py | 123 ++++++++++++++++-- .../convert/calldata/v1/eip712_path.py | 38 +++++- .../convert/calldata/v1/eip712_schema.py | 52 +++++++- src/erc7730/convert/calldata/v1/enum.py | 14 +- src/erc7730/convert/calldata/v1/map.py | 84 ++++++++++-- src/erc7730/convert/calldata/v1/selector.py | 2 +- src/erc7730/convert/calldata/v1/tlv.py | 117 +++++++++++------ src/erc7730/lint/v2/lint_validate_map_keys.py | 16 ++- src/erc7730/model/calldata/v1/descriptor.py | 14 ++ src/erc7730/model/calldata/v1/eip712.py | 49 ++++++- src/erc7730/model/calldata/v1/instruction.py | 86 ++++++++++-- src/erc7730/model/calldata/v1/value.py | 55 +++++++- .../convert/calldata/test_convert_eip712.py | 44 ++++++- .../v2/convert/calldata/test_convert_maps.py | 2 +- 14 files changed, 607 insertions(+), 89 deletions(-) diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index 372acaca..c09746d8 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -8,8 +8,9 @@ """ import hashlib -from typing import cast +from typing import Any, cast +from pydantic import BaseModel from pydantic_string_url import HttpUrl from erc7730.common.abi import ( @@ -24,7 +25,7 @@ from erc7730.common.output import ConsoleOutputAdder, OutputAdder, exception_to_output from erc7730.convert.calldata.v1.abi import function_to_abi_tree from erc7730.convert.calldata.v1.eip712_path import convert_eip712_data_path -from erc7730.convert.calldata.v1.eip712_schema import ReconstructedSchema, reconstruct_schema +from erc7730.convert.calldata.v1.eip712_schema import ReconstructedSchema, compute_domain_separator, reconstruct_schema from erc7730.convert.calldata.v1.enum import convert_enums from erc7730.convert.calldata.v1.map import MapEntries from erc7730.convert.calldata.v1.path import ( @@ -70,7 +71,10 @@ CalldataDescriptorParamV1, ) from erc7730.model.calldata.v1.value import ( + CalldataDescriptorContainerPathV1, + CalldataDescriptorContainerPathValueV1, CalldataDescriptorDataPathV1, + CalldataDescriptorEIP712PathV1, CalldataDescriptorPathElementLeafV1, CalldataDescriptorPathLeafType, CalldataDescriptorTypeFamily, @@ -88,6 +92,7 @@ from erc7730.model.resolved.v2.context import ( ResolvedContractContext, ResolvedDeployment, + ResolvedDomain, ResolvedEIP712Context, ) from erc7730.model.resolved.v2.descriptor import ResolvedERC7730Descriptor @@ -109,6 +114,9 @@ # length of an EVM address (ADDRESS_LENGTH in app-ethereum) ADDRESS_LENGTH = 20 +# length of a domain separator (keccak256 hash) +DOMAIN_SEPARATOR_LENGTH = 32 + def _describe(input_descriptor: InputERC7730Descriptor, source: HttpUrl | None) -> str: """Name a descriptor in a diagnostic. @@ -264,7 +272,7 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal ) # Use v1 convert_enums — v2 ResolvedDeployment is duck-type compatible with v1 - enums = convert_enums(deployment, selector, descriptor.metadata.enums) # type: ignore[arg-type] + enums = convert_enums(deployment, descriptor.metadata.enums, selector=selector) # type: ignore[arg-type] enums_by_id = {enum.enum_id: enum.id for enum in enums} maps = MapEntries(deployment, selector) @@ -401,6 +409,13 @@ def _convert_v2_field( ) ) is None: return None + if ( + isinstance(param.value, CalldataDescriptorValuePathV1) + and isinstance(param.value.binary_path, CalldataDescriptorEIP712PathV1) + and (constraints := _normalize_eip712_constraints(constraints, type_family, param.value.type_size, out)) + is None + ): + return None return [ CalldataDescriptorInstructionFieldV1(name=name, param=param, visibility=visibility, constraints=constraints) @@ -426,6 +441,44 @@ def _convert_v2_field( ) +def _normalize_eip712_constraints( + constraints: list[str], type_family: CalldataDescriptorTypeFamily, type_size: int | None, out: OutputAdder +) -> list[str] | None: + """ + Encode visibility constraints the way the device compares the leaf of a typed message: byte for byte, on the one + encoding a value has (see "Leaf encoding" in doc/eip712.md of app-ethereum-dev). + + :param constraints: hex encoded constraints, encoded for the type family + :param type_family: type family of the leaf + :param type_size: size of the type of the leaf, in bytes + :param out: error handler + :return: hex encoded constraints, or None on error + """ + normalized: list[str] = [] + for constraint in constraints: + payload = from_hex(constraint) + match type_family: + case CalldataDescriptorTypeFamily.UINT | CalldataDescriptorTypeFamily.INT: + # no leading zero byte, unless the value is zero (a leaf of the size of the type is a negative integer) + if type_family is CalldataDescriptorTypeFamily.UINT or len(payload) != type_size: + payload = payload.lstrip(b"\x00") or b"\x00" + case CalldataDescriptorTypeFamily.ADDRESS: + if len(payload) > ADDRESS_LENGTH: + return out.error( + title="Invalid visibility condition value", + message=f"An address constraint is {ADDRESS_LENGTH} bytes, {constraint} is {len(payload)}.", + ) + payload = payload.rjust(ADDRESS_LENGTH, b"\x00") + case CalldataDescriptorTypeFamily.BYTES if type_size is not None and len(payload) != type_size: + return out.error( + title="Invalid visibility condition value", + message=f"A bytes{type_size} constraint is exactly {type_size} bytes, {constraint} is " + f"{len(payload)}.", + ) + normalized.append(f"0x{payload.hex()}") + return normalized + + def _constrained_value_width(value: CalldataDescriptorValueV1) -> int | None: """ Byte length the device will compare a constraint against, when it can be determined statically. @@ -1081,6 +1134,8 @@ def _convert_eip712_descriptors( descriptor = _convert_eip712_message( descriptor=resolved_descriptor, deployment=deployment, + domain=domain, + domain_separator=resolved_context.eip712.domainSeparator, schema=schema, format=format, source=source, @@ -1096,6 +1151,8 @@ def _convert_eip712_descriptors( def _convert_eip712_message( descriptor: ResolvedERC7730Descriptor, deployment: ResolvedDeployment, + domain: ResolvedDomain | None, + domain_separator: str | None, schema: ReconstructedSchema, format: ResolvedFormat, source: HttpUrl | None, @@ -1106,6 +1163,8 @@ def _convert_eip712_message( :param descriptor: resolved v2 source ERC-7730 descriptor :param deployment: chain id / verifying contract address for which the descriptor is generated + :param domain: EIP-712 domain of the messages + :param domain_separator: domain separator given by the descriptor, computed from the domain when not set :param schema: reconstructed EIP-712 schema (structs + primary type hash) :param format: v2 resolved format for the message :param source: source of the descriptor file @@ -1128,18 +1187,50 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal else None ) - # TODO the ENUM_VALUE struct carries a SELECTOR tag whose meaning for EIP-712 messages is not defined in the - # specification; a zeroed selector is used until it is clarified. - enum_selector = Selector("0x00000000") - enums = convert_enums(deployment, enum_selector, descriptor.metadata.enums) # type: ignore[arg-type] + if domain_separator: + try: + separator_bytes = from_hex(domain_separator) + except ValueError: + separator_bytes = b"" + if len(separator_bytes) != DOMAIN_SEPARATOR_LENGTH: + return out.error( + title="Invalid domain separator", + message=f"Domain separator {domain_separator} must be a {DOMAIN_SEPARATOR_LENGTH} bytes hexadecimal " + "string.", + ) + domain_separator_hex = HexStr("0x" + separator_bytes.hex()) + elif (computed := compute_domain_separator(schema, domain, deployment, out)) is None: + return None + else: + domain_separator_hex = computed + + # enums and maps are provided to the device keyed by the message they are for + enums = convert_enums( + deployment, # type: ignore[arg-type] + descriptor.metadata.enums, + domain_separator=domain_separator_hex, + primary_type_hash=schema.primary_type_hash, + ) enums_by_id = {enum.enum_id: enum.id for enum in enums} + maps = MapEntries(deployment, domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash) fields: list[CalldataDescriptorInstructionFieldV1] = [] for input_field in format.fields: - if (output_fields := _convert_v2_field(convert_path, input_field, enums_by_id, out)) is None: + if ( + output_fields := _convert_v2_field( + convert_path=convert_path, field=input_field, enums=enums_by_id, maps=maps, out=out + ) + ) is None: return None fields.extend(output_fields) + # the device refuses a descriptor reading the value of the container, which a typed message does not have + if any(_reads_container_value(field) for field in fields): + return out.error( + title="Unsupported container path", + message="@.value cannot be used in an EIP-712 message, the device refuses it.", + ) + hash = hashlib.sha3_256() for field in fields: hash.update(from_hex(field.descriptor)) @@ -1149,6 +1240,7 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal message_info = CalldataDescriptorInstructionEIP712MessageInfoV1( chain_id=deployment.chainId, address=deployment.address, + domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash, hash=hash.digest().hex(), operation_type=first_not_none(format.intent, format.id, schema.primary_type), # type: ignore[arg-type] @@ -1164,9 +1256,24 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal network=cast(str, ledger_network_id(deployment.chainId)), chain_id=deployment.chainId, address=deployment.address, + domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash, schema_info=schema_info, message_info=message_info, enums=enums, + maps=maps.entries, fields=fields, ) + + +def _reads_container_value(model: Any) -> bool: + """Whether a serialized instruction holds a CONTAINER path reading the VALUE of the container.""" + match model: + case CalldataDescriptorContainerPathV1(value=CalldataDescriptorContainerPathValueV1.VALUE): + return True + case BaseModel(): + return any(_reads_container_value(getattr(model, name)) for name in type(model).model_fields) + case list(): + return any(_reads_container_value(item) for item in model) + case _: + return False diff --git a/src/erc7730/convert/calldata/v1/eip712_path.py b/src/erc7730/convert/calldata/v1/eip712_path.py index 4af27ba2..7e25f229 100644 --- a/src/erc7730/convert/calldata/v1/eip712_path.py +++ b/src/erc7730/convert/calldata/v1/eip712_path.py @@ -10,7 +10,9 @@ from erc7730.convert.calldata.v1.eip712_schema import ParsedSolidityType, parse_solidity_type from erc7730.model.calldata.v1.eip712 import CalldataDescriptorEIP712SolType from erc7730.model.calldata.v1.value import ( + MAX_EIP712_PATH_ELEMENTS, CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementLeafSliceV1, CalldataDescriptorEIP712PathElementStructFieldV1, CalldataDescriptorEIP712PathElementV1, CalldataDescriptorEIP712PathV1, @@ -36,6 +38,14 @@ } +# leaf types a leaf slice applies to +_SLICEABLE_LEAVES = ( + CalldataDescriptorEIP712SolType.BYTES_FIX, + CalldataDescriptorEIP712SolType.BYTES_DYN, + CalldataDescriptorEIP712SolType.STRING, +) + + def _leaf_type_family_size(parsed: ParsedSolidityType) -> tuple[CalldataDescriptorTypeFamily, int | None]: """Determine the VALUE type family and size (in bytes) from the leaf Solidity type.""" match parsed.sol_type: @@ -72,8 +82,10 @@ def convert_eip712_data_path( current_struct: str = primary_type current_parsed: ParsedSolidityType | None = None remaining_dims = 0 + leaf_sliced = False - for element in data_path.elements: + last_index = len(data_path.elements) - 1 + for position, element in enumerate(data_path.elements): match element: case Field(identifier=name): if current_parsed is not None: @@ -129,6 +141,20 @@ def convert_eip712_data_path( elements.append(CalldataDescriptorEIP712PathElementArraySliceV1(start=array_index, end=end)) remaining_dims -= 1 + case ArraySlice(start=start, end=end) if ( + remaining_dims == 0 + and position == last_index + and current_parsed is not None + and current_parsed.sol_type in _SLICEABLE_LEAVES + ): + if start is not None and end is not None and start >= 0 and end >= 0 and end <= start: + return out.error( + title="Invalid EIP-712 path", + message=f"Leaf slice [{start}:{end}] is empty, the device refuses a slice with no byte.", + ) + elements.append(CalldataDescriptorEIP712PathElementLeafSliceV1(start=start, end=end)) + leaf_sliced = True + case ArraySlice(start=start, end=end): if remaining_dims <= 0: return out.error( @@ -156,7 +182,17 @@ def convert_eip712_data_path( message=f'EIP-712 path ends on struct "{current_parsed.struct_name}"; a scalar leaf is required.', ) + if len(elements) > MAX_EIP712_PATH_ELEMENTS: + return out.error( + title="Invalid EIP-712 path", + message=f"EIP-712 path {data_path} has {len(elements)} elements, the device accepts at most " + f"{MAX_EIP712_PATH_ELEMENTS}.", + ) + type_family, type_size = _leaf_type_family_size(current_parsed) + if leaf_sliced: + # the size of a slice is not the size of the type it is cut from + type_size = None return CalldataDescriptorValuePathV1( type_family=type_family, diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py index 7b15e1ce..bc8ed8b3 100644 --- a/src/erc7730/convert/calldata/v1/eip712_schema.py +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -14,13 +14,14 @@ from eth_utils import keccak from erc7730.common.abi import parse_encode_type, to_encode_type +from erc7730.common.binary import from_hex from erc7730.common.output import OutputAdder from erc7730.model.calldata.v1.eip712 import ( CalldataDescriptorEIP712FieldV1, CalldataDescriptorEIP712SolType, CalldataDescriptorEIP712StructV1, ) -from erc7730.model.resolved.v2.context import ResolvedDomain +from erc7730.model.resolved.v2.context import ResolvedDeployment, ResolvedDomain from erc7730.model.types import HexStr @@ -186,3 +187,52 @@ def reconstruct_schema( types=types, structs=structs, ) + + +def compute_domain_separator( + schema: ReconstructedSchema, + domain: ResolvedDomain | None, + deployment: ResolvedDeployment, + out: OutputAdder, +) -> HexStr | None: + """ + Compute the domain separator, ``hashStruct(domain)``, of the messages of one deployment. + + The domain is made of the values of the descriptor domain, with the chain id and contract address of the + deployment. + + :param schema: reconstructed schema, which holds the type of the domain + :param domain: the resolved EIP-712 domain + :param deployment: deployment providing the chain id and verifying contract of the domain + :param out: error handler + :return: the domain separator, or None on error + """ + domain_fields = schema.types["EIP712Domain"] + domain_type = f"EIP712Domain({','.join(f'{type_str} {name}' for type_str, name in domain_fields)})" + + encoded = bytearray(keccak(text=domain_type)) + for _, name in domain_fields: + match name: + case "name" | "version": + value = getattr(domain, name) + encoded += keccak(text=value) + case "chainId": + encoded += deployment.chainId.to_bytes(32) + case "verifyingContract": + encoded += from_hex(deployment.address).rjust(32, b"\x00") + case "salt": + salt_hex = domain.salt if domain is not None else None + try: + salt = from_hex(salt_hex) if salt_hex is not None else b"" + except ValueError: + salt = b"" + if len(salt) != 32: + return out.error( + title="Invalid domain salt", + message=f"Domain salt {salt_hex} must be a 32 bytes hexadecimal string.", + ) + encoded += salt + case _: + raise ValueError(f"Unexpected domain field {name}") + + return HexStr("0x" + keccak(bytes(encoded)).hex()) diff --git a/src/erc7730/convert/calldata/v1/enum.py b/src/erc7730/convert/calldata/v1/enum.py index 3d78f6ab..2557ccc2 100644 --- a/src/erc7730/convert/calldata/v1/enum.py +++ b/src/erc7730/convert/calldata/v1/enum.py @@ -7,7 +7,7 @@ ) from erc7730.model.metadata import EnumDefinition from erc7730.model.resolved.context import ResolvedDeployment -from erc7730.model.types import Id, Selector +from erc7730.model.types import HexStr, Id, Selector # A bool holds 0 or 1 in calldata, and an enum key is the field value it matches, so these are # the keys a descriptor writes for a bool field. JSON has no bool object key, so they arrive as @@ -31,12 +31,20 @@ def enum_ordinal(ordinal: str) -> int: def convert_enums( - deployment: ResolvedDeployment, selector: Selector, enums: dict[Id, EnumDefinition] | None + deployment: ResolvedDeployment, + enums: dict[Id, EnumDefinition] | None, + selector: Selector | None = None, + domain_separator: HexStr | None = None, + primary_type_hash: HexStr | None = None, ) -> list[CalldataDescriptorInstructionEnumValueV1]: """ Convert descriptor enum definitions to calldata descriptor enum value instructions. + @param deployment: deployment the enums are bound to @param enums: descriptor enum definitions + @param selector: function selector the enums are bound to (transactions) + @param domain_separator: domain separator the enums are bound to (EIP-712 messages) + @param primary_type_hash: primary type hash the enums are bound to (EIP-712 messages) @return: instructions for each enum entry """ if enums is None: @@ -47,6 +55,8 @@ def convert_enums( chain_id=deployment.chainId, address=deployment.address, selector=selector, + domain_separator=domain_separator, + primary_type_hash=primary_type_hash, id=i, enum_id=enum_id, value=enum_ordinal(ordinal), diff --git a/src/erc7730/convert/calldata/v1/map.py b/src/erc7730/convert/calldata/v1/map.py index b7d85d91..16d910aa 100644 --- a/src/erc7730/convert/calldata/v1/map.py +++ b/src/erc7730/convert/calldata/v1/map.py @@ -9,11 +9,14 @@ - the chain id is a 64 bits big endian integer, the sender / target addresses are 20 bytes, the native value is a 256 bits big endian integer +In a typed message, the key is the leaf as the host sends it (see "Leaf encoding" in doc/eip712.md): an integer in its +minimal big-endian form (``7`` is ``0x07``), a ``bytesN`` on exactly N bytes, an address on 20 bytes. + See doc/tlv_structs.md#map_entry in https://github.com/LedgerHQ/app-ethereum for specifications of these structs. """ from collections.abc import Callable -from typing import assert_never +from typing import Any, assert_never from erc7730.common.abi import ABIDataType from erc7730.common.binary import from_hex @@ -25,6 +28,8 @@ CalldataDescriptorContainerPathV1, CalldataDescriptorContainerPathValueV1, CalldataDescriptorDataPathV1, + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathV1, CalldataDescriptorMapRefV1, CalldataDescriptorPathElementArrayV1, CalldataDescriptorPathElementLeafV1, @@ -60,16 +65,25 @@ class MapEntries: """ - Device side maps of a calldata descriptor (bound to a single deployment and selector). + Device side maps of a calldata descriptor, bound to a single deployment and either a selector (transaction), or the + domain separator and primary type hash of the message (EIP-712 message). Map ids are allocated per descriptor: a map looked up several times with the same key and value encodings shares its id and MAP_ENTRY structs, a map looked up with different encodings (for instance its values read as addresses in one field and as strings in another) gets one id per encoding. """ - def __init__(self, deployment: ResolvedDeployment, selector: Selector) -> None: + def __init__( + self, + deployment: ResolvedDeployment, + selector: Selector | None = None, + domain_separator: HexStr | None = None, + primary_type_hash: HexStr | None = None, + ) -> None: self.deployment = deployment self.selector = selector + self.domain_separator = domain_separator + self.primary_type_hash = primary_type_hash self.entries: list[CalldataDescriptorInstructionMapEntryV1] = [] self._ids: dict[tuple[str, tuple[tuple[bytes, bytes], ...]], int] = {} @@ -121,6 +135,8 @@ def map_ref( chain_id=self.deployment.chainId, address=Address(self.deployment.address), selector=self.selector, + domain_separator=self.domain_separator, + primary_type_hash=self.primary_type_hash, map=map_name, id=map_id, key_source=key_source, @@ -197,15 +213,20 @@ def _convert_key_path( case DataPath() as data_path: if (key := convert_path(data_path, out)) is None: return None - if not isinstance(key.binary_path, CalldataDescriptorDataPathV1): + if isinstance(key.binary_path, CalldataDescriptorEIP712PathV1): + path_elements: list[Any] = list(key.binary_path.elements) + elif isinstance(key.binary_path, CalldataDescriptorDataPathV1): + path_elements = list(key.binary_path.elements) + else: return out.error( title="Unsupported map key", - message=f"Path {data_path} used as key of map {value_map.map} cannot be looked up by the " - "device: maps are only supported on transaction fields.", + message=f"Path {data_path} cannot be used as key of map {value_map.map}.", ) # the device looks up a single key: it rejects a path reading several values - for element in key.binary_path.elements: - if isinstance(element, CalldataDescriptorPathElementArrayV1) and not _is_single_element(element): + for element in path_elements: + if isinstance( + element, CalldataDescriptorPathElementArrayV1 | CalldataDescriptorEIP712PathElementArraySliceV1 + ) and not _is_single_element(element): return out.error( title="Unsupported map key", message=f"Path {data_path} used as key of map {value_map.map} references several values, a " @@ -217,7 +238,9 @@ def _convert_key_path( assert_never(value_map.keyPath) -def _is_single_element(element: CalldataDescriptorPathElementArrayV1) -> bool: +def _is_single_element( + element: CalldataDescriptorPathElementArrayV1 | CalldataDescriptorEIP712PathElementArraySliceV1, +) -> bool: """Whether an array path element selects a single array element.""" match element.start, element.end: case int(start), int(end): @@ -281,10 +304,53 @@ def invalid(reason: str) -> bytes | None: return _encode_static_key(key_source, key, invalid) return _encode_dynamic_key(key_source, key, invalid) + case CalldataDescriptorEIP712PathV1(): + return _encode_eip712_key(key_source, key, invalid) + case _: assert_never(key.binary_path) +def _encode_eip712_key(key_source: str, key: CalldataDescriptorValuePathV1, invalid: _Invalid) -> bytes | None: + """Encode a key read from a leaf of a typed message: the device compares the leaf as the host sends it.""" + size = key.type_size + match key.type_family: + case CalldataDescriptorTypeFamily.UINT | CalldataDescriptorTypeFamily.INT: + if (value := _parse_int(key_source)) is None: + return invalid("expected an integer") + if size is None: + return invalid("the size of the integer is unknown") + if key.type_family is CalldataDescriptorTypeFamily.UINT: + if value < 0: + return invalid("expected an unsigned integer") + if value.bit_length() > size * 8: + return invalid(f"it does not fit in {size} bytes") + elif not -(1 << (size * 8 - 1)) <= value < 1 << (size * 8 - 1): + return invalid(f"it does not fit in {size} bytes") + if value < 0: + # a negative integer takes exactly the size of its type, which is how the device tells its sign + return _check_key_size(value.to_bytes(size, byteorder="big", signed=True), invalid) + return _check_key_size(value.to_bytes(max(1, (value.bit_length() + 7) // 8), byteorder="big"), invalid) + case CalldataDescriptorTypeFamily.ADDRESS: + if (address := _encode_hex(key_source, ADDRESS_LENGTH, invalid)) is None: + return None + if len(address) != ADDRESS_LENGTH: + return invalid(f"an address is exactly {ADDRESS_LENGTH} bytes") + return address + case CalldataDescriptorTypeFamily.BOOL: + return _encode_bool(key_source, invalid) + case CalldataDescriptorTypeFamily.BYTES: + if (hex_encoded := _encode_hex(key_source, MAX_MAP_ENTRY_SIZE, invalid)) is None: + return None + if size is not None and len(hex_encoded) != size: + return invalid(f"a bytes{size} value is exactly {size} bytes, got {len(hex_encoded)}") + return _check_key_size(hex_encoded, invalid) + case CalldataDescriptorTypeFamily.STRING: + return _check_key_size(key_source.encode("utf-8"), invalid) + case _: + return invalid(f"{key.type_family.name.lower()} keys are not supported") + + def _encode_static_key(key_source: str, key: CalldataDescriptorValuePathV1, invalid: _Invalid) -> bytes | None: """Encode a key read from a static calldata value: the device reads the whole ABI encoded chunk.""" match key.type_family: diff --git a/src/erc7730/convert/calldata/v1/selector.py b/src/erc7730/convert/calldata/v1/selector.py index dda3ab40..beb38f44 100644 --- a/src/erc7730/convert/calldata/v1/selector.py +++ b/src/erc7730/convert/calldata/v1/selector.py @@ -62,7 +62,7 @@ def convert_selector( creator_url = owner_info.url deploy_date = owner_info.deploymentDate.strftime("%Y-%m-%dT%H:%M:%SZ") if owner_info.deploymentDate else None - enums = convert_enums(deployment, selector, descriptor.metadata.enums) + enums = convert_enums(deployment, descriptor.metadata.enums, selector=selector) enums_by_id = {enum.enum_id: enum.id for enum in enums} diff --git a/src/erc7730/convert/calldata/v1/tlv.py b/src/erc7730/convert/calldata/v1/tlv.py index 48333030..ac0abce4 100644 --- a/src/erc7730/convert/calldata/v1/tlv.py +++ b/src/erc7730/convert/calldata/v1/tlv.py @@ -43,11 +43,12 @@ from erc7730.model.calldata.v1.value import ( CalldataDescriptorContainerPathV1, CalldataDescriptorDataPathV1, - CalldataDescriptorMapRefV1, CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementLeafSliceV1, CalldataDescriptorEIP712PathElementStructFieldV1, CalldataDescriptorEIP712PathElementV1, CalldataDescriptorEIP712PathV1, + CalldataDescriptorMapRefV1, CalldataDescriptorPathElementArrayV1, CalldataDescriptorPathElementLeafV1, CalldataDescriptorPathElementRefV1, @@ -63,8 +64,8 @@ @pydantic_enum_by_name class CalldataDescriptorTransactionInfoTag(IntEnum): - # TRANSACTION_INFO and EIP712_MESSAGE_INFO share this structure; tag 0x03 is context-dependent, carrying a - # SELECTOR (SignTx) or a PRIMARY_TYPE_HASH (EIP-712 message, see CalldataDescriptorEIP712MessageInfoTag). + # OPERATION_INFO is TRANSACTION_INFO or EIP712_MESSAGE_INFO depending on its context: CHAIN_ID, CONTRACT_ADDR and + # SELECTOR are for a transaction only, DOMAIN_SEPARATOR and PRIMARY_TYPE_HASH for an EIP-712 message only. VERSION = 0x00 CHAIN_ID = 0x01 CONTRACT_ADDR = 0x02 @@ -76,15 +77,11 @@ class CalldataDescriptorTransactionInfoTag(IntEnum): CREATOR_URL = 0x08 CONTRACT_NAME = 0x09 DEPLOY_DATE = 0x0A + DOMAIN_SEPARATOR = 0x0B + PRIMARY_TYPE_HASH = 0x0C SIGNATURE = 0xFF -@pydantic_enum_by_name -class CalldataDescriptorEIP712MessageInfoTag(IntEnum): - # EIP712_MESSAGE_INFO reuses the TRANSACTION_INFO tags; only tag 0x03 differs (same value as SELECTOR). - PRIMARY_TYPE_HASH = 0x03 - - @pydantic_enum_by_name class CalldataDescriptorEIP712SchemaTag(IntEnum): VERSION = 0x00 @@ -113,6 +110,7 @@ class CalldataDescriptorEIP712PathTag(IntEnum): VERSION = 0x00 EIP712_STRUCT_FIELD = 0x01 EIP712_ARRAY_SLICE = 0x02 + EIP712_LEAF_SLICE = 0x03 @pydantic_enum_by_name @@ -121,6 +119,12 @@ class CalldataDescriptorEIP712ArraySliceTag(IntEnum): END = 0x02 +@pydantic_enum_by_name +class CalldataDescriptorEIP712LeafSliceTag(IntEnum): + START = 0x01 + END = 0x02 + + @pydantic_enum_by_name class CalldataDescriptorEnumValueTag(IntEnum): VERSION = 0x00 @@ -130,6 +134,8 @@ class CalldataDescriptorEnumValueTag(IntEnum): ID = 0x04 VALUE = 0x05 NAME = 0x06 + DOMAIN_SEPARATOR = 0x07 + PRIMARY_TYPE_HASH = 0x08 @pydantic_enum_by_name @@ -141,6 +147,8 @@ class CalldataDescriptorMapEntryTag(IntEnum): ID = 0x04 KEY = 0x05 VALUE = 0x06 + DOMAIN_SEPARATOR = 0x07 + PRIMARY_TYPE_HASH = 0x08 SIGNATURE = 0xFF @@ -286,27 +294,15 @@ class CalldataDescriptorPathSliceElementTag(IntEnum): END = 0x02 -def _tlv_transaction_info_base( - obj: CalldataDescriptorInstructionTransactionInfoBaseV1, - target_tag: CalldataDescriptorTransactionInfoTag | CalldataDescriptorEIP712MessageInfoTag, - target_value: bytes, -) -> bytes: +def _tlv_operation_info_body(obj: CalldataDescriptorInstructionTransactionInfoBaseV1) -> bytes: """ - Encode the structure shared by TRANSACTION_INFO and EIP712_MESSAGE_INFO. - - The two structs share every tag but tag 0x03, which identifies what the descriptor applies to (a function - selector or an EIP-712 message primary type), passed by the caller. + Encode the tags TRANSACTION_INFO and EIP712_MESSAGE_INFO have in common, which are all but the VERSION and the tags + identifying the operation. @param obj: object representation of struct - @param target_tag: tag 0x03 (SELECTOR or PRIMARY_TYPE_HASH) - @param target_value: payload for tag 0x03 - @return: encoded struct TLV + @return: encoded tags TLV """ out = bytearray() - out += tlv(CalldataDescriptorTransactionInfoTag.VERSION, obj.version.to_bytes(1)) - out += tlv(CalldataDescriptorTransactionInfoTag.CHAIN_ID, obj.chain_id.to_bytes(8)) - out += tlv(CalldataDescriptorTransactionInfoTag.CONTRACT_ADDR, from_hex(obj.address)) - out += tlv(target_tag, target_value) out += tlv(CalldataDescriptorTransactionInfoTag.FIELDS_HASH, from_hex(obj.hash)) out += tlv(CalldataDescriptorTransactionInfoTag.OPERATION_TYPE, obj.operation_type) @@ -336,22 +332,31 @@ def tlv_transaction_info(obj: CalldataDescriptorInstructionTransactionInfoV1) -> @param obj: object representation of struct @return: encoded struct TLV """ - return _tlv_transaction_info_base(obj, CalldataDescriptorTransactionInfoTag.SELECTOR, from_hex(obj.selector)) + out = bytearray() + out += tlv(CalldataDescriptorTransactionInfoTag.VERSION, obj.version.to_bytes(1)) + out += tlv(CalldataDescriptorTransactionInfoTag.CHAIN_ID, obj.chain_id.to_bytes(8)) + out += tlv(CalldataDescriptorTransactionInfoTag.CONTRACT_ADDR, from_hex(obj.address)) + out += tlv(CalldataDescriptorTransactionInfoTag.SELECTOR, from_hex(obj.selector)) + out += _tlv_operation_info_body(obj) + return out def tlv_eip712_message_info(obj: CalldataDescriptorInstructionEIP712MessageInfoV1) -> bytes: """ - Encode a struct of type EIP712_MESSAGE_INFO. + Encode a struct of type EIP712_MESSAGE_INFO (without its signature, which is computed by CAL). - Same wire structure as TRANSACTION_INFO, except tag 0x03 carries the primary type hash (32 bytes) instead of a - function selector. + The device refuses CHAIN_ID, CONTRACT_ADDR and SELECTOR in a message info: it is bound to the message by the + domain separator and the primary type hash. @param obj: object representation of struct @return: encoded struct TLV """ - return _tlv_transaction_info_base( - obj, CalldataDescriptorEIP712MessageInfoTag.PRIMARY_TYPE_HASH, from_hex(obj.primary_type_hash) - ) + out = bytearray() + out += tlv(CalldataDescriptorTransactionInfoTag.VERSION, obj.version.to_bytes(1)) + out += _tlv_operation_info_body(obj) + out += tlv(CalldataDescriptorTransactionInfoTag.DOMAIN_SEPARATOR, from_hex(obj.domain_separator)) + out += tlv(CalldataDescriptorTransactionInfoTag.PRIMARY_TYPE_HASH, from_hex(obj.primary_type_hash)) + return out def tlv_eip712_schema(obj: CalldataDescriptorInstructionEIP712SchemaV1) -> bytes: @@ -376,7 +381,7 @@ def tlv_eip712_struct(obj: CalldataDescriptorEIP712StructV1) -> bytes: @return: encoded struct TLV """ out = bytearray() - out += tlv(CalldataDescriptorEIP712StructTag.VERSION, (0).to_bytes(1)) + out += tlv(CalldataDescriptorEIP712StructTag.VERSION, (1).to_bytes(1)) out += tlv(CalldataDescriptorEIP712StructTag.NAME, obj.name) for field in obj.fields: out += tlv(CalldataDescriptorEIP712StructTag.EIP712_FIELD, tlv_eip712_field(field)) @@ -391,7 +396,7 @@ def tlv_eip712_field(obj: CalldataDescriptorEIP712FieldV1) -> bytes: @return: encoded struct TLV """ out = bytearray() - out += tlv(CalldataDescriptorEIP712FieldTag.VERSION, (0).to_bytes(1)) + out += tlv(CalldataDescriptorEIP712FieldTag.VERSION, (1).to_bytes(1)) out += tlv(CalldataDescriptorEIP712FieldTag.NAME, obj.name) out += tlv(CalldataDescriptorEIP712FieldTag.TYPE, obj.sol_type.value.to_bytes(1)) @@ -403,8 +408,8 @@ def tlv_eip712_field(obj: CalldataDescriptorEIP712FieldV1) -> bytes: # empty payload marks a dynamic dimension out += tlv(CalldataDescriptorEIP712FieldTag.ARRAY_DIM) else: - # TODO spec declares ARRAY_DIM as uint32 but examples encode it minimally (T[2] -> 04 01 02); encoded - # here as minimal big-endian (>= 1 byte) to match the spec examples, pending clarification + # a fixed dimension is minimal big-endian on at least one byte (T[0] -> 04 01 00, T[2] -> 04 01 02), as an + # empty payload is a dynamic dimension length = max(1, (dimension.bit_length() + 7) // 8) out += tlv(CalldataDescriptorEIP712FieldTag.ARRAY_DIM, dimension.to_bytes(length)) @@ -414,6 +419,25 @@ def tlv_eip712_field(obj: CalldataDescriptorEIP712FieldV1) -> bytes: return out +def _tlv_operation_context( + tags: type[CalldataDescriptorEnumValueTag] | type[CalldataDescriptorMapEntryTag], + obj: CalldataDescriptorInstructionEnumValueV1 | CalldataDescriptorInstructionMapEntryV1, +) -> bytes: + """ + Encode the tags binding an ENUM_VALUE or MAP_ENTRY to an operation: chain, contract and selector for a + transaction, domain separator and primary type hash for an EIP-712 message, and none of the other. + """ + out = bytearray() + if obj.selector is not None: + out += tlv(tags["CHAIN_ID"], obj.chain_id.to_bytes(8)) + out += tlv(tags["CONTRACT_ADDR"], from_hex(obj.address)) + out += tlv(tags["SELECTOR"], from_hex(obj.selector)) + elif obj.domain_separator is not None and obj.primary_type_hash is not None: + out += tlv(tags["DOMAIN_SEPARATOR"], from_hex(obj.domain_separator)) + out += tlv(tags["PRIMARY_TYPE_HASH"], from_hex(obj.primary_type_hash)) + return out + + def tlv_enum_value(obj: CalldataDescriptorInstructionEnumValueV1) -> bytes: """ Encode a struct of type ENUM_VALUE. @@ -423,9 +447,7 @@ def tlv_enum_value(obj: CalldataDescriptorInstructionEnumValueV1) -> bytes: """ out = bytearray() out += tlv(CalldataDescriptorEnumValueTag.VERSION, obj.version.to_bytes(1)) - out += tlv(CalldataDescriptorEnumValueTag.CHAIN_ID, obj.chain_id.to_bytes(8)) - out += tlv(CalldataDescriptorEnumValueTag.CONTRACT_ADDR, from_hex(obj.address)) - out += tlv(CalldataDescriptorEnumValueTag.SELECTOR, from_hex(obj.selector)) + out += _tlv_operation_context(CalldataDescriptorEnumValueTag, obj) out += tlv(CalldataDescriptorEnumValueTag.ID, obj.id.to_bytes(1)) out += tlv(CalldataDescriptorEnumValueTag.VALUE, obj.value.to_bytes(1)) out += tlv(CalldataDescriptorEnumValueTag.NAME, obj.name) @@ -441,9 +463,7 @@ def tlv_map_entry(obj: CalldataDescriptorInstructionMapEntryV1) -> bytes: """ out = bytearray() out += tlv(CalldataDescriptorMapEntryTag.VERSION, obj.version.to_bytes(1)) - out += tlv(CalldataDescriptorMapEntryTag.CHAIN_ID, obj.chain_id.to_bytes(8)) - out += tlv(CalldataDescriptorMapEntryTag.CONTRACT_ADDR, from_hex(obj.address)) - out += tlv(CalldataDescriptorMapEntryTag.SELECTOR, from_hex(obj.selector)) + out += _tlv_operation_context(CalldataDescriptorMapEntryTag, obj) out += tlv(CalldataDescriptorMapEntryTag.ID, obj.id.to_bytes(1)) out += tlv(CalldataDescriptorMapEntryTag.KEY, from_hex(obj.key)) out += tlv(CalldataDescriptorMapEntryTag.VALUE, from_hex(obj.value)) @@ -840,7 +860,7 @@ def tlv_data_path_element(obj: CalldataDescriptorPathElementV1) -> bytes: def tlv_eip712_path_element(obj: CalldataDescriptorEIP712PathElementV1) -> bytes: """ - Encode an element of an EIP712_PATH (either a struct field index or an array slice). + Encode an element of an EIP712_PATH (a struct field index, an array slice or a leaf slice). @param obj: object representation of struct @return: encoded struct TLV @@ -861,6 +881,17 @@ def tlv_eip712_path_element(obj: CalldataDescriptorEIP712PathElementV1) -> bytes out += tlv(CalldataDescriptorEIP712PathTag.EIP712_ARRAY_SLICE, bytes(slice_out)) + case CalldataDescriptorEIP712PathElementLeafSliceV1() as leaf_slice: + slice_out = bytearray() + + if (start := leaf_slice.start) is not None: + slice_out += tlv(CalldataDescriptorEIP712LeafSliceTag.START, start.to_bytes(2, signed=True)) + + if (end := leaf_slice.end) is not None: + slice_out += tlv(CalldataDescriptorEIP712LeafSliceTag.END, end.to_bytes(2, signed=True)) + + out += tlv(CalldataDescriptorEIP712PathTag.EIP712_LEAF_SLICE, bytes(slice_out)) + case _: assert_never(obj) return out diff --git a/src/erc7730/lint/v2/lint_validate_map_keys.py b/src/erc7730/lint/v2/lint_validate_map_keys.py index be63a12b..e9e61200 100644 --- a/src/erc7730/lint/v2/lint_validate_map_keys.py +++ b/src/erc7730/lint/v2/lint_validate_map_keys.py @@ -5,10 +5,11 @@ be encodable as the value at the key path (for instance, a uint32 key must fit in 4 bytes). """ +from collections.abc import Callable from typing import assert_never, final, override from erc7730.common.output import OutputAdder -from erc7730.convert.calldata.v1.abi import function_to_abi_tree +from erc7730.convert.calldata.v1.abi import ABITree, function_to_abi_tree from erc7730.convert.calldata.v1.map import encode_map_keys from erc7730.convert.calldata.v1.path import convert_data_path from erc7730.convert.resolved.v2.values import is_deployment_key @@ -53,12 +54,8 @@ def lint( continue # only built when needed: some ABI types (fixed point numbers) cannot be converted to a tree abi_tree = function_to_abi_tree(abi) - - def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorValuePathV1 | None: - return convert_data_path(data_path, abi_tree, out) - for value_map in value_maps: - encode_map_keys(value_map, convert_path, out) + encode_map_keys(value_map, _path_converter(abi_tree), out) case _: assert_never(descriptor.context) @@ -78,3 +75,10 @@ def _value_maps(field: ResolvedField) -> list[ResolvedValueMap]: return [value_map for sub_field in field.fields for value_map in _value_maps(sub_field)] case _: assert_never(field) + + +def _path_converter(abi_tree: ABITree) -> Callable[[DataPath, OutputAdder], CalldataDescriptorValuePathV1 | None]: + def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorValuePathV1 | None: + return convert_data_path(data_path, abi_tree, out) + + return convert_path diff --git a/src/erc7730/model/calldata/v1/descriptor.py b/src/erc7730/model/calldata/v1/descriptor.py index 4aadea67..b1977bfc 100644 --- a/src/erc7730/model/calldata/v1/descriptor.py +++ b/src/erc7730/model/calldata/v1/descriptor.py @@ -90,6 +90,13 @@ class CalldataDescriptorEIP712V1(CalldataDescriptorBase): "descriptor specification)", ) + domain_separator: HexStr = Field( + title="Domain separator", + description="hashStruct(domain) of the EIP-712 message domain.", + min_length=64, + max_length=66, + ) + primary_type_hash: HexStr = Field( title="Primary type hash", description="keccak256(encodeType(primaryType)) of the EIP-712 message primary type.", @@ -112,6 +119,13 @@ class CalldataDescriptorEIP712V1(CalldataDescriptorBase): description="Descriptor and metadata to craft ENUM APDUs.", ) + maps: list[CalldataDescriptorInstructionMapEntryV1] = Field( + default_factory=list, + title="MAP_ENTRY instructions descriptors", + description="Descriptor and metadata to craft MAP_ENTRY APDUs, one per key of the maps looked up by the " + "device. Only the entries matching the keys read from the message need to be provided.", + ) + fields: list[CalldataDescriptorInstructionFieldV1] = Field( title="EIP712_FIELD_DESCRIPTOR instructions descriptors", description="Descriptor and metadata to craft EIP712_FIELD_DESCRIPTOR APDUs.", diff --git a/src/erc7730/model/calldata/v1/eip712.py b/src/erc7730/model/calldata/v1/eip712.py index 77a71654..d3bde631 100644 --- a/src/erc7730/model/calldata/v1/eip712.py +++ b/src/erc7730/model/calldata/v1/eip712.py @@ -8,9 +8,9 @@ from enum import IntEnum from functools import cached_property -from typing import Literal +from typing import Literal, Self -from pydantic import Field, computed_field +from pydantic import Field, computed_field, model_validator from erc7730.common.pydantic import pydantic_enum_by_name from erc7730.model.base import Model @@ -34,6 +34,18 @@ class CalldataDescriptorEIP712SolType(IntEnum): BYTES_DYN = 0x07 +# limits of the device (doc/eip712.md#implementation-limits in app-ethereum-dev) +MAX_ARRAY_DIMENSIONS = 8 +MAX_ARRAY_DIMENSION_SIZE = 255 + +# base types carrying a TYPE_SIZE +_SIZED_TYPES = ( + CalldataDescriptorEIP712SolType.INT, + CalldataDescriptorEIP712SolType.UINT, + CalldataDescriptorEIP712SolType.BYTES_FIX, +) + + class CalldataDescriptorEIP712FieldV1(Model): """Descriptor for the EIP712_FIELD struct (one field of an EIP-712 struct type).""" @@ -70,6 +82,20 @@ class CalldataDescriptorEIP712FieldV1(Model): description="Referenced struct name, only set if the type is STRUCT.", ) + @model_validator(mode="after") + def _validate_field(self) -> Self: + if any(c in self.name for c in "(),"): + raise ValueError(f'Field name "{self.name}" cannot contain "(", ")" or ",".') + if (self.sol_type in _SIZED_TYPES) != (self.type_size is not None): + raise ValueError(f"A type size is required for INT, UINT and BYTES_FIX only, got {self.sol_type.name}.") + if (self.sol_type == CalldataDescriptorEIP712SolType.STRUCT) != (self.struct_name is not None): + raise ValueError(f"A struct name is required for STRUCT only, got {self.sol_type.name}.") + if len(self.array_dimensions) > MAX_ARRAY_DIMENSIONS: + raise ValueError(f"At most {MAX_ARRAY_DIMENSIONS} array dimensions are supported per field.") + if any(d is not None and not 0 <= d <= MAX_ARRAY_DIMENSION_SIZE for d in self.array_dimensions): + raise ValueError(f"Fixed array dimensions must be between 0 and {MAX_ARRAY_DIMENSION_SIZE}.") + return self + class CalldataDescriptorEIP712StructV1(Model): """Descriptor for the EIP712_STRUCT struct (one EIP-712 struct type declaration).""" @@ -85,6 +111,15 @@ class CalldataDescriptorEIP712StructV1(Model): description="One entry per declared field, in declaration order.", ) + @model_validator(mode="after") + def _validate_struct(self) -> Self: + if any(c in self.name for c in " ()[],"): + raise ValueError(f'Struct name "{self.name}" cannot contain a space or any of "(", ")", "[", "]", ",".') + names = [f.name for f in self.fields] + if len(set(names)) != len(names): + raise ValueError(f'Struct "{self.name}" has several fields of the same name.') + return self + class CalldataDescriptorInstructionEIP712SchemaV1(CalldataDescriptorInstructionBaseV1): """Instruction descriptor for the EIP712_SCHEMA struct (whole schema, all struct types nested).""" @@ -98,8 +133,18 @@ class CalldataDescriptorInstructionEIP712SchemaV1(CalldataDescriptorInstructionB structs: list[CalldataDescriptorEIP712StructV1] = Field( title="Structs", description="One entry per declared struct type.", + min_length=1, ) + @model_validator(mode="after") + def _validate_schema(self) -> Self: + names = [struct.name for struct in self.structs] + if len(set(names)) != len(names): + raise ValueError("The schema has several structs of the same name.") + if "EIP712Domain" not in names: + raise ValueError("The schema must contain the EIP712Domain struct.") + return self + @computed_field(title="Descriptor", description="Hex encoded EIP712_SCHEMA TLV struct") # type: ignore[misc] @cached_property def descriptor(self) -> CalldataDescriptorInstructionHex: diff --git a/src/erc7730/model/calldata/v1/instruction.py b/src/erc7730/model/calldata/v1/instruction.py index 251d074e..b2e78ad5 100644 --- a/src/erc7730/model/calldata/v1/instruction.py +++ b/src/erc7730/model/calldata/v1/instruction.py @@ -64,6 +64,20 @@ class CalldataDescriptorFieldVisibilityV1(IntEnum): IF_NOT_IN = 0x02 +def _validate_operation_context( + selector: str | None, domain_separator: str | None, primary_type_hash: str | None +) -> None: + """ + Check an ENUM_VALUE / MAP_ENTRY is bound to exactly one kind of operation: a transaction (selector), or an EIP-712 + message (domain separator and primary type hash). The device refuses a struct with tags of both, or of none. + """ + if selector is not None: + if domain_separator is not None or primary_type_hash is not None: + raise ValueError("A selector cannot be combined with a domain separator or a primary type hash.") + elif domain_separator is None or primary_type_hash is None: + raise ValueError("Either a selector, or both a domain separator and a primary type hash, are required.") + + # extra must be ignored because of descriptor computed field class CalldataDescriptorInstructionBaseV1(CalldataDescriptorStructV1, ABC, extra="ignore"): """Base class for calldata descriptor instructions.""" @@ -73,8 +87,9 @@ class CalldataDescriptorInstructionTransactionInfoBaseV1(CalldataDescriptorInstr """ Common fields for the TRANSACTION_INFO / EIP712_MESSAGE_INFO structs. - These two structs share the same wire structure and are handled as a single structure in the Ethereum app; they - differ only by tag 0x03 (SELECTOR for calldata, PRIMARY_TYPE_HASH for EIP-712 messages). + These two structs are the OPERATION_INFO structure of the Ethereum app in two contexts: they share every tag but + the ones identifying the operation (CHAIN_ID, CONTRACT_ADDR and SELECTOR for a transaction, DOMAIN_SEPARATOR and + PRIMARY_TYPE_HASH for an EIP-712 message). """ version: Literal[1] = Field( @@ -170,10 +185,19 @@ class CalldataDescriptorInstructionEIP712MessageInfoV1(CalldataDescriptorInstruc """ Instruction descriptor for the EIP712_MESSAGE_INFO struct. - Same wire structure as TRANSACTION_INFO, except tag 0x03 carries the EIP-712 primary type hash (32 bytes) instead - of a function selector (4 bytes). Referred to as "EIP712 v2" in the Ethereum app specifications. + The OPERATION_INFO structure in the context of an EIP-712 message: it is bound to the message by its domain + separator and primary type hash, and carries neither chain id, contract address nor selector on the wire (they + are only kept as metadata of the deployment the domain separator was computed for). Referred to as "EIP712 v2" in + the Ethereum app specifications. """ + domain_separator: HexStr = Field( + title="Domain separator", + description="hashStruct(domain) of the EIP-712 message domain.", + min_length=64, + max_length=66, + ) + primary_type_hash: HexStr = Field( title="Primary type hash", description="keccak256(encodeType(primaryType)) of the EIP-712 message primary type.", @@ -211,11 +235,34 @@ class CalldataDescriptorInstructionEnumValueV1(CalldataDescriptorInstructionBase description="The contract deployment address.", ) - selector: Selector = Field( + selector: Selector | None = Field( + default=None, title="Function selector", - description="The 4-bytes function selector this descriptor applies to.", + description="The 4-bytes function selector this descriptor applies to (transactions only).", + ) + + domain_separator: HexStr | None = Field( + default=None, + title="Domain separator", + description="hashStruct(domain) of the EIP-712 message this descriptor applies to (EIP-712 messages only).", + min_length=64, + max_length=66, + ) + + primary_type_hash: HexStr | None = Field( + default=None, + title="Primary type hash", + description="keccak256(encodeType(primaryType)) of the EIP-712 message this descriptor applies to (EIP-712 " + "messages only).", + min_length=64, + max_length=66, ) + @model_validator(mode="after") + def _validate_context(self) -> Self: + _validate_operation_context(self.selector, self.domain_separator, self.primary_type_hash) + return self + enum_id: str = Field( title="Source enum identifier", description="Source identifier of the enum (to differentiate multiple enums in one contract)", @@ -275,11 +322,34 @@ class CalldataDescriptorInstructionMapEntryV1(CalldataDescriptorInstructionBaseV description="The contract deployment address.", ) - selector: Selector = Field( + selector: Selector | None = Field( + default=None, title="Function selector", - description="The 4-bytes function selector this descriptor applies to.", + description="The 4-bytes function selector this descriptor applies to (transactions only).", ) + domain_separator: HexStr | None = Field( + default=None, + title="Domain separator", + description="hashStruct(domain) of the EIP-712 message this descriptor applies to (EIP-712 messages only).", + min_length=64, + max_length=66, + ) + + primary_type_hash: HexStr | None = Field( + default=None, + title="Primary type hash", + description="keccak256(encodeType(primaryType)) of the EIP-712 message this descriptor applies to (EIP-712 " + "messages only).", + min_length=64, + max_length=66, + ) + + @model_validator(mode="after") + def _validate_context(self) -> Self: + _validate_operation_context(self.selector, self.domain_separator, self.primary_type_hash) + return self + map: str = Field( title="Source map reference", description="Path of the map in the source descriptor.", diff --git a/src/erc7730/model/calldata/v1/value.py b/src/erc7730/model/calldata/v1/value.py index 1d65cfd3..d6d3878c 100644 --- a/src/erc7730/model/calldata/v1/value.py +++ b/src/erc7730/model/calldata/v1/value.py @@ -6,9 +6,9 @@ """ from enum import IntEnum -from typing import Annotated, Literal +from typing import Annotated, Literal, Self -from pydantic import Discriminator, Field +from pydantic import Discriminator, Field, model_validator from erc7730.common.pydantic import pydantic_enum_by_name from erc7730.model.base import Model @@ -18,6 +18,9 @@ from erc7730.model.resolved.path import ResolvedPath from erc7730.model.types import HexStr, ScalarType +# maximum number of elements of an EIP712_PATH (doc/eip712.md#implementation-limits in app-ethereum-dev) +MAX_EIP712_PATH_ELEMENTS = 17 + @pydantic_enum_by_name class CalldataDescriptorPathElementType(IntEnum): @@ -267,8 +270,41 @@ class CalldataDescriptorEIP712PathElementArraySliceV1(Model): ) +class CalldataDescriptorEIP712PathElementLeafSliceV1(Model): + """ + Descriptor for the EIP712_LEAF_SLICE path element (keep some bytes of the leaf). + + Only valid as last element, on a bytesN, bytes or string leaf. A negative bound counts back from the end of the + leaf. + """ + + type: Literal["leaf_slice"] = Field( + default="leaf_slice", + title="Element type", + description="Type of the EIP-712 path element", + ) + + start: int | None = Field( + default=None, + title="Start", + description="First byte kept (inclusive). If not provided, the slice starts at the first byte of the leaf.", + ge=-32768, + le=32767, + ) + + end: int | None = Field( + default=None, + title="End", + description="End of the bytes kept (exclusive). If not provided, the slice ends at the end of the leaf.", + ge=-32768, + le=32767, + ) + + CalldataDescriptorEIP712PathElementV1 = Annotated[ - CalldataDescriptorEIP712PathElementStructFieldV1 | CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementStructFieldV1 + | CalldataDescriptorEIP712PathElementArraySliceV1 + | CalldataDescriptorEIP712PathElementLeafSliceV1, Field( title="EIP-712 path element", description="Path element to reach the target value in the EIP-712 value tree", @@ -300,11 +336,20 @@ class CalldataDescriptorEIP712PathV1(CalldataDescriptorStructV1): elements: list[CalldataDescriptorEIP712PathElementV1] = Field( title="Elements", - description="Interleaved struct field / array slice elements to reach the target value in the value tree", + description="Interleaved struct field / array slice elements to reach the target value in the value tree, " + "optionally followed by a leaf slice", min_length=1, - max_length=256, + max_length=MAX_EIP712_PATH_ELEMENTS, ) + @model_validator(mode="after") + def _validate_elements(self) -> Self: + if not isinstance(self.elements[0], CalldataDescriptorEIP712PathElementStructFieldV1): + raise ValueError("An EIP-712 path must begin with a struct field.") + if any(isinstance(e, CalldataDescriptorEIP712PathElementLeafSliceV1) for e in self.elements[:-1]): + raise ValueError("A leaf slice can only be the last element of an EIP-712 path.") + return self + CalldataDescriptorPathV1 = Annotated[ CalldataDescriptorContainerPathV1 | CalldataDescriptorDataPathV1 | CalldataDescriptorEIP712PathV1, diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 3bb719f2..56b7d8fd 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -6,11 +6,12 @@ from erc7730.convert.calldata.convert_erc7730_v2_input_to_calldata import ( erc7730_v2_descriptor_to_calldata_descriptors, ) -from erc7730.convert.calldata.v1.tlv import tlv_eip712_field, tlv_eip712_path_element +from erc7730.convert.calldata.v1.tlv import tlv_eip712_field, tlv_eip712_message_info, tlv_eip712_path_element from erc7730.model.calldata.v1.descriptor import CalldataDescriptorEIP712V1 from erc7730.model.calldata.v1.eip712 import CalldataDescriptorEIP712FieldV1, CalldataDescriptorEIP712SolType from erc7730.model.calldata.v1.value import ( CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementLeafSliceV1, CalldataDescriptorEIP712PathElementStructFieldV1, CalldataDescriptorEIP712PathV1, CalldataDescriptorValuePathV1, @@ -36,6 +37,7 @@ def _convert( *, domain: dict[str, Any] | None = None, chain_id: int = DEFAULT_CHAIN_ID, + address: str = DEFAULT_ADDRESS, ) -> CalldataDescriptorEIP712V1: """Build a minimal EIP-712 v2 descriptor and return the single converted calldata descriptor.""" descriptor = InputERC7730Descriptor.model_validate_json( @@ -45,7 +47,7 @@ def _convert( "context": { "$id": "test", "eip712": { - "deployments": [{"chainId": chain_id, "address": DEFAULT_ADDRESS}], + "deployments": [{"chainId": chain_id, "address": address}], "domain": domain if domain is not None else {"name": "Test", "version": "1"}, }, }, @@ -200,3 +202,41 @@ def test_eip712_path_element_tlv_encoding() -> None: # wildcard slice (no START/END) is an empty payload assert tlv_eip712_path_element(CalldataDescriptorEIP712PathElementArraySliceV1()).hex() == "0200" + + +def test_eip712_leaf_slice_tlv_encoding() -> None: + # EIP712_LEAF_SLICE: tag 0x03 wrapping START (0x01) / END (0x02) + assert ( + tlv_eip712_path_element(CalldataDescriptorEIP712PathElementLeafSliceV1(start=0, end=4)).hex() + == "03080102000002020004" + ) + + +def _tags(tlv: bytes) -> list[int]: + """List the tags of a flat TLV (single byte tag, single byte length).""" + tags = [] + i = 0 + while i < len(tlv): + tags.append(tlv[i]) + i += 2 + tlv[i + 1] + return tags + + +def test_eip712_message_info_is_bound_by_domain_separator_and_primary_type_hash() -> None: + descriptor = _convert(PERMIT_TYPE, [{"path": "value", "label": "Value", "format": "amount"}]) + tags = _tags(tlv_eip712_message_info(descriptor.message_info)) + + assert 0x0B in tags # DOMAIN_SEPARATOR + assert 0x0C in tags # PRIMARY_TYPE_HASH + assert descriptor.domain_separator == descriptor.message_info.domain_separator + + +def test_eip712_domain_separator_matches_eip712_reference_vector() -> None: + # EIP-712 reference example (Ether Mail) + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + domain={"name": "Ether Mail", "version": "1"}, + address="0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", + ) + assert descriptor.domain_separator == "0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f" diff --git a/tests/v2/convert/calldata/test_convert_maps.py b/tests/v2/convert/calldata/test_convert_maps.py index 2cc13322..cd5628d6 100644 --- a/tests/v2/convert/calldata/test_convert_maps.py +++ b/tests/v2/convert/calldata/test_convert_maps.py @@ -67,7 +67,7 @@ def convert( } ) ) - return erc7730_v2_descriptor_to_calldata_descriptors(descriptor) + return [d for d in erc7730_v2_descriptor_to_calldata_descriptors(descriptor) if isinstance(d, CalldataDescriptorV1)] def convert_one(signature: str, fields: list[dict[str, Any]], maps: dict[str, dict[str, Any]]) -> CalldataDescriptorV1: From 201e313d79b834085cfcab9ac5ef72880d4f4cd3 Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 12 Nov 2026 13:35:42 +0100 Subject: [PATCH 05/13] feat(BACK-12243): support EIP-712 descriptors without deployment An EIP-712 descriptor is addressed by its domain separator and primary type hash: the verifying contract is optional. - chain id, address and network are optional for EIP-712 descriptors, message info, enums and map entries - emit a descriptor when no deployment is declared, taking the chain and contract from the domain if it has them - compute the domain separator from the domain fields only, and check the separator given by the descriptor - add domain separator tests (salt, no verifying contract) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../convert_erc7730_v2_input_to_calldata.py | 59 +++++++++--- .../convert/calldata/v1/eip712_schema.py | 29 ++++-- src/erc7730/convert/calldata/v1/enum.py | 6 +- src/erc7730/convert/calldata/v1/map.py | 6 +- src/erc7730/convert/calldata/v1/tlv.py | 2 + src/erc7730/model/calldata/__init__.py | 20 +--- src/erc7730/model/calldata/v1/descriptor.py | 38 +++++++- src/erc7730/model/calldata/v1/instruction.py | 71 +++++++++----- .../convert/calldata/test_convert_eip712.py | 95 ++++++++++++++++++- 9 files changed, 255 insertions(+), 71 deletions(-) diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index c09746d8..ace976ba 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -794,6 +794,11 @@ def _convert_v2_param( return None def _deployment_map_key(value_map: ResolvedValueMap) -> str | None: + if maps.deployment is None: + return out.error( + title="Missing deployment", + message=f"Map {value_map.map} is keyed by the deployment, which the descriptor does not declare.", + ) return deployment_map_key(value_map.keyPath, maps.deployment.chainId, maps.deployment.address) def _lookup_deployment_value(value_map: ResolvedValueMap, key: str) -> ResolvedValueConstant | None: @@ -823,7 +828,9 @@ def _check_token_chain(params: object) -> bool: other_chain_path = chain_id_path is not None and not ( isinstance(chain_id_path, ContainerPath) and chain_id_path.field == ContainerField.CHAIN_ID ) - if (chain_id is not None and chain_id != maps.deployment.chainId) or other_chain_path: + if ( + chain_id is not None and (maps.deployment is None or chain_id != maps.deployment.chainId) + ) or other_chain_path: out.error( title="Unsupported token chain", message=f"""Token "{field.label}" may be on another chain than the transaction, which cannot be """ @@ -1104,7 +1111,7 @@ def _convert_eip712_descriptors( if not isinstance(context, InputEIP712Context): return [] - if chain_id is not None: + if chain_id is not None and context.eip712.deployments: deployment_chain_ids = {d.chainId for d in context.eip712.deployments} if chain_id not in deployment_chain_ids: return [] @@ -1118,12 +1125,17 @@ def _convert_eip712_descriptors( output_descriptors: list[CalldataDescriptor] = [] - for deployment in resolved_context.eip712.deployments: - if chain_id is not None and chain_id != deployment.chainId: + # a descriptor without deployment is addressed by its domain separator only: its domain is the one of the descriptor + deployments: list[ResolvedDeployment | None] = [*resolved_context.eip712.deployments] or [None] + + for deployment in deployments: + deployment_chain_id = deployment.chainId if deployment else (domain.chainId if domain else None) + + if chain_id is not None and deployment_chain_id is not None and chain_id != deployment_chain_id: continue - if ledger_network_id(deployment.chainId) is None: - out.warning(f"Chain id {deployment.chainId} is not known, skipping it") + if deployment_chain_id is not None and ledger_network_id(deployment_chain_id) is None: + out.warning(f"Chain id {deployment_chain_id} is not known, skipping it") continue for encode_type_key, format in resolved_descriptor.display.formats.items(): @@ -1150,7 +1162,7 @@ def _convert_eip712_descriptors( def _convert_eip712_message( descriptor: ResolvedERC7730Descriptor, - deployment: ResolvedDeployment, + deployment: ResolvedDeployment | None, domain: ResolvedDomain | None, domain_separator: str | None, schema: ReconstructedSchema, @@ -1162,7 +1174,7 @@ def _convert_eip712_message( Generate a calldata descriptor for a single EIP-712 message primary type. :param descriptor: resolved v2 source ERC-7730 descriptor - :param deployment: chain id / verifying contract address for which the descriptor is generated + :param deployment: chain id / verifying contract address for which the descriptor is generated, if any :param domain: EIP-712 domain of the messages :param domain_separator: domain separator given by the descriptor, computed from the domain when not set :param schema: reconstructed EIP-712 schema (structs + primary type hash) @@ -1187,6 +1199,15 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal else None ) + # without deployment, the chain id and verifying contract can only come from the domain + chain_id = deployment.chainId if deployment else (domain.chainId if domain else None) + address = deployment.address if deployment else (domain.verifyingContract if domain else None) + if deployment is None and chain_id is not None and address is not None: + deployment = ResolvedDeployment(chainId=chain_id, address=address) + + has_domain_fields = bool(schema.types["EIP712Domain"]) + computed = compute_domain_separator(schema, domain, chain_id, address, out) if has_domain_fields else None + if domain_separator: try: separator_bytes = from_hex(domain_separator) @@ -1199,7 +1220,17 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal "string.", ) domain_separator_hex = HexStr("0x" + separator_bytes.hex()) - elif (computed := compute_domain_separator(schema, domain, deployment, out)) is None: + if computed is not None and computed != domain_separator_hex: + out.warning( + f"Domain separator {domain_separator_hex} does not match the one computed from the domain " + f"({computed}), the device will not match the messages of this descriptor." + ) + elif computed is None: + if not has_domain_fields: + return out.error( + title="Missing domain", + message="The domain separator cannot be computed: set the domain or the domain separator.", + ) return None else: domain_separator_hex = computed @@ -1238,8 +1269,8 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal schema_info = CalldataDescriptorInstructionEIP712SchemaV1(structs=schema.structs) message_info = CalldataDescriptorInstructionEIP712MessageInfoV1( - chain_id=deployment.chainId, - address=deployment.address, + chain_id=chain_id, + address=address, domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash, hash=hash.digest().hex(), @@ -1253,9 +1284,9 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal return CalldataDescriptorEIP712V1( source=source, - network=cast(str, ledger_network_id(deployment.chainId)), - chain_id=deployment.chainId, - address=deployment.address, + network=ledger_network_id(chain_id) if chain_id is not None else None, + chain_id=chain_id, + address=address, domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash, schema_info=schema_info, diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py index bc8ed8b3..59b57682 100644 --- a/src/erc7730/convert/calldata/v1/eip712_schema.py +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -21,7 +21,7 @@ CalldataDescriptorEIP712SolType, CalldataDescriptorEIP712StructV1, ) -from erc7730.model.resolved.v2.context import ResolvedDeployment, ResolvedDomain +from erc7730.model.resolved.v2.context import ResolvedDomain from erc7730.model.types import HexStr @@ -192,18 +192,20 @@ def reconstruct_schema( def compute_domain_separator( schema: ReconstructedSchema, domain: ResolvedDomain | None, - deployment: ResolvedDeployment, + chain_id: int | None, + address: str | None, out: OutputAdder, ) -> HexStr | None: """ Compute the domain separator, ``hashStruct(domain)``, of the messages of one deployment. - The domain is made of the values of the descriptor domain, with the chain id and contract address of the - deployment. + The fields of the domain are the ones of its reconstructed type (see ``reconstruct_schema``): their values are the + ones of the descriptor domain, with the chain id and contract address of the deployment. :param schema: reconstructed schema, which holds the type of the domain :param domain: the resolved EIP-712 domain - :param deployment: deployment providing the chain id and verifying contract of the domain + :param chain_id: chain id of the domain + :param address: verifying contract of the domain :param out: error handler :return: the domain separator, or None on error """ @@ -217,9 +219,15 @@ def compute_domain_separator( value = getattr(domain, name) encoded += keccak(text=value) case "chainId": - encoded += deployment.chainId.to_bytes(32) + if chain_id is None: + _missing_domain_value(name, out) + return None + encoded += chain_id.to_bytes(32) case "verifyingContract": - encoded += from_hex(deployment.address).rjust(32, b"\x00") + if address is None: + _missing_domain_value(name, out) + return None + encoded += from_hex(address).rjust(32, b"\x00") case "salt": salt_hex = domain.salt if domain is not None else None try: @@ -236,3 +244,10 @@ def compute_domain_separator( raise ValueError(f"Unexpected domain field {name}") return HexStr("0x" + keccak(bytes(encoded)).hex()) + + +def _missing_domain_value(name: str, out: OutputAdder) -> None: + out.error( + title="Missing domain value", + message=f"Domain field {name} has no value: declare a deployment, or set it in the domain.", + ) diff --git a/src/erc7730/convert/calldata/v1/enum.py b/src/erc7730/convert/calldata/v1/enum.py index 2557ccc2..f927c9ba 100644 --- a/src/erc7730/convert/calldata/v1/enum.py +++ b/src/erc7730/convert/calldata/v1/enum.py @@ -31,7 +31,7 @@ def enum_ordinal(ordinal: str) -> int: def convert_enums( - deployment: ResolvedDeployment, + deployment: ResolvedDeployment | None, enums: dict[Id, EnumDefinition] | None, selector: Selector | None = None, domain_separator: HexStr | None = None, @@ -52,8 +52,8 @@ def convert_enums( return [ CalldataDescriptorInstructionEnumValueV1( - chain_id=deployment.chainId, - address=deployment.address, + chain_id=deployment.chainId if deployment else None, + address=deployment.address if deployment else None, selector=selector, domain_separator=domain_separator, primary_type_hash=primary_type_hash, diff --git a/src/erc7730/convert/calldata/v1/map.py b/src/erc7730/convert/calldata/v1/map.py index 16d910aa..7be4ee6b 100644 --- a/src/erc7730/convert/calldata/v1/map.py +++ b/src/erc7730/convert/calldata/v1/map.py @@ -75,7 +75,7 @@ class MapEntries: def __init__( self, - deployment: ResolvedDeployment, + deployment: ResolvedDeployment | None, selector: Selector | None = None, domain_separator: HexStr | None = None, primary_type_hash: HexStr | None = None, @@ -132,8 +132,8 @@ def map_ref( for key_source, key_bytes, value_bytes in encoded: self.entries.append( CalldataDescriptorInstructionMapEntryV1( - chain_id=self.deployment.chainId, - address=Address(self.deployment.address), + chain_id=self.deployment.chainId if self.deployment else None, + address=Address(self.deployment.address) if self.deployment else None, selector=self.selector, domain_separator=self.domain_separator, primary_type_hash=self.primary_type_hash, diff --git a/src/erc7730/convert/calldata/v1/tlv.py b/src/erc7730/convert/calldata/v1/tlv.py index ac0abce4..b416bf49 100644 --- a/src/erc7730/convert/calldata/v1/tlv.py +++ b/src/erc7730/convert/calldata/v1/tlv.py @@ -429,6 +429,8 @@ def _tlv_operation_context( """ out = bytearray() if obj.selector is not None: + if obj.chain_id is None or obj.address is None: + raise ValueError("A chain id and a contract address are required with a selector.") out += tlv(tags["CHAIN_ID"], obj.chain_id.to_bytes(8)) out += tlv(tags["CONTRACT_ADDR"], from_hex(obj.address)) out += tlv(tags["SELECTOR"], from_hex(obj.selector)) diff --git a/src/erc7730/model/calldata/__init__.py b/src/erc7730/model/calldata/__init__.py index 28f260ab..b4e3ef65 100644 --- a/src/erc7730/model/calldata/__init__.py +++ b/src/erc7730/model/calldata/__init__.py @@ -14,7 +14,6 @@ from pydantic_string_url import HttpUrl from erc7730.model.base import Model -from erc7730.model.types import Address, Id class CalldataDescriptorVersion(StrEnum): @@ -27,8 +26,7 @@ class CalldataDescriptorBase(Model, ABC): """ A clear signing descriptor for a smart contract function calldata or an EIP-712 message. - Note a calldata descriptor is bound to a single deployment (single chain id/contract address) and a single function - (contract calldata) or message primary type (EIP-712). + Note a calldata descriptor is bound to a single function (contract calldata) or message primary type (EIP-712). Also referred to as a "generic parser descriptor". """ @@ -38,19 +36,3 @@ class CalldataDescriptorBase(Model, ABC): title="Descriptor source URL", description="The URL of the source of the descriptor (typically in clear-signing-erc7730-registry).", ) - - network: Id = Field( - title="Ledger Network identifier", - description="The Ledger network this descriptor applies to.", - ) - - chain_id: int = Field( - title="Chain ID", - description="The contract deployment EIP-155 chain id.", - ge=1, - ) - - address: Address = Field( - title="Contract address", - description="The contract deployment address.", - ) diff --git a/src/erc7730/model/calldata/v1/descriptor.py b/src/erc7730/model/calldata/v1/descriptor.py index b1977bfc..8e7a0397 100644 --- a/src/erc7730/model/calldata/v1/descriptor.py +++ b/src/erc7730/model/calldata/v1/descriptor.py @@ -17,7 +17,7 @@ CalldataDescriptorInstructionMapEntryV1, CalldataDescriptorInstructionTransactionInfoV1, ) -from erc7730.model.types import HexStr, Selector +from erc7730.model.types import Address, HexStr, Id, Selector class CalldataDescriptorV1(CalldataDescriptorBase): @@ -33,6 +33,22 @@ class CalldataDescriptorV1(CalldataDescriptorBase): description="Type of the descriptor (contract calldata).", ) + network: Id = Field( + title="Ledger Network identifier", + description="The Ledger network this descriptor applies to.", + ) + + chain_id: int = Field( + title="Chain ID", + description="The contract deployment EIP-155 chain id.", + ge=1, + ) + + address: Address = Field( + title="Contract address", + description="The contract deployment address.", + ) + selector: Selector = Field( title="Function selector", description="The 4-bytes function selector this descriptor applies to.", @@ -90,6 +106,26 @@ class CalldataDescriptorEIP712V1(CalldataDescriptorBase): "descriptor specification)", ) + network: Id | None = Field( + default=None, + title="Ledger Network identifier", + description="The Ledger network this descriptor applies to, if the descriptor is bound to a chain.", + ) + + chain_id: int | None = Field( + default=None, + title="Chain ID", + description="The EIP-155 chain id of the deployment, if the descriptor is bound to a chain.", + ge=1, + ) + + address: Address | None = Field( + default=None, + title="Contract address", + description="The verifying contract address, if the domain has one. The descriptor is addressed by its domain " + "separator and primary type hash, the contract is only a way to look it up.", + ) + domain_separator: HexStr = Field( title="Domain separator", description="hashStruct(domain) of the EIP-712 message domain.", diff --git a/src/erc7730/model/calldata/v1/instruction.py b/src/erc7730/model/calldata/v1/instruction.py index b2e78ad5..ea4546a5 100644 --- a/src/erc7730/model/calldata/v1/instruction.py +++ b/src/erc7730/model/calldata/v1/instruction.py @@ -65,13 +65,19 @@ class CalldataDescriptorFieldVisibilityV1(IntEnum): def _validate_operation_context( - selector: str | None, domain_separator: str | None, primary_type_hash: str | None + selector: str | None, + chain_id: int | None, + address: str | None, + domain_separator: str | None, + primary_type_hash: str | None, ) -> None: """ Check an ENUM_VALUE / MAP_ENTRY is bound to exactly one kind of operation: a transaction (selector), or an EIP-712 message (domain separator and primary type hash). The device refuses a struct with tags of both, or of none. """ if selector is not None: + if chain_id is None or address is None: + raise ValueError("A chain id and a contract address are required with a selector.") if domain_separator is not None or primary_type_hash is not None: raise ValueError("A selector cannot be combined with a domain separator or a primary type hash.") elif domain_separator is None or primary_type_hash is None: @@ -98,17 +104,6 @@ class CalldataDescriptorInstructionTransactionInfoBaseV1(CalldataDescriptorInstr description="Version of the struct", ) - chain_id: int = Field( - title="Chain ID", - description="The contract deployment EIP-155 chain id.", - ge=1, - ) - - address: Address = Field( - title="Contract address", - description="The contract deployment address.", - ) - hash: str = Field( title="Structs hash", description="Hash of all the FIELD structs", @@ -166,6 +161,17 @@ class CalldataDescriptorInstructionTransactionInfoBaseV1(CalldataDescriptorInstr class CalldataDescriptorInstructionTransactionInfoV1(CalldataDescriptorInstructionTransactionInfoBaseV1): """Instruction descriptor for the TRANSACTION_INFO struct.""" + chain_id: int = Field( + title="Chain ID", + description="The contract deployment EIP-155 chain id.", + ge=1, + ) + + address: Address = Field( + title="Contract address", + description="The contract deployment address.", + ) + selector: Selector = Field( title="Function selector", description="The 4-bytes function selector this descriptor applies to.", @@ -191,6 +197,19 @@ class CalldataDescriptorInstructionEIP712MessageInfoV1(CalldataDescriptorInstruc the Ethereum app specifications. """ + chain_id: int | None = Field( + default=None, + title="Chain ID", + description="The contract deployment EIP-155 chain id (metadata only, not part of the struct).", + ge=1, + ) + + address: Address | None = Field( + default=None, + title="Contract address", + description="The verifying contract address (metadata only, not part of the struct).", + ) + domain_separator: HexStr = Field( title="Domain separator", description="hashStruct(domain) of the EIP-712 message domain.", @@ -224,15 +243,17 @@ class CalldataDescriptorInstructionEnumValueV1(CalldataDescriptorInstructionBase description="Version of the ENUM struct", ) - chain_id: int = Field( + chain_id: int | None = Field( + default=None, title="Chain ID", - description="The contract deployment EIP-155 chain id.", + description="The contract deployment EIP-155 chain id (required for transactions).", ge=1, ) - address: Address = Field( + address: Address | None = Field( + default=None, title="Contract address", - description="The contract deployment address.", + description="The contract deployment address (required for transactions).", ) selector: Selector | None = Field( @@ -260,7 +281,9 @@ class CalldataDescriptorInstructionEnumValueV1(CalldataDescriptorInstructionBase @model_validator(mode="after") def _validate_context(self) -> Self: - _validate_operation_context(self.selector, self.domain_separator, self.primary_type_hash) + _validate_operation_context( + self.selector, self.chain_id, self.address, self.domain_separator, self.primary_type_hash + ) return self enum_id: str = Field( @@ -311,15 +334,17 @@ class CalldataDescriptorInstructionMapEntryV1(CalldataDescriptorInstructionBaseV description="Version of the MAP_ENTRY struct", ) - chain_id: int = Field( + chain_id: int | None = Field( + default=None, title="Chain ID", - description="The contract deployment EIP-155 chain id.", + description="The contract deployment EIP-155 chain id (required for transactions).", ge=1, ) - address: Address = Field( + address: Address | None = Field( + default=None, title="Contract address", - description="The contract deployment address.", + description="The contract deployment address (required for transactions).", ) selector: Selector | None = Field( @@ -347,7 +372,9 @@ class CalldataDescriptorInstructionMapEntryV1(CalldataDescriptorInstructionBaseV @model_validator(mode="after") def _validate_context(self) -> Self: - _validate_operation_context(self.selector, self.domain_separator, self.primary_type_hash) + _validate_operation_context( + self.selector, self.chain_id, self.address, self.domain_separator, self.primary_type_hash + ) return self map: str = Field( diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 56b7d8fd..ce325268 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -3,6 +3,7 @@ from eth_utils import keccak +from erc7730.common.output import ListOutputAdder, OutputAdder from erc7730.convert.calldata.convert_erc7730_v2_input_to_calldata import ( erc7730_v2_descriptor_to_calldata_descriptors, ) @@ -38,6 +39,9 @@ def _convert( domain: dict[str, Any] | None = None, chain_id: int = DEFAULT_CHAIN_ID, address: str = DEFAULT_ADDRESS, + deployments: list[dict[str, Any]] | None = None, + domain_separator: str | None = None, + out: OutputAdder | None = None, ) -> CalldataDescriptorEIP712V1: """Build a minimal EIP-712 v2 descriptor and return the single converted calldata descriptor.""" descriptor = InputERC7730Descriptor.model_validate_json( @@ -47,8 +51,11 @@ def _convert( "context": { "$id": "test", "eip712": { - "deployments": [{"chainId": chain_id, "address": address}], + "deployments": [{"chainId": chain_id, "address": address}] + if deployments is None + else deployments, "domain": domain if domain is not None else {"name": "Test", "version": "1"}, + **({"domainSeparator": domain_separator} if domain_separator else {}), }, }, "metadata": {"owner": "Test Owner"}, @@ -57,7 +64,7 @@ def _convert( ) ) - descriptors = erc7730_v2_descriptor_to_calldata_descriptors(descriptor, chain_id=chain_id) + descriptors = erc7730_v2_descriptor_to_calldata_descriptors(descriptor, chain_id=chain_id, out=out) assert len(descriptors) == 1 descriptor_out = descriptors[0] assert isinstance(descriptor_out, CalldataDescriptorEIP712V1) @@ -240,3 +247,87 @@ def test_eip712_domain_separator_matches_eip712_reference_vector() -> None: address="0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ) assert descriptor.domain_separator == "0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f" + + +def _domain_separator(fields: list[tuple[str, str, bytes]]) -> str: + """Reference hashStruct(EIP712Domain), encoded by hand: (type, name, 32 bytes encoded value) per field.""" + domain_type = "EIP712Domain(" + ",".join(f"{t} {n}" for t, n, _ in fields) + ")" + return "0x" + keccak(keccak(text=domain_type) + b"".join(v for _, _, v in fields)).hex() + + +def test_eip712_domain_separator_with_salt_and_without_contract() -> None: + salt = "0x" + "11" * 32 + expected = _domain_separator( + [("string", "name", keccak(text="Test")), ("bytes32", "salt", bytes.fromhex("11" * 32))] + ) + out = ListOutputAdder() + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + domain={"name": "Test", "salt": salt}, + deployments=[], + domain_separator=expected, + out=out, + ) + + assert not out.has_warnings + assert descriptor.domain_separator == expected + assert [f.name for f in descriptor.schema_info.structs[0].fields] == ["name", "salt"] + + +def test_eip712_descriptor_without_deployment_is_not_bound_to_a_chain() -> None: + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + deployments=[], + domain_separator="0x" + "ab" * 32, + chain_id=137, + ) + + assert descriptor.chain_id is None + assert descriptor.address is None + assert descriptor.network is None + assert descriptor.message_info.chain_id is None + assert descriptor.message_info.address is None + assert descriptor.message_info.descriptor + assert descriptor.model_dump_json() + + +def test_eip712_descriptor_without_deployment_takes_chain_and_contract_from_the_domain() -> None: + expected = _domain_separator( + [ + ("string", "name", keccak(text="Test")), + ("uint256", "chainId", (1).to_bytes(32)), + ("address", "verifyingContract", bytes.fromhex(DEFAULT_ADDRESS[2:]).rjust(32, b"\x00")), + ] + ) + out = ListOutputAdder() + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + domain={"name": "Test", "chainId": 1, "verifyingContract": DEFAULT_ADDRESS}, + deployments=[], + domain_separator=expected, + out=out, + ) + + assert not out.has_warnings + assert descriptor.chain_id == 1 + assert descriptor.address == DEFAULT_ADDRESS.lower() + assert descriptor.network is not None + assert descriptor.domain_separator == expected + + +def test_eip712_domain_separator_given_by_the_descriptor_is_checked() -> None: + out = ListOutputAdder() + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + deployments=[], + domain_separator="0x" + "ab" * 32, + out=out, + ) + + assert descriptor.domain_separator == "0x" + "ab" * 32 + assert out.has_warnings + assert any("does not match" in o.message for o in out.outputs) From 7a539be1c50ef01af42ec118ac37e3f6ee8ee879 Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 12 Nov 2026 13:55:42 +0100 Subject: [PATCH 06/13] feat(BACK-12243): lint the EIP-712 domain separator against the domain The converter uses a domainSeparator given by the descriptor as is, as the declared domain may be partial. A new linter recomputes the separator from the domain and deployments, and warns when none matches. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../convert_erc7730_v2_input_to_calldata.py | 22 ++-- src/erc7730/lint/v2/lint.py | 2 + .../lint_validate_eip712_domain_separator.py | 87 +++++++++++++ .../convert/calldata/test_convert_eip712.py | 5 +- ...t_lint_validate_eip712_domain_separator.py | 116 ++++++++++++++++++ 5 files changed, 215 insertions(+), 17 deletions(-) create mode 100644 src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py create mode 100644 tests/v2/lint/test_lint_validate_eip712_domain_separator.py diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index ace976ba..a3574072 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -1205,9 +1205,8 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal if deployment is None and chain_id is not None and address is not None: deployment = ResolvedDeployment(chainId=chain_id, address=address) - has_domain_fields = bool(schema.types["EIP712Domain"]) - computed = compute_domain_separator(schema, domain, chain_id, address, out) if has_domain_fields else None - + # a separator given by the descriptor is used as is (the domain of the descriptor may be only partial, it is up to + # the linter to check it against the domain) if domain_separator: try: separator_bytes = from_hex(domain_separator) @@ -1220,17 +1219,12 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal "string.", ) domain_separator_hex = HexStr("0x" + separator_bytes.hex()) - if computed is not None and computed != domain_separator_hex: - out.warning( - f"Domain separator {domain_separator_hex} does not match the one computed from the domain " - f"({computed}), the device will not match the messages of this descriptor." - ) - elif computed is None: - if not has_domain_fields: - return out.error( - title="Missing domain", - message="The domain separator cannot be computed: set the domain or the domain separator.", - ) + elif not schema.types["EIP712Domain"]: + return out.error( + title="Missing domain", + message="The domain separator cannot be computed: set the domain or the domain separator.", + ) + elif (computed := compute_domain_separator(schema, domain, chain_id, address, out)) is None: return None else: domain_separator_hex = computed diff --git a/src/erc7730/lint/v2/lint.py b/src/erc7730/lint/v2/lint.py index c1f82259..828939c2 100644 --- a/src/erc7730/lint/v2/lint.py +++ b/src/erc7730/lint/v2/lint.py @@ -17,6 +17,7 @@ from erc7730.lint.v2 import ERC7730Linter, MultiLinter from erc7730.lint.v2.lint_transaction_type_classifier import ClassifyTransactionTypeLinter from erc7730.lint.v2.lint_validate_display_fields import ValidateDisplayFieldsLinter +from erc7730.lint.v2.lint_validate_eip712_domain_separator import ValidateEIP712DomainSeparatorLinter from erc7730.lint.v2.lint_validate_eip712_keys import ValidateEIP712KeysLinter from erc7730.lint.v2.lint_validate_map_keys import ValidateMapKeysLinter from erc7730.lint.v2.lint_validate_max_length import ValidateMaxLengthLinter @@ -56,6 +57,7 @@ def lint_all(paths: list[Path], out: OutputAdder) -> int: [ ValidateDisplayFieldsLinter(), ValidateEIP712KeysLinter(), + ValidateEIP712DomainSeparatorLinter(), ValidateMapKeysLinter(), ClassifyTransactionTypeLinter(), ValidateMaxLengthLinter(), diff --git a/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py b/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py new file mode 100644 index 00000000..5be3f07a --- /dev/null +++ b/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py @@ -0,0 +1,87 @@ +""" +V2 linter that validates the ``domainSeparator`` of an EIP-712 context against the domain of the descriptor. + +The converter uses a ``domainSeparator`` given by the descriptor as is, as the ``domain`` constraint of a descriptor may +be only partial (the signed domain can have more members than the ones listed). This linter recomputes the separator +from the declared domain and deployments, and reports when none of them gives the declared value: the device would +never match the messages with it. +""" + +from typing import final, override + +from erc7730.common.binary import from_hex +from erc7730.common.output import ListOutputAdder, OutputAdder +from erc7730.convert.calldata.v1.eip712_schema import compute_domain_separator, reconstruct_schema +from erc7730.lint.v2 import ERC7730Linter +from erc7730.model.input.v2.descriptor import InputERC7730Descriptor +from erc7730.model.resolved.v2.context import ResolvedEIP712Context +from erc7730.model.resolved.v2.descriptor import ResolvedERC7730Descriptor + + +@final +class ValidateEIP712DomainSeparatorLinter(ERC7730Linter): + """ + Validates that the ``domainSeparator`` of an EIP-712 context matches the separator computed from the domain. + + Nothing is reported when the separator cannot be computed (no domain member, or a missing chain id / verifying + contract), as there is nothing to compare it to. + """ + + @override + def lint( + self, input_descriptor: InputERC7730Descriptor, descriptor: ResolvedERC7730Descriptor, out: OutputAdder + ) -> None: + if not isinstance(descriptor.context, ResolvedEIP712Context): + return + + eip712 = descriptor.context.eip712 + if not (declared := eip712.domainSeparator): + return + + try: + declared_bytes = from_hex(declared) + except ValueError: + declared_bytes = b"" + if len(declared_bytes) != 32: + out.error( + title="Invalid domain separator", + message=f"Domain separator {declared} must be a 32 bytes hexadecimal string.", + ) + return + + # the type of the domain does not depend on the format key: any valid one gives it + schema = None + for key in descriptor.display.formats: + if schema := reconstruct_schema(str(key), eip712.domain, bool(eip712.deployments), ListOutputAdder()): + break + if schema is None or not schema.types["EIP712Domain"]: + return + + # without deployment the chain id and verifying contract can only come from the domain + bindings: list[tuple[int | None, str | None]] = [(d.chainId, d.address) for d in eip712.deployments] + if not bindings: + domain = eip712.domain + bindings = [(domain.chainId, domain.verifyingContract) if domain else (None, None)] + + computed = [ + compute_domain_separator(schema, eip712.domain, chain_id, address, ListOutputAdder()) + for chain_id, address in bindings + ] + known = [separator for separator in computed if separator is not None] + if not known: + return + + expected = {bytes.fromhex(separator[2:]) for separator in known} + if declared_bytes not in expected: + out.warning( + title="Domain separator mismatch", + message=f"Domain separator {declared} is not the one computed from the domain " + f"({', '.join(sorted(known))}). If the domain is partial this is expected, otherwise the device will " + "not match the messages of this descriptor.", + ) + elif len(known) > 1: + out.warning( + title="Domain separator shared by several deployments", + message=f"Domain separator {declared} matches only some of the {len(known)} deployments, as it " + "depends on the chain id and the verifying contract. Omit it to compute one per deployment.", + ) diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index ce325268..6fbe8ad3 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -318,7 +318,7 @@ def test_eip712_descriptor_without_deployment_takes_chain_and_contract_from_the_ assert descriptor.domain_separator == expected -def test_eip712_domain_separator_given_by_the_descriptor_is_checked() -> None: +def test_eip712_domain_separator_given_by_the_descriptor_is_used_as_is() -> None: out = ListOutputAdder() descriptor = _convert( PERMIT_TYPE, @@ -329,5 +329,4 @@ def test_eip712_domain_separator_given_by_the_descriptor_is_checked() -> None: ) assert descriptor.domain_separator == "0x" + "ab" * 32 - assert out.has_warnings - assert any("does not match" in o.message for o in out.outputs) + assert not out.outputs diff --git a/tests/v2/lint/test_lint_validate_eip712_domain_separator.py b/tests/v2/lint/test_lint_validate_eip712_domain_separator.py new file mode 100644 index 00000000..bd5784da --- /dev/null +++ b/tests/v2/lint/test_lint_validate_eip712_domain_separator.py @@ -0,0 +1,116 @@ +import json +from typing import Any + +from eth_utils import keccak + +from erc7730.common.output import ListOutputAdder +from erc7730.convert.resolved.v2.convert_erc7730_input_to_resolved import ERC7730InputToResolved +from erc7730.lint.v2.lint_validate_eip712_domain_separator import ValidateEIP712DomainSeparatorLinter +from erc7730.model.input.v2.descriptor import InputERC7730Descriptor + +PERMIT_TYPE = "Permit(address owner,uint256 value)" +CONTRACT = "0x000000000000000000000000000000000000dEaD" + + +def _separator(*members: tuple[str, str, bytes]) -> str: + domain_type = "EIP712Domain(" + ",".join(f"{t} {n}" for t, n, _ in members) + ")" + return "0x" + keccak(keccak(text=domain_type) + b"".join(v for _, _, v in members)).hex() + + +NAME = ("string", "name", keccak(text="Test")) +SALT = ("bytes32", "salt", bytes.fromhex("11" * 32)) +NAME_ONLY = _separator(NAME) + + +def lint(eip712: dict[str, Any]) -> list[tuple[str | None, str]]: + descriptor = InputERC7730Descriptor.model_validate_json( + json.dumps( + { + "$schema": "specs/erc7730-v2.schema.json", + "context": {"$id": "test", "eip712": eip712}, + "metadata": {"owner": "Test Owner"}, + "display": { + "formats": { + PERMIT_TYPE: {"intent": "Test", "fields": [{"path": "value", "label": "V", "format": "raw"}]} + } + }, + } + ) + ) + out = ListOutputAdder() + resolved = ERC7730InputToResolved().convert(descriptor, out) + assert resolved is not None, out.outputs + ValidateEIP712DomainSeparatorLinter().lint(descriptor, resolved, out) + return [(o.title, o.message) for o in out.outputs] + + +def test_no_domain_separator() -> None: + assert lint({"deployments": [{"chainId": 1, "address": CONTRACT}], "domain": {"name": "Test"}}) == [] + + +def test_matching_domain_separator_without_deployment() -> None: + assert lint({"domain": {"name": "Test"}, "domainSeparator": NAME_ONLY}) == [] + + +def test_matching_domain_separator_with_salt() -> None: + separator = _separator(NAME, SALT) + assert lint({"domain": {"name": "Test", "salt": "0x" + "11" * 32}, "domainSeparator": separator}) == [] + + +def test_matching_domain_separator_from_the_domain_chain_and_contract() -> None: + separator = _separator( + NAME, + ("uint256", "chainId", (1).to_bytes(32)), + ("address", "verifyingContract", bytes.fromhex(CONTRACT[2:]).rjust(32, b"\x00")), + ) + domain = {"name": "Test", "chainId": 1, "verifyingContract": CONTRACT} + assert lint({"domain": domain, "domainSeparator": separator}) == [] + + +def test_matching_domain_separator_of_a_deployment() -> None: + separator = _separator( + NAME, + ("uint256", "chainId", (1).to_bytes(32)), + ("address", "verifyingContract", bytes.fromhex(CONTRACT[2:]).rjust(32, b"\x00")), + ) + assert ( + lint( + { + "domain": {"name": "Test"}, + "deployments": [{"chainId": 1, "address": CONTRACT}], + "domainSeparator": separator, + } + ) + == [] + ) + + +def test_domain_separator_mismatch() -> None: + outputs = lint({"domain": {"name": "Test"}, "domainSeparator": "0x" + "ab" * 32}) + assert [title for title, _ in outputs] == ["Domain separator mismatch"] + assert NAME_ONLY in outputs[0][1] + + +def test_domain_separator_matching_only_some_deployments() -> None: + separator = _separator( + NAME, + ("uint256", "chainId", (1).to_bytes(32)), + ("address", "verifyingContract", bytes.fromhex(CONTRACT[2:]).rjust(32, b"\x00")), + ) + outputs = lint( + { + "domain": {"name": "Test"}, + "deployments": [{"chainId": 1, "address": CONTRACT}, {"chainId": 10, "address": CONTRACT}], + "domainSeparator": separator, + } + ) + assert [title for title, _ in outputs] == ["Domain separator shared by several deployments"] + + +def test_invalid_domain_separator_length() -> None: + outputs = lint({"domain": {"name": "Test"}, "domainSeparator": "0x1234"}) + assert [title for title, _ in outputs] == ["Invalid domain separator"] + + +def test_domain_separator_without_domain_is_not_compared() -> None: + assert lint({"domainSeparator": "0x" + "ab" * 32}) == [] From a782f0d238900e9406ee7ae138fd6ef9e364c628 Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 12 Nov 2026 15:49:47 +0100 Subject: [PATCH 07/13] test(BACK-12243): restrict calldata registry test to EIP-712 files Restore the resolution registry test and mark the EIP-712 files the converter does not support yet as expected failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../calldata/test_convert_registry_files.py | 14 ++++++------- .../resolved/test_convert_registry_files.py | 19 ++++++++++++++++++ tests/files.py | 20 ++++++++++++++----- 3 files changed, 41 insertions(+), 12 deletions(-) create mode 100644 tests/convert/resolved/test_convert_registry_files.py diff --git a/tests/convert/calldata/test_convert_registry_files.py b/tests/convert/calldata/test_convert_registry_files.py index 56c6fa35..d235b2d5 100644 --- a/tests/convert/calldata/test_convert_registry_files.py +++ b/tests/convert/calldata/test_convert_registry_files.py @@ -7,20 +7,20 @@ ) from erc7730.model.input.v2.descriptor import InputERC7730Descriptor from tests.cases import path_id -from tests.files import ERC7730_DESCRIPTORS, ERC7730_EXPECTED_EMPTY_CALLDATA +from tests.files import ERC7730_EIP712_DESCRIPTORS, ERC7730_EXPECTED_CALLDATA_FAILURES pytestmark = pytest.mark.integration -@pytest.mark.parametrize("input_file", ERC7730_DESCRIPTORS, ids=path_id) -def test_registry_files(input_file: Path) -> None: +@pytest.mark.parametrize("input_file", ERC7730_EIP712_DESCRIPTORS, ids=path_id) +def test_registry_files(request: pytest.FixtureRequest, input_file: Path) -> None: """ - Test generating calldata descriptors for ERC-7730 registry files (also exercises resolution). + Test generating calldata descriptors for ERC-7730 registry EIP-712 files (also exercises resolution). """ - descriptors = erc7730_v2_descriptor_to_calldata_descriptors(InputERC7730Descriptor.load(input_file)) + if path_id(input_file) in ERC7730_EXPECTED_CALLDATA_FAILURES: + request.applymarker(pytest.mark.xfail(strict=True, reason="unsupported by the calldata converter")) - if input_file.name in ERC7730_EXPECTED_EMPTY_CALLDATA: - return + descriptors = erc7730_v2_descriptor_to_calldata_descriptors(InputERC7730Descriptor.load(input_file)) assert descriptors # model_dump_json evaluates every computed TLV .descriptor field, exercising the full TLV encoding diff --git a/tests/convert/resolved/test_convert_registry_files.py b/tests/convert/resolved/test_convert_registry_files.py new file mode 100644 index 00000000..b79a4ebd --- /dev/null +++ b/tests/convert/resolved/test_convert_registry_files.py @@ -0,0 +1,19 @@ +from pathlib import Path + +import pytest + +from erc7730.convert.convert import convert_and_raise_errors +from erc7730.convert.resolved.v2.convert_erc7730_input_to_resolved import ERC7730InputToResolved +from erc7730.model.input.v2.descriptor import InputERC7730Descriptor +from tests.cases import path_id +from tests.files import ERC7730_DESCRIPTORS + +pytestmark = pytest.mark.integration + + +@pytest.mark.parametrize("input_file", ERC7730_DESCRIPTORS, ids=path_id) +def test_registry_files(input_file: Path) -> None: + """ + Test converting ERC-7730 registry files from input to resolved form. + """ + convert_and_raise_errors(InputERC7730Descriptor.load(input_file), ERC7730InputToResolved()) diff --git a/tests/files.py b/tests/files.py index e90a393e..6a4afba5 100644 --- a/tests/files.py +++ b/tests/files.py @@ -50,11 +50,21 @@ def _is_registry_descriptor(path: Path) -> bool: ) ERC7730_DESCRIPTORS = sorted(ERC7730_CALLDATA_DESCRIPTORS + ERC7730_EIP712_DESCRIPTORS) -# Registry descriptors that legitimately generate no calldata descriptor: conversion is still run on them (exercising -# resolution), but the non-empty calldata assertion is skipped. -ERC7730_EXPECTED_EMPTY_CALLDATA = { - "calldata-KasExitBridge.json", # only deployed on chain 38833 (Igra), which is not a Ledger-supported network - "calldata-PftNft.json", # enum keyed by "True"/"False" instead of integer field values (not encodable as uint8) +# Registry descriptors the calldata converter does not support yet (known gaps, reported as conversion errors). They are +# expected to fail: the test turns red once one is fixed, so it can be removed from this list. +ERC7730_EXPECTED_CALLDATA_FAILURES = { + # visibility conditions on formats other than raw/addressName (#335) + "gondi/eip712-LoanOffer-v3_1.json", + "gondi/eip712-LoanOffer-v3_2.json", + "paraswap/eip712-paraswap.json", + "permit/eip712-permit-ethereum-dai.json", + "permit/eip712-permit-polygon-dai.json", + # constant/value rejected: $.value above 255 or $.base empty + "rarible/eip712-rarible-exchange-v2.json", + # visibility condition value not encodable for the field type + "gondi/eip712-ExecutionData-v3_1.json", + "gondi/eip712-ExecutionData-v3_2.json", + "ocarina-trade/eip712-OTCRegistry.json", } ERC7730_V2_SCHEMA_PATH = ERC7730_REGISTRY_ROOT / "specs" / "erc7730-v2.schema.json" ERC7730_V2_SCHEMA = load_json_file(ERC7730_V2_SCHEMA_PATH) From 5dcf09172e6a12990b404e52173d15673e57bfeb Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 12 Nov 2026 17:23:37 +0100 Subject: [PATCH 08/13] fix(BACK-12243): address Copilot review of the EIP-712 calldata conversion - bind the domain chain id and verifying contract to the deployment once, reject conflicts, and carry them independently to maps, enums and token checks - reject a given domain separator that is not the one of the declared domain - keep descriptors on networks unknown to Ledger, and isolate schema errors to the failing format - check fixed array indexes, keep the width of a sliced bytesN leaf, pad int constraints only when negative - lint EIP-712 map keys, require 32 bytes hashes, accept $ in struct names Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/erc7730/common/abi.py | 2 +- .../convert_erc7730_v2_input_to_calldata.py | 98 ++++++---- .../convert/calldata/v1/eip712_path.py | 23 ++- .../convert/calldata/v1/eip712_schema.py | 84 ++++++-- src/erc7730/convert/calldata/v1/enum.py | 11 +- src/erc7730/convert/calldata/v1/map.py | 15 +- src/erc7730/convert/calldata/v1/selector.py | 2 +- .../lint_validate_eip712_domain_separator.py | 54 ++---- src/erc7730/lint/v2/lint_validate_map_keys.py | 31 ++- src/erc7730/model/calldata/v1/descriptor.py | 4 +- src/erc7730/model/calldata/v1/instruction.py | 12 +- .../convert/calldata/test_convert_eip712.py | 180 ++++++++++++++++-- ...t_lint_validate_eip712_domain_separator.py | 5 +- tests/v2/lint/test_lint_validate_map_keys.py | 43 ++++- 14 files changed, 428 insertions(+), 136 deletions(-) diff --git a/src/erc7730/common/abi.py b/src/erc7730/common/abi.py index 84a6aa1c..879fd823 100644 --- a/src/erc7730/common/abi.py +++ b/src/erc7730/common/abi.py @@ -152,7 +152,7 @@ def get_functions(abis: list[ABI], *, include_read_only: bool = False) -> Functi return functions -_ENCODE_TYPE_RE = re.compile(r"([\w:]+)\(([^)]*)\)") +_ENCODE_TYPE_RE = re.compile(r"([\w:$]+)\(([^)]*)\)") def parse_encode_type(encode_type: str) -> tuple[str, dict[str, list[tuple[str, str]]]]: diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index a3574072..4485df79 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -22,10 +22,16 @@ from erc7730.common.binary import from_hex from erc7730.common.ledger import ledger_network_id from erc7730.common.options import first_not_none -from erc7730.common.output import ConsoleOutputAdder, OutputAdder, exception_to_output +from erc7730.common.output import ConsoleOutputAdder, ListOutputAdder, OutputAdder, exception_to_output from erc7730.convert.calldata.v1.abi import function_to_abi_tree from erc7730.convert.calldata.v1.eip712_path import convert_eip712_data_path -from erc7730.convert.calldata.v1.eip712_schema import ReconstructedSchema, compute_domain_separator, reconstruct_schema +from erc7730.convert.calldata.v1.eip712_schema import ( + EIP712DomainBinding, + ReconstructedSchema, + bind_domain, + compute_domain_separator, + reconstruct_schema, +) from erc7730.convert.calldata.v1.enum import convert_enums from erc7730.convert.calldata.v1.map import MapEntries from erc7730.convert.calldata.v1.path import ( @@ -36,7 +42,7 @@ from erc7730.convert.resolved.v2.convert_erc7730_input_to_resolved import ( ERC7730InputToResolved, ) -from erc7730.convert.resolved.v2.values import deployment_map_key, encode_value, lookup_map_value +from erc7730.convert.resolved.v2.values import encode_value, is_deployment_key, lookup_map_value from erc7730.model.abi import Function from erc7730.model.calldata.descriptor import ( CalldataDescriptor, @@ -271,10 +277,9 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal else None ) - # Use v1 convert_enums — v2 ResolvedDeployment is duck-type compatible with v1 - enums = convert_enums(deployment, descriptor.metadata.enums, selector=selector) # type: ignore[arg-type] + enums = convert_enums(deployment.chainId, deployment.address, descriptor.metadata.enums, selector=selector) enums_by_id = {enum.enum_id: enum.id for enum in enums} - maps = MapEntries(deployment, selector) + maps = MapEntries(deployment.chainId, deployment.address, selector) fields: list[CalldataDescriptorInstructionFieldV1] = [] for input_field in format.fields: @@ -459,8 +464,11 @@ def _normalize_eip712_constraints( payload = from_hex(constraint) match type_family: case CalldataDescriptorTypeFamily.UINT | CalldataDescriptorTypeFamily.INT: - # no leading zero byte, unless the value is zero (a leaf of the size of the type is a negative integer) - if type_family is CalldataDescriptorTypeFamily.UINT or len(payload) != type_size: + # no leading zero byte, unless the value is zero; only a negative integer has the size of its type + negative = ( + type_family is CalldataDescriptorTypeFamily.INT and len(payload) == type_size and payload[0] >= 0x80 + ) + if not negative: payload = payload.lstrip(b"\x00") or b"\x00" case CalldataDescriptorTypeFamily.ADDRESS: if len(payload) > ADDRESS_LENGTH: @@ -794,12 +802,15 @@ def _convert_v2_param( return None def _deployment_map_key(value_map: ResolvedValueMap) -> str | None: - if maps.deployment is None: + # only for maps keyed on the chain id or the contract address, which the descriptor may not know + key_path = value_map.keyPath + by_chain_id = isinstance(key_path, ContainerPath) and key_path.field == ContainerField.CHAIN_ID + if (key := maps.chain_id if by_chain_id else maps.address) is None: return out.error( title="Missing deployment", - message=f"Map {value_map.map} is keyed by the deployment, which the descriptor does not declare.", + message=f"Map {value_map.map} is keyed by {key_path}, which the descriptor does not declare.", ) - return deployment_map_key(value_map.keyPath, maps.deployment.chainId, maps.deployment.address) + return str(key) def _lookup_deployment_value(value_map: ResolvedValueMap, key: str) -> ResolvedValueConstant | None: if (map_value := lookup_map_value(value_map.values, key)) is None: @@ -819,7 +830,9 @@ def _check_token_chain(params: object) -> bool: :return: True if the token is on the transaction chain, False on error (reported) """ chain_id = getattr(params, "chainId", None) - if isinstance(chain_id, ResolvedValueMap) and (key := _deployment_map_key(chain_id)) is not None: + if isinstance(chain_id, ResolvedValueMap) and is_deployment_key(chain_id.keyPath): + if (key := _deployment_map_key(chain_id)) is None: + return False if (map_value := _lookup_deployment_value(chain_id, key)) is None: return False chain_id = map_value.value @@ -828,9 +841,7 @@ def _check_token_chain(params: object) -> bool: other_chain_path = chain_id_path is not None and not ( isinstance(chain_id_path, ContainerPath) and chain_id_path.field == ContainerField.CHAIN_ID ) - if ( - chain_id is not None and (maps.deployment is None or chain_id != maps.deployment.chainId) - ) or other_chain_path: + if (chain_id is not None and (maps.chain_id is None or chain_id != maps.chain_id)) or other_chain_path: out.error( title="Unsupported token chain", message=f"""Token "{field.label}" may be on another chain than the transaction, which cannot be """ @@ -849,8 +860,10 @@ def _convert_resolved_value( # the calldata descriptor is generated for a single deployment, so a map keyed on the chain id or target # contract address resolves to a constant, other keys are only known when the transaction is signed and # the device looks the value up in the map entries provided with the descriptor - if (key := _deployment_map_key(resolved_value)) is None: + if not is_deployment_key(resolved_value.keyPath): return maps.map_ref(resolved_value, abi_type, convert_path, out) + if (key := _deployment_map_key(resolved_value)) is None: + return None if (map_value := _lookup_deployment_value(resolved_value, key)) is None: return None resolved_value = map_value @@ -910,13 +923,15 @@ def _convert_resolved_value( input_sender_addresses = getattr(address_params, "senderAddress", None) if isinstance(input_sender_addresses, ResolvedValueMap): # sender addresses are constants in the TRUSTED_NAME struct, the device cannot look them up - if (key := _deployment_map_key(input_sender_addresses)) is None: + if not is_deployment_key(input_sender_addresses.keyPath): return out.error( title="Unsupported map key", message=f"Sender addresses cannot be looked up in map {input_sender_addresses.map} using " f"key {input_sender_addresses.keyPath}: the device only accepts constant sender " "addresses, so only @.chainId and @.to keys are supported.", ) + if (key := _deployment_map_key(input_sender_addresses)) is None: + return None if (sender_address := _lookup_deployment_value(input_sender_addresses, key)) is None: return None sender_addresses = [Address(str(sender_address.value))] @@ -1129,15 +1144,13 @@ def _convert_eip712_descriptors( deployments: list[ResolvedDeployment | None] = [*resolved_context.eip712.deployments] or [None] for deployment in deployments: - deployment_chain_id = deployment.chainId if deployment else (domain.chainId if domain else None) - - if chain_id is not None and deployment_chain_id is not None and chain_id != deployment_chain_id: + if (binding := bind_domain(domain, deployment, out)) is None: continue - if deployment_chain_id is not None and ledger_network_id(deployment_chain_id) is None: - out.warning(f"Chain id {deployment_chain_id} is not known, skipping it") + if chain_id is not None and binding.chain_id is not None and chain_id != binding.chain_id: continue + # the domain separator and the primary type hash address the message, an unknown network does not prevent that for encode_type_key, format in resolved_descriptor.display.formats.items(): schema = reconstruct_schema(str(encode_type_key), domain, has_deployments, out) if schema is None: @@ -1145,7 +1158,7 @@ def _convert_eip712_descriptors( descriptor = _convert_eip712_message( descriptor=resolved_descriptor, - deployment=deployment, + binding=binding, domain=domain, domain_separator=resolved_context.eip712.domainSeparator, schema=schema, @@ -1162,7 +1175,7 @@ def _convert_eip712_descriptors( def _convert_eip712_message( descriptor: ResolvedERC7730Descriptor, - deployment: ResolvedDeployment | None, + binding: EIP712DomainBinding, domain: ResolvedDomain | None, domain_separator: str | None, schema: ReconstructedSchema, @@ -1174,7 +1187,7 @@ def _convert_eip712_message( Generate a calldata descriptor for a single EIP-712 message primary type. :param descriptor: resolved v2 source ERC-7730 descriptor - :param deployment: chain id / verifying contract address for which the descriptor is generated, if any + :param binding: chain id / verifying contract address of the domain for which the descriptor is generated :param domain: EIP-712 domain of the messages :param domain_separator: domain separator given by the descriptor, computed from the domain when not set :param schema: reconstructed EIP-712 schema (structs + primary type hash) @@ -1199,14 +1212,12 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal else None ) - # without deployment, the chain id and verifying contract can only come from the domain - chain_id = deployment.chainId if deployment else (domain.chainId if domain else None) - address = deployment.address if deployment else (domain.verifyingContract if domain else None) - if deployment is None and chain_id is not None and address is not None: - deployment = ResolvedDeployment(chainId=chain_id, address=address) + domain_fields = schema.types["EIP712Domain"] + computed = compute_domain_separator(domain_fields, domain, binding, ListOutputAdder() if domain_separator else out) - # a separator given by the descriptor is used as is (the domain of the descriptor may be only partial, it is up to - # the linter to check it against the domain) + # a separator given by the descriptor has to be the one of the domain the descriptor declares: the device is given + # the type of this domain, so a separator of another domain (for instance one with more members than the + # descriptor declares) could never match a message if domain_separator: try: separator_bytes = from_hex(domain_separator) @@ -1219,25 +1230,38 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal "string.", ) domain_separator_hex = HexStr("0x" + separator_bytes.hex()) - elif not schema.types["EIP712Domain"]: + if computed is None or from_hex(computed) != separator_bytes: + return out.error( + title="Domain separator mismatch", + message=f"Domain separator {domain_separator} is not the one of the domain of the descriptor " + f"({computed or 'it cannot be computed'}). Declare every member of the domain (name, version, " + "chainId, verifyingContract, salt) so that its type can be reconstructed.", + ) + elif computed is None: + return None + elif not domain_fields: return out.error( title="Missing domain", message="The domain separator cannot be computed: set the domain or the domain separator.", ) - elif (computed := compute_domain_separator(schema, domain, chain_id, address, out)) is None: - return None else: domain_separator_hex = computed + chain_id = binding.chain_id + address = binding.address + # enums and maps are provided to the device keyed by the message they are for enums = convert_enums( - deployment, # type: ignore[arg-type] + chain_id, + address, descriptor.metadata.enums, domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash, ) enums_by_id = {enum.enum_id: enum.id for enum in enums} - maps = MapEntries(deployment, domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash) + maps = MapEntries( + chain_id, address, domain_separator=domain_separator_hex, primary_type_hash=schema.primary_type_hash + ) fields: list[CalldataDescriptorInstructionFieldV1] = [] for input_field in format.fields: diff --git a/src/erc7730/convert/calldata/v1/eip712_path.py b/src/erc7730/convert/calldata/v1/eip712_path.py index 7e25f229..33988238 100644 --- a/src/erc7730/convert/calldata/v1/eip712_path.py +++ b/src/erc7730/convert/calldata/v1/eip712_path.py @@ -46,6 +46,16 @@ ) +def _leaf_slice_width(parsed: ParsedSolidityType, start: int | None, end: int | None) -> int | None: + """Width in bytes of a slice of a leaf, only known when the leaf has a fixed size (``bytesN``).""" + if parsed.sol_type != CalldataDescriptorEIP712SolType.BYTES_FIX or parsed.type_size is None: + return None + size = parsed.type_size + first = min(max((start or 0) + (size if start is not None and start < 0 else 0), 0), size) + last = size if end is None else min(max(end + (size if end < 0 else 0), 0), size) + return last - first if last > first else None + + def _leaf_type_family_size(parsed: ParsedSolidityType) -> tuple[CalldataDescriptorTypeFamily, int | None]: """Determine the VALUE type family and size (in bytes) from the leaf Solidity type.""" match parsed.sol_type: @@ -83,6 +93,7 @@ def convert_eip712_data_path( current_parsed: ParsedSolidityType | None = None remaining_dims = 0 leaf_sliced = False + slice_width: int | None = None last_index = len(data_path.elements) - 1 for position, element in enumerate(data_path.elements): @@ -136,6 +147,13 @@ def convert_eip712_data_path( title="Invalid EIP-712 path", message="Array index applied to a non-array value.", ) + # the dimension this selector applies to, outermost first + dimension = current_parsed.array_dimensions[remaining_dims - 1] if current_parsed else None + if dimension is not None and not -dimension <= array_index < dimension: + return out.error( + title="Invalid EIP-712 path", + message=f"Array index {array_index} is out of bounds for array of dimension {dimension}.", + ) # a single element [i] is a slice [i, i+1); for i == -1, end defaults to the array length end = None if array_index == -1 else array_index + 1 elements.append(CalldataDescriptorEIP712PathElementArraySliceV1(start=array_index, end=end)) @@ -154,6 +172,7 @@ def convert_eip712_data_path( ) elements.append(CalldataDescriptorEIP712PathElementLeafSliceV1(start=start, end=end)) leaf_sliced = True + slice_width = _leaf_slice_width(current_parsed, start, end) case ArraySlice(start=start, end=end): if remaining_dims <= 0: @@ -191,8 +210,8 @@ def convert_eip712_data_path( type_family, type_size = _leaf_type_family_size(current_parsed) if leaf_sliced: - # the size of a slice is not the size of the type it is cut from - type_size = None + # the size of a slice is not the size of the type it is cut from, it is only known for a fixed size leaf + type_size = slice_width return CalldataDescriptorValuePathV1( type_family=type_family, diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py index 59b57682..7ad0d702 100644 --- a/src/erc7730/convert/calldata/v1/eip712_schema.py +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -21,7 +21,7 @@ CalldataDescriptorEIP712SolType, CalldataDescriptorEIP712StructV1, ) -from erc7730.model.resolved.v2.context import ResolvedDomain +from erc7730.model.resolved.v2.context import ResolvedDeployment, ResolvedDomain from erc7730.model.types import HexStr @@ -46,6 +46,48 @@ class ReconstructedSchema: structs: list[CalldataDescriptorEIP712StructV1] = field(default_factory=list) +@dataclass(frozen=True) +class EIP712DomainBinding: + """Chain id and verifying contract of the domain of the messages, either of which may be unknown.""" + + chain_id: int | None + address: str | None + + +def bind_domain( + domain: ResolvedDomain | None, deployment: ResolvedDeployment | None, out: OutputAdder +) -> EIP712DomainBinding | None: + """ + Resolve the chain id and verifying contract of the domain of the messages of a deployment. + + The deployment provides them when the domain does not declare them, which is also the only source for a descriptor + without deployment. A domain declaring a chain id or a verifying contract the deployment is not on is rejected, + as no message of the deployment can have this domain. + + :param domain: the resolved EIP-712 domain + :param deployment: the deployment the descriptor is generated for, if any + :param out: error handler + :return: the binding, or None on error + """ + domain_chain_id = domain.chainId if domain is not None else None + domain_address = domain.verifyingContract if domain is not None else None + if deployment is None: + return EIP712DomainBinding(chain_id=domain_chain_id, address=domain_address) + + if domain_chain_id is not None and domain_chain_id != deployment.chainId: + return out.error( + title="Conflicting domain chain id", + message=f"The domain chain id {domain_chain_id} is not the one of the deployment {deployment.chainId}.", + ) + if domain_address is not None and domain_address.lower() != deployment.address.lower(): + return out.error( + title="Conflicting domain verifying contract", + message=f"The domain verifying contract {domain_address} is not the one of the deployment " + f"{deployment.address}.", + ) + return EIP712DomainBinding(chain_id=deployment.chainId, address=deployment.address) + + def parse_solidity_type(type_str: str) -> ParsedSolidityType: """ Parse a Solidity type string into base type, size and array dimensions. @@ -94,7 +136,7 @@ def parse_solidity_type(type_str: str) -> ParsedSolidityType: ) -def _reconstruct_domain_fields(domain: ResolvedDomain | None, has_deployments: bool) -> list[tuple[str, str]]: +def reconstruct_domain_fields(domain: ResolvedDomain | None, has_deployments: bool) -> list[tuple[str, str]]: """ Reconstruct the ``EIP712Domain`` type fields, in canonical EIP-712 order. @@ -169,13 +211,21 @@ def reconstruct_schema( types: dict[str, list[tuple[str, str]]] = {} structs: list[CalldataDescriptorEIP712StructV1] = [] - domain_fields = _reconstruct_domain_fields(domain, has_deployments) + domain_fields = reconstruct_domain_fields(domain, has_deployments) types["EIP712Domain"] = domain_fields - structs.append(_build_struct("EIP712Domain", domain_fields)) for type_name, type_fields in raw_types.items(): types[type_name] = type_fields - structs.append(_build_struct(type_name, type_fields)) + + # a type outside the limits of the device is reported for this format only + try: + structs.append(_build_struct("EIP712Domain", domain_fields)) + structs.extend(_build_struct(type_name, type_fields) for type_name, type_fields in raw_types.items()) + except ValueError as e: + return out.error( + title="Unsupported EIP-712 type", + message=f"Format key '{encode_type_key}' has a type the device cannot handle: {e}", + ) # PRIMARY_TYPE_HASH = keccak256(encodeType(primaryType)); normalize to canonical order so the hash does not # depend on the ordering of the source format key @@ -190,26 +240,20 @@ def reconstruct_schema( def compute_domain_separator( - schema: ReconstructedSchema, + domain_fields: list[tuple[str, str]], domain: ResolvedDomain | None, - chain_id: int | None, - address: str | None, + binding: EIP712DomainBinding, out: OutputAdder, ) -> HexStr | None: """ Compute the domain separator, ``hashStruct(domain)``, of the messages of one deployment. - The fields of the domain are the ones of its reconstructed type (see ``reconstruct_schema``): their values are the - ones of the descriptor domain, with the chain id and contract address of the deployment. - - :param schema: reconstructed schema, which holds the type of the domain - :param domain: the resolved EIP-712 domain - :param chain_id: chain id of the domain - :param address: verifying contract of the domain + :param domain_fields: the fields of the type of the domain (see ``reconstruct_domain_fields``) + :param domain: the resolved EIP-712 domain, which holds the values of its name, version and salt + :param binding: chain id and verifying contract of the domain :param out: error handler :return: the domain separator, or None on error """ - domain_fields = schema.types["EIP712Domain"] domain_type = f"EIP712Domain({','.join(f'{type_str} {name}' for type_str, name in domain_fields)})" encoded = bytearray(keccak(text=domain_type)) @@ -219,15 +263,15 @@ def compute_domain_separator( value = getattr(domain, name) encoded += keccak(text=value) case "chainId": - if chain_id is None: + if binding.chain_id is None: _missing_domain_value(name, out) return None - encoded += chain_id.to_bytes(32) + encoded += binding.chain_id.to_bytes(32) case "verifyingContract": - if address is None: + if binding.address is None: _missing_domain_value(name, out) return None - encoded += from_hex(address).rjust(32, b"\x00") + encoded += from_hex(binding.address).rjust(32, b"\x00") case "salt": salt_hex = domain.salt if domain is not None else None try: diff --git a/src/erc7730/convert/calldata/v1/enum.py b/src/erc7730/convert/calldata/v1/enum.py index f927c9ba..9b27ca82 100644 --- a/src/erc7730/convert/calldata/v1/enum.py +++ b/src/erc7730/convert/calldata/v1/enum.py @@ -6,7 +6,6 @@ CalldataDescriptorInstructionEnumValueV1, ) from erc7730.model.metadata import EnumDefinition -from erc7730.model.resolved.context import ResolvedDeployment from erc7730.model.types import HexStr, Id, Selector # A bool holds 0 or 1 in calldata, and an enum key is the field value it matches, so these are @@ -31,7 +30,8 @@ def enum_ordinal(ordinal: str) -> int: def convert_enums( - deployment: ResolvedDeployment | None, + chain_id: int | None, + address: str | None, enums: dict[Id, EnumDefinition] | None, selector: Selector | None = None, domain_separator: HexStr | None = None, @@ -40,7 +40,8 @@ def convert_enums( """ Convert descriptor enum definitions to calldata descriptor enum value instructions. - @param deployment: deployment the enums are bound to + @param chain_id: chain id the enums are bound to + @param address: contract address the enums are bound to @param enums: descriptor enum definitions @param selector: function selector the enums are bound to (transactions) @param domain_separator: domain separator the enums are bound to (EIP-712 messages) @@ -52,8 +53,8 @@ def convert_enums( return [ CalldataDescriptorInstructionEnumValueV1( - chain_id=deployment.chainId if deployment else None, - address=deployment.address if deployment else None, + chain_id=chain_id, + address=address, selector=selector, domain_separator=domain_separator, primary_type_hash=primary_type_hash, diff --git a/src/erc7730/convert/calldata/v1/map.py b/src/erc7730/convert/calldata/v1/map.py index 7be4ee6b..09f46a0e 100644 --- a/src/erc7730/convert/calldata/v1/map.py +++ b/src/erc7730/convert/calldata/v1/map.py @@ -40,7 +40,6 @@ CalldataDescriptorValuePathV1, ) from erc7730.model.paths import ContainerPath, DataPath -from erc7730.model.resolved.v2.context import ResolvedDeployment from erc7730.model.resolved.v2.display import ResolvedValueMap from erc7730.model.types import Address, HexStr, Selector @@ -65,8 +64,8 @@ class MapEntries: """ - Device side maps of a calldata descriptor, bound to a single deployment and either a selector (transaction), or the - domain separator and primary type hash of the message (EIP-712 message). + Device side maps of a calldata descriptor, bound to a single chain and contract and either a selector + (transaction), or the domain separator and primary type hash of the message (EIP-712 message). Map ids are allocated per descriptor: a map looked up several times with the same key and value encodings shares its id and MAP_ENTRY structs, a map looked up with different encodings (for instance its values read as addresses @@ -75,12 +74,14 @@ class MapEntries: def __init__( self, - deployment: ResolvedDeployment | None, + chain_id: int | None, + address: str | None, selector: Selector | None = None, domain_separator: HexStr | None = None, primary_type_hash: HexStr | None = None, ) -> None: - self.deployment = deployment + self.chain_id = chain_id + self.address = address self.selector = selector self.domain_separator = domain_separator self.primary_type_hash = primary_type_hash @@ -132,8 +133,8 @@ def map_ref( for key_source, key_bytes, value_bytes in encoded: self.entries.append( CalldataDescriptorInstructionMapEntryV1( - chain_id=self.deployment.chainId if self.deployment else None, - address=Address(self.deployment.address) if self.deployment else None, + chain_id=self.chain_id, + address=Address(self.address) if self.address else None, selector=self.selector, domain_separator=self.domain_separator, primary_type_hash=self.primary_type_hash, diff --git a/src/erc7730/convert/calldata/v1/selector.py b/src/erc7730/convert/calldata/v1/selector.py index beb38f44..5f613994 100644 --- a/src/erc7730/convert/calldata/v1/selector.py +++ b/src/erc7730/convert/calldata/v1/selector.py @@ -62,7 +62,7 @@ def convert_selector( creator_url = owner_info.url deploy_date = owner_info.deploymentDate.strftime("%Y-%m-%dT%H:%M:%SZ") if owner_info.deploymentDate else None - enums = convert_enums(deployment, descriptor.metadata.enums, selector=selector) + enums = convert_enums(deployment.chainId, deployment.address, descriptor.metadata.enums, selector=selector) enums_by_id = {enum.enum_id: enum.id for enum in enums} diff --git a/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py b/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py index 5be3f07a..b70667ac 100644 --- a/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py +++ b/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py @@ -1,17 +1,17 @@ """ V2 linter that validates the ``domainSeparator`` of an EIP-712 context against the domain of the descriptor. -The converter uses a ``domainSeparator`` given by the descriptor as is, as the ``domain`` constraint of a descriptor may -be only partial (the signed domain can have more members than the ones listed). This linter recomputes the separator -from the declared domain and deployments, and reports when none of them gives the declared value: the device would -never match the messages with it. +The device is given the type of the domain reconstructed from the descriptor, so a ``domainSeparator`` has to be the +one of this domain: the calldata converter rejects a descriptor whose separator differs from the one computed from the +declared domain and deployments. This linter reports it, for instance when the signed domain has more members (such as +a ``version``) than the descriptor declares. """ from typing import final, override from erc7730.common.binary import from_hex from erc7730.common.output import ListOutputAdder, OutputAdder -from erc7730.convert.calldata.v1.eip712_schema import compute_domain_separator, reconstruct_schema +from erc7730.convert.calldata.v1.eip712_schema import bind_domain, compute_domain_separator, reconstruct_domain_fields from erc7730.lint.v2 import ERC7730Linter from erc7730.model.input.v2.descriptor import InputERC7730Descriptor from erc7730.model.resolved.v2.context import ResolvedEIP712Context @@ -22,9 +22,6 @@ class ValidateEIP712DomainSeparatorLinter(ERC7730Linter): """ Validates that the ``domainSeparator`` of an EIP-712 context matches the separator computed from the domain. - - Nothing is reported when the separator cannot be computed (no domain member, or a missing chain id / verifying - contract), as there is nothing to compare it to. """ @override @@ -49,39 +46,30 @@ def lint( ) return - # the type of the domain does not depend on the format key: any valid one gives it - schema = None - for key in descriptor.display.formats: - if schema := reconstruct_schema(str(key), eip712.domain, bool(eip712.deployments), ListOutputAdder()): - break - if schema is None or not schema.types["EIP712Domain"]: - return - - # without deployment the chain id and verifying contract can only come from the domain - bindings: list[tuple[int | None, str | None]] = [(d.chainId, d.address) for d in eip712.deployments] - if not bindings: - domain = eip712.domain - bindings = [(domain.chainId, domain.verifyingContract) if domain else (None, None)] + domain_fields = reconstruct_domain_fields(eip712.domain, bool(eip712.deployments)) + bindings = [bind_domain(eip712.domain, deployment, ListOutputAdder()) for deployment in eip712.deployments] + if not eip712.deployments: + bindings = [bind_domain(eip712.domain, None, ListOutputAdder())] computed = [ - compute_domain_separator(schema, eip712.domain, chain_id, address, ListOutputAdder()) - for chain_id, address in bindings + compute_domain_separator(domain_fields, eip712.domain, binding, ListOutputAdder()) if binding else None + for binding in bindings ] known = [separator for separator in computed if separator is not None] - if not known: - return + matching = [separator for separator in known if from_hex(separator) == declared_bytes] - expected = {bytes.fromhex(separator[2:]) for separator in known} - if declared_bytes not in expected: - out.warning( + if not matching: + out.error( title="Domain separator mismatch", message=f"Domain separator {declared} is not the one computed from the domain " - f"({', '.join(sorted(known))}). If the domain is partial this is expected, otherwise the device will " - "not match the messages of this descriptor.", + f"({', '.join(sorted(known)) or 'it cannot be computed'}). Declare every member of the domain (name, " + "version, chainId, verifyingContract, salt), otherwise the converter rejects the descriptor and the " + "device cannot match its messages.", ) - elif len(known) > 1: + elif len(matching) < len(computed): out.warning( title="Domain separator shared by several deployments", - message=f"Domain separator {declared} matches only some of the {len(known)} deployments, as it " - "depends on the chain id and the verifying contract. Omit it to compute one per deployment.", + message=f"Domain separator {declared} matches only some of the {len(computed)} deployments, as it " + "depends on the chain id and the verifying contract: the others are rejected by the converter. Omit it " + "to compute one per deployment.", ) diff --git a/src/erc7730/lint/v2/lint_validate_map_keys.py b/src/erc7730/lint/v2/lint_validate_map_keys.py index e9e61200..664e62b1 100644 --- a/src/erc7730/lint/v2/lint_validate_map_keys.py +++ b/src/erc7730/lint/v2/lint_validate_map_keys.py @@ -8,8 +8,10 @@ from collections.abc import Callable from typing import assert_never, final, override -from erc7730.common.output import OutputAdder +from erc7730.common.output import ListOutputAdder, OutputAdder from erc7730.convert.calldata.v1.abi import ABITree, function_to_abi_tree +from erc7730.convert.calldata.v1.eip712_path import convert_eip712_data_path +from erc7730.convert.calldata.v1.eip712_schema import ReconstructedSchema, reconstruct_schema from erc7730.convert.calldata.v1.map import encode_map_keys from erc7730.convert.calldata.v1.path import convert_data_path from erc7730.convert.resolved.v2.values import is_deployment_key @@ -34,8 +36,8 @@ class ValidateMapKeysLinter(ERC7730Linter): Validates that the keys of maps looked up with a key read from the transaction can be encoded as the key value. Maps keyed on the chain id or the target contract address are resolved for each deployment and validated during - resolution. Only contract descriptors with function signatures as format keys are validated: the ABI is needed to - know how the key is encoded. + resolution. Contract descriptors are only validated with function signatures as format keys: the ABI is needed to + know how the key is encoded. EIP-712 descriptors use the schema rebuilt from their format keys. """ @override @@ -43,8 +45,18 @@ def lint( self, input_descriptor: InputERC7730Descriptor, descriptor: ResolvedERC7730Descriptor, out: OutputAdder ) -> None: match descriptor.context: - case ResolvedEIP712Context(): - pass # map lookups are not supported for EIP-712 messages by the device + case ResolvedEIP712Context() as context: + for encode_type_key, fmt in descriptor.display.formats.items(): + if not (value_maps := [value_map for field in fmt.fields for value_map in _value_maps(field)]): + continue + # a format that cannot be converted is reported by the converter + schema = reconstruct_schema( + str(encode_type_key), context.eip712.domain, bool(context.eip712.deployments), ListOutputAdder() + ) + if schema is None: + continue + for value_map in value_maps: + encode_map_keys(value_map, _eip712_path_converter(schema), out) case ResolvedContractContext(): abis = parse_declared_abis(input_descriptor) for selector, fmt in descriptor.display.formats.items(): @@ -77,6 +89,15 @@ def _value_maps(field: ResolvedField) -> list[ResolvedValueMap]: assert_never(field) +def _eip712_path_converter( + schema: ReconstructedSchema, +) -> Callable[[DataPath, OutputAdder], CalldataDescriptorValuePathV1 | None]: + def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorValuePathV1 | None: + return convert_eip712_data_path(data_path, schema.primary_type, schema.types, out) + + return convert_path + + def _path_converter(abi_tree: ABITree) -> Callable[[DataPath, OutputAdder], CalldataDescriptorValuePathV1 | None]: def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorValuePathV1 | None: return convert_data_path(data_path, abi_tree, out) diff --git a/src/erc7730/model/calldata/v1/descriptor.py b/src/erc7730/model/calldata/v1/descriptor.py index 8e7a0397..9c0cc5ed 100644 --- a/src/erc7730/model/calldata/v1/descriptor.py +++ b/src/erc7730/model/calldata/v1/descriptor.py @@ -129,14 +129,14 @@ class CalldataDescriptorEIP712V1(CalldataDescriptorBase): domain_separator: HexStr = Field( title="Domain separator", description="hashStruct(domain) of the EIP-712 message domain.", - min_length=64, + min_length=66, max_length=66, ) primary_type_hash: HexStr = Field( title="Primary type hash", description="keccak256(encodeType(primaryType)) of the EIP-712 message primary type.", - min_length=64, + min_length=66, max_length=66, ) diff --git a/src/erc7730/model/calldata/v1/instruction.py b/src/erc7730/model/calldata/v1/instruction.py index ea4546a5..ad851f3e 100644 --- a/src/erc7730/model/calldata/v1/instruction.py +++ b/src/erc7730/model/calldata/v1/instruction.py @@ -213,14 +213,14 @@ class CalldataDescriptorInstructionEIP712MessageInfoV1(CalldataDescriptorInstruc domain_separator: HexStr = Field( title="Domain separator", description="hashStruct(domain) of the EIP-712 message domain.", - min_length=64, + min_length=66, max_length=66, ) primary_type_hash: HexStr = Field( title="Primary type hash", description="keccak256(encodeType(primaryType)) of the EIP-712 message primary type.", - min_length=64, + min_length=66, max_length=66, ) @@ -266,7 +266,7 @@ class CalldataDescriptorInstructionEnumValueV1(CalldataDescriptorInstructionBase default=None, title="Domain separator", description="hashStruct(domain) of the EIP-712 message this descriptor applies to (EIP-712 messages only).", - min_length=64, + min_length=66, max_length=66, ) @@ -275,7 +275,7 @@ class CalldataDescriptorInstructionEnumValueV1(CalldataDescriptorInstructionBase title="Primary type hash", description="keccak256(encodeType(primaryType)) of the EIP-712 message this descriptor applies to (EIP-712 " "messages only).", - min_length=64, + min_length=66, max_length=66, ) @@ -357,7 +357,7 @@ class CalldataDescriptorInstructionMapEntryV1(CalldataDescriptorInstructionBaseV default=None, title="Domain separator", description="hashStruct(domain) of the EIP-712 message this descriptor applies to (EIP-712 messages only).", - min_length=64, + min_length=66, max_length=66, ) @@ -366,7 +366,7 @@ class CalldataDescriptorInstructionMapEntryV1(CalldataDescriptorInstructionBaseV title="Primary type hash", description="keccak256(encodeType(primaryType)) of the EIP-712 message this descriptor applies to (EIP-712 " "messages only).", - min_length=64, + min_length=66, max_length=66, ) diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 6fbe8ad3..480d25e0 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -1,13 +1,16 @@ import json from typing import Any +import pytest from eth_utils import keccak -from erc7730.common.output import ListOutputAdder, OutputAdder +from erc7730.common.output import ListOutputAdder, Output, OutputAdder from erc7730.convert.calldata.convert_erc7730_v2_input_to_calldata import ( erc7730_v2_descriptor_to_calldata_descriptors, ) +from erc7730.convert.calldata.v1.eip712_schema import reconstruct_schema from erc7730.convert.calldata.v1.tlv import tlv_eip712_field, tlv_eip712_message_info, tlv_eip712_path_element +from erc7730.model.calldata.descriptor import CalldataDescriptor from erc7730.model.calldata.v1.descriptor import CalldataDescriptorEIP712V1 from erc7730.model.calldata.v1.eip712 import CalldataDescriptorEIP712FieldV1, CalldataDescriptorEIP712SolType from erc7730.model.calldata.v1.value import ( @@ -32,7 +35,7 @@ def _eip712_path(descriptor: CalldataDescriptorEIP712V1, index: int) -> Calldata return path -def _convert( +def _convert_all( encode_type: str, fields: list[dict[str, Any]], *, @@ -41,9 +44,10 @@ def _convert( address: str = DEFAULT_ADDRESS, deployments: list[dict[str, Any]] | None = None, domain_separator: str | None = None, + maps: dict[str, Any] | None = None, out: OutputAdder | None = None, -) -> CalldataDescriptorEIP712V1: - """Build a minimal EIP-712 v2 descriptor and return the single converted calldata descriptor.""" +) -> list[CalldataDescriptor]: + """Build a minimal EIP-712 v2 descriptor and return the converted calldata descriptors.""" descriptor = InputERC7730Descriptor.model_validate_json( json.dumps( { @@ -58,13 +62,21 @@ def _convert( **({"domainSeparator": domain_separator} if domain_separator else {}), }, }, - "metadata": {"owner": "Test Owner"}, + "metadata": { + "owner": "Test Owner", + **({"maps": {name: {"values": values} for name, values in maps.items()}} if maps else {}), + }, "display": {"formats": {encode_type: {"intent": "Test intent", "fields": fields}}}, } ) ) - descriptors = erc7730_v2_descriptor_to_calldata_descriptors(descriptor, chain_id=chain_id, out=out) + return erc7730_v2_descriptor_to_calldata_descriptors(descriptor, chain_id=chain_id, out=out) + + +def _convert(encode_type: str, fields: list[dict[str, Any]], **kwargs: Any) -> CalldataDescriptorEIP712V1: + """Build a minimal EIP-712 v2 descriptor and return the single converted calldata descriptor.""" + descriptors = _convert_all(encode_type, fields, **kwargs) assert len(descriptors) == 1 descriptor_out = descriptors[0] assert isinstance(descriptor_out, CalldataDescriptorEIP712V1) @@ -279,8 +291,9 @@ def test_eip712_descriptor_without_deployment_is_not_bound_to_a_chain() -> None: descriptor = _convert( PERMIT_TYPE, [{"path": "value", "label": "Value", "format": "amount"}], + domain={"name": "Test"}, deployments=[], - domain_separator="0x" + "ab" * 32, + domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), chain_id=137, ) @@ -318,15 +331,160 @@ def test_eip712_descriptor_without_deployment_takes_chain_and_contract_from_the_ assert descriptor.domain_separator == expected -def test_eip712_domain_separator_given_by_the_descriptor_is_used_as_is() -> None: +def test_eip712_domain_separator_given_by_the_descriptor_is_used() -> None: + expected = _domain_separator( + [ + ("string", "name", keccak(text="Test")), + ("string", "version", keccak(text="1")), + ("uint256", "chainId", DEFAULT_CHAIN_ID.to_bytes(32)), + ("address", "verifyingContract", bytes.fromhex(DEFAULT_ADDRESS[2:]).rjust(32, b"\x00")), + ] + ) out = ListOutputAdder() descriptor = _convert( PERMIT_TYPE, [{"path": "value", "label": "Value", "format": "amount"}], - deployments=[], - domain_separator="0x" + "ab" * 32, + domain_separator=expected, out=out, ) - assert descriptor.domain_separator == "0x" + "ab" * 32 + assert descriptor.domain_separator == expected assert not out.outputs + + +def test_eip712_domain_separator_of_another_domain_is_rejected() -> None: + # the separator can be the one of a domain with more members than the descriptor declares: its type is unknown + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + domain_separator="0x" + "ab" * 32, + out=out, + ) + + assert descriptors == [] + assert [o.title for o in out.outputs if o.level == Output.Level.ERROR] == ["Domain separator mismatch"] + + +TOKEN = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + + +def _errors(out: ListOutputAdder) -> list[str | None]: + return [o.title for o in out.outputs if o.level == Output.Level.ERROR] + + +def _token_amount(key_path: str, chain_id: int | None = None) -> dict[str, Any]: + token: dict[str, Any] = {"map": "$.metadata.maps.tokens", "keyPath": key_path} + params: dict[str, Any] = {"token": token} + if chain_id is not None: + params["chainId"] = chain_id + return {"path": "value", "label": "Amount", "format": "tokenAmount", "params": params} + + +def test_eip712_message_keyed_map_does_not_need_a_deployment() -> None: + out = ListOutputAdder() + descriptor = _convert( + PERMIT_TYPE, + [_token_amount("#.nonce")], + domain={"name": "Test"}, + deployments=[], + domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), + maps={"tokens": {"0": TOKEN}}, + out=out, + ) + + assert not out.has_errors + assert len(descriptor.maps) == 1 + + +def test_eip712_chain_keyed_map_with_a_domain_chain_but_no_contract() -> None: + out = ListOutputAdder() + descriptor = _convert( + PERMIT_TYPE, + [_token_amount("@.chainId", chain_id=1)], + domain={"name": "Test", "chainId": 1}, + deployments=[], + domain_separator=_domain_separator( + [("string", "name", keccak(text="Test")), ("uint256", "chainId", (1).to_bytes(32))] + ), + maps={"tokens": {"1": TOKEN}}, + out=out, + ) + + assert not out.has_errors + assert descriptor.chain_id == 1 + assert descriptor.address is None + assert descriptor.maps == [] + + +def test_eip712_domain_conflicting_with_the_deployment_is_rejected() -> None: + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + domain={"name": "Test", "chainId": 10}, + out=out, + ) + + assert descriptors == [] + assert _errors(out) == ["Conflicting domain chain id"] + + +def test_eip712_descriptor_on_an_unknown_network_is_kept() -> None: + descriptor = _convert( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + chain_id=999_999_999, + ) + + assert descriptor.network is None + assert descriptor.chain_id == 999_999_999 + assert descriptor.model_dump_json() + + +def test_eip712_type_outside_the_device_limits_is_reported() -> None: + out = ListOutputAdder() + + assert reconstruct_schema("Batch(uint256[256] values)", None, False, out) is None + assert _errors(out) == ["Unsupported EIP-712 type"] + + +def test_eip712_struct_name_with_dollar_sign() -> None: + schema = reconstruct_schema("Weird$Type_1(uint256 value)", None, False, ListOutputAdder()) + + assert schema is not None + assert schema.primary_type == "Weird$Type_1" + assert schema.primary_type_hash == "0x" + keccak(text="Weird$Type_1(uint256 value)").hex() + + +@pytest.mark.parametrize( + ("path", "valid"), + [("values.[1]", True), ("values.[-2]", True), ("values.[2]", False), ("values.[-3]", False)], +) +def test_eip712_fixed_array_index_is_checked(path: str, valid: bool) -> None: + descriptors = _convert_all("Batch(uint256[2] values)", [{"path": path, "label": "Value", "format": "raw"}]) + + assert bool(descriptors) is valid + + +def test_eip712_leaf_slice_of_a_fixed_size_leaf_keeps_its_width() -> None: + descriptor = _convert("Msg(bytes32 key)", [{"path": "key.[0:4]", "label": "Key", "format": "raw"}]) + + value = descriptor.fields[0].param.value + assert isinstance(value, CalldataDescriptorValuePathV1) + assert value.type_size == 4 + + +@pytest.mark.parametrize( + ("constraint", "expected"), + [("0x0005", "0x05"), (5, "0x05"), ("0xff80", "0xff80"), (-128, "0xff80")], +) +def test_eip712_full_width_int_constraint_is_padded_for_negative_values_only( + constraint: str | int, expected: str +) -> None: + descriptor = _convert( + "Msg(int16 v)", + [{"path": "v", "label": "V", "format": "raw", "visible": {"mustMatch": [constraint]}}], + ) + + assert descriptor.fields[0].constraints == [expected] diff --git a/tests/v2/lint/test_lint_validate_eip712_domain_separator.py b/tests/v2/lint/test_lint_validate_eip712_domain_separator.py index bd5784da..215295c8 100644 --- a/tests/v2/lint/test_lint_validate_eip712_domain_separator.py +++ b/tests/v2/lint/test_lint_validate_eip712_domain_separator.py @@ -112,5 +112,6 @@ def test_invalid_domain_separator_length() -> None: assert [title for title, _ in outputs] == ["Invalid domain separator"] -def test_domain_separator_without_domain_is_not_compared() -> None: - assert lint({"domainSeparator": "0x" + "ab" * 32}) == [] +def test_domain_separator_without_domain_is_a_mismatch() -> None: + outputs = lint({"domainSeparator": "0x" + "ab" * 32}) + assert [title for title, _ in outputs] == ["Domain separator mismatch"] diff --git a/tests/v2/lint/test_lint_validate_map_keys.py b/tests/v2/lint/test_lint_validate_map_keys.py index 69ee8c1e..86e7a828 100644 --- a/tests/v2/lint/test_lint_validate_map_keys.py +++ b/tests/v2/lint/test_lint_validate_map_keys.py @@ -1,4 +1,5 @@ import json +from collections.abc import Mapping import pytest @@ -11,7 +12,20 @@ TOKEN_B = "0xdAC17F958D2ee523a2206206994597C13D831ec7" -def lint(key_path: str, keys: list[str], signature: str = "deposit(uint256 assets, uint32 marketId)") -> list[str]: +EIP712_CONTEXT = { + "eip712": { + "deployments": [{"chainId": 1, "address": "0x0000000000000000000000000000000000000001"}], + "domain": {"name": "Test"}, + } +} + + +def lint( + key_path: str, + keys: list[str], + signature: str = "deposit(uint256 assets, uint32 marketId)", + context: Mapping[str, object] | None = None, +) -> list[str]: """Lint a descriptor looking up a token amount token in a map, with the given keys.""" descriptor = InputERC7730Descriptor.model_validate_json( json.dumps( @@ -19,9 +33,14 @@ def lint(key_path: str, keys: list[str], signature: str = "deposit(uint256 asset "$schema": "specs/erc7730-v2.schema.json", "context": { "$id": "test", - "contract": { - "deployments": [{"chainId": 1, "address": "0x0000000000000000000000000000000000000001"}] - }, + **( + context + or { + "contract": { + "deployments": [{"chainId": 1, "address": "0x0000000000000000000000000000000000000001"}] + } + } + ), }, "metadata": { "owner": "Test Owner", @@ -114,3 +133,19 @@ def test_format_without_map_lookup_not_converted_to_abi_tree() -> None: assert resolved is not None, out.outputs ValidateMapKeysLinter().lint(descriptor, resolved, out) assert out.outputs == [] + + +@pytest.mark.parametrize( + "keys,expected", + [ + (["1", "4294967296"], 'Key "4294967296" of map $.metadata.maps.tokens cannot be matched'), + (["1", "foo"], 'Key "foo" of map $.metadata.maps.tokens cannot be matched'), + ], +) +def test_invalid_eip712_keys(keys: list[str], expected: str) -> None: + messages = lint("#.marketId", keys, "Deposit(uint256 assets,uint32 marketId)", EIP712_CONTEXT) + assert any(expected in message for message in messages), messages + + +def test_valid_eip712_keys() -> None: + assert lint("#.marketId", ["1", "4294967295"], "Deposit(uint256 assets,uint32 marketId)", EIP712_CONTEXT) == [] From 39fd31f8ef3c41c3a9b8dbddacef4b0373e9848d Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 26 Nov 2026 09:56:52 +0100 Subject: [PATCH 09/13] fix(BACK-12243): address the remaining Copilot review findings - filter deployments by the requested chain before binding them to the domain - report path bounds, struct field indices and statically empty leaf slices the device cannot represent - reject non canonical integer and bytesN widths, undefined referenced structs and conflicting EIP712Domain - use the legal name of the owner info when set - fail the registry test on any conversion error, not only on empty output - drop the serve text length error made obsolete by DER encoded TLV lengths Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../convert_erc7730_v2_input_to_calldata.py | 7 +- .../convert/calldata/v1/eip712_path.py | 42 +++++++++++- .../convert/calldata/v1/eip712_schema.py | 36 +++++++--- src/erc7730/serve/v2/compile.py | 4 +- .../calldata/test_convert_registry_files.py | 6 +- tests/files.py | 1 + tests/serve/v2/test_compile.py | 2 - .../convert/calldata/test_convert_eip712.py | 68 +++++++++++++++++++ 8 files changed, 146 insertions(+), 20 deletions(-) diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index 4485df79..18bca22e 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -1144,6 +1144,10 @@ def _convert_eip712_descriptors( deployments: list[ResolvedDeployment | None] = [*resolved_context.eip712.deployments] or [None] for deployment in deployments: + # a deployment of another chain is not converted, so its conflicts with the domain are not reported either + if chain_id is not None and deployment is not None and deployment.chainId != chain_id: + continue + if (binding := bind_domain(domain, deployment, out)) is None: continue @@ -1204,7 +1208,8 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal creator_url: str | None = None deploy_date: str | None = None if descriptor.metadata.info is not None: - creator_legal_name = descriptor.metadata.owner + # the v2 schema has no legal name: the owner is the one of the entity + creator_legal_name = descriptor.metadata.info.legalName or descriptor.metadata.owner creator_url = str(descriptor.metadata.info.url) if descriptor.metadata.info.url else None deploy_date = ( descriptor.metadata.info.deploymentDate.strftime("%Y-%m-%dT%H:%M:%SZ") diff --git a/src/erc7730/convert/calldata/v1/eip712_path.py b/src/erc7730/convert/calldata/v1/eip712_path.py index 33988238..da0902fd 100644 --- a/src/erc7730/convert/calldata/v1/eip712_path.py +++ b/src/erc7730/convert/calldata/v1/eip712_path.py @@ -39,6 +39,10 @@ # leaf types a leaf slice applies to +_MIN_BOUND = -32768 +_MAX_BOUND = 32767 +_MAX_FIELD_INDEX = 255 + _SLICEABLE_LEAVES = ( CalldataDescriptorEIP712SolType.BYTES_FIX, CalldataDescriptorEIP712SolType.BYTES_DYN, @@ -46,14 +50,19 @@ ) +def _unrepresentable_bound(*bounds: int | None) -> int | None: + """First bound the device cannot represent (signed 16 bits), if any.""" + return next((bound for bound in bounds if bound is not None and not _MIN_BOUND <= bound <= _MAX_BOUND), None) + + def _leaf_slice_width(parsed: ParsedSolidityType, start: int | None, end: int | None) -> int | None: - """Width in bytes of a slice of a leaf, only known when the leaf has a fixed size (``bytesN``).""" + """Width in bytes of a slice of a leaf, only known when the leaf has a fixed size (``bytesN``), 0 if empty.""" if parsed.sol_type != CalldataDescriptorEIP712SolType.BYTES_FIX or parsed.type_size is None: return None size = parsed.type_size first = min(max((start or 0) + (size if start is not None and start < 0 else 0), 0), size) last = size if end is None else min(max(end + (size if end < 0 else 0), 0), size) - return last - first if last > first else None + return max(last - first, 0) def _leaf_type_family_size(parsed: ParsedSolidityType) -> tuple[CalldataDescriptorTypeFamily, int | None]: @@ -128,6 +137,13 @@ def convert_eip712_data_path( message=f'Field "{name}" not found in struct "{current_struct}".', ) + if index > _MAX_FIELD_INDEX: + return out.error( + title="Invalid EIP-712 path", + message=f'Field "{name}" is the field {index} of struct "{current_struct}", the device ' + f"addresses at most {_MAX_FIELD_INDEX + 1} fields.", + ) + elements.append(CalldataDescriptorEIP712PathElementStructFieldV1(index=index)) current_parsed = parse_solidity_type(struct_fields[index][0]) remaining_dims = len(current_parsed.array_dimensions) @@ -156,6 +172,11 @@ def convert_eip712_data_path( ) # a single element [i] is a slice [i, i+1); for i == -1, end defaults to the array length end = None if array_index == -1 else array_index + 1 + if (bound := _unrepresentable_bound(array_index, end)) is not None: + return out.error( + title="Invalid EIP-712 path", + message=f"Array index {array_index} is not supported, the device cannot represent {bound}.", + ) elements.append(CalldataDescriptorEIP712PathElementArraySliceV1(start=array_index, end=end)) remaining_dims -= 1 @@ -170,9 +191,19 @@ def convert_eip712_data_path( title="Invalid EIP-712 path", message=f"Leaf slice [{start}:{end}] is empty, the device refuses a slice with no byte.", ) + if (bound := _unrepresentable_bound(start, end)) is not None: + return out.error( + title="Invalid EIP-712 path", + message=f"Leaf slice [{start}:{end}] is not supported, the device cannot represent {bound}.", + ) + slice_width = _leaf_slice_width(current_parsed, start, end) + if slice_width == 0: + return out.error( + title="Invalid EIP-712 path", + message=f"Leaf slice [{start}:{end}] is empty, the device refuses a slice with no byte.", + ) elements.append(CalldataDescriptorEIP712PathElementLeafSliceV1(start=start, end=end)) leaf_sliced = True - slice_width = _leaf_slice_width(current_parsed, start, end) case ArraySlice(start=start, end=end): if remaining_dims <= 0: @@ -180,6 +211,11 @@ def convert_eip712_data_path( title="Invalid EIP-712 path", message="Array slice applied to a non-array value.", ) + if (bound := _unrepresentable_bound(start, end)) is not None: + return out.error( + title="Invalid EIP-712 path", + message=f"Array slice [{start}:{end}] is not supported, the device cannot represent {bound}.", + ) elements.append(CalldataDescriptorEIP712PathElementArraySliceV1(start=start, end=end)) remaining_dims -= 1 diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py index 7ad0d702..73eb907a 100644 --- a/src/erc7730/convert/calldata/v1/eip712_schema.py +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -88,6 +88,13 @@ def bind_domain( return EIP712DomainBinding(chain_id=deployment.chainId, address=deployment.address) +def _integer_size(base: str, width: str) -> int: + """Size in bytes of an integer type, which has to be written in its canonical form (``uint256`` not ``uint``).""" + if not width or int(width) % 8 != 0 or not 8 <= int(width) <= 256 or width != str(int(width)): + raise ValueError(f"{base} is not a valid type, an integer is written with its width, 8 to 256 by steps of 8") + return int(width) // 8 + + def parse_solidity_type(type_str: str) -> ParsedSolidityType: """ Parse a Solidity type string into base type, size and array dimensions. @@ -111,10 +118,10 @@ def parse_solidity_type(type_str: str) -> ParsedSolidityType: if (match := re.fullmatch(r"uint(\d*)", base)) is not None: sol_type = CalldataDescriptorEIP712SolType.UINT - type_size = (int(match.group(1)) if match.group(1) else 256) // 8 + type_size = _integer_size(base, match.group(1)) elif (match := re.fullmatch(r"int(\d*)", base)) is not None: sol_type = CalldataDescriptorEIP712SolType.INT - type_size = (int(match.group(1)) if match.group(1) else 256) // 8 + type_size = _integer_size(base, match.group(1)) elif base == "address": sol_type = CalldataDescriptorEIP712SolType.ADDRESS elif base == "bool": @@ -126,6 +133,8 @@ def parse_solidity_type(type_str: str) -> ParsedSolidityType: elif (match := re.fullmatch(r"bytes(\d+)", base)) is not None: sol_type = CalldataDescriptorEIP712SolType.BYTES_FIX type_size = int(match.group(1)) + if not 1 <= type_size <= 32: + raise ValueError(f"{base} is not a valid type, bytesN is 1 to 32 bytes") else: # TODO fixed/ufixed Solidity types are not handled (rare in EIP-712); anything else is treated as a struct sol_type = CalldataDescriptorEIP712SolType.STRUCT @@ -208,19 +217,26 @@ def reconstruct_schema( message=f"Failed to parse format key as encodeType: {e}", ) - types: dict[str, list[tuple[str, str]]] = {} - structs: list[CalldataDescriptorEIP712StructV1] = [] - domain_fields = reconstruct_domain_fields(domain, has_deployments) - types["EIP712Domain"] = domain_fields - for type_name, type_fields in raw_types.items(): - types[type_name] = type_fields + # the domain is described by the descriptor: a message type of the same name is the same type or a conflict + if raw_types.get("EIP712Domain", domain_fields) != domain_fields: + return out.error( + title="Conflicting EIP712Domain", + message=f"Format key '{encode_type_key}' defines EIP712Domain differently from the domain of the " + "descriptor.", + ) + + types: dict[str, list[tuple[str, str]]] = {"EIP712Domain": domain_fields, **raw_types} + structs: list[CalldataDescriptorEIP712StructV1] = [] # a type outside the limits of the device is reported for this format only try: - structs.append(_build_struct("EIP712Domain", domain_fields)) - structs.extend(_build_struct(type_name, type_fields) for type_name, type_fields in raw_types.items()) + structs.extend(_build_struct(type_name, type_fields) for type_name, type_fields in types.items()) + for type_name, type_fields in types.items(): + for type_str, field_name in type_fields: + if (struct_name := parse_solidity_type(type_str).struct_name) is not None and struct_name not in types: + raise ValueError(f"{type_name}.{field_name} refers to the undefined struct {struct_name}") except ValueError as e: return out.error( title="Unsupported EIP-712 type", diff --git a/src/erc7730/serve/v2/compile.py b/src/erc7730/serve/v2/compile.py index cee55e2f..c0484e04 100644 --- a/src/erc7730/serve/v2/compile.py +++ b/src/erc7730/serve/v2/compile.py @@ -55,11 +55,9 @@ def compile_calldata(descriptor: InputERC7730Descriptor) -> CompileResult: ) if out.has_errors: return ConversionFailed(diagnostics) - # the TLV is only encoded during serialization, with one-byte lengths and ASCII text + # the TLV is only encoded during serialization, and only supports ASCII text try: payload = RootModel[list[CalldataDescriptor]](descriptors).model_dump(mode="json", exclude_none=True) - except OverflowError: - return InvalidDescriptor("a text is too long for the calldata TLV encoding") except UnicodeEncodeError as e: return InvalidDescriptor(f"calldata descriptors: ASCII text only, found {e.object[e.start : e.end]!r}") return Compiled(tuple(payload), diagnostics) diff --git a/tests/convert/calldata/test_convert_registry_files.py b/tests/convert/calldata/test_convert_registry_files.py index d235b2d5..bcef8664 100644 --- a/tests/convert/calldata/test_convert_registry_files.py +++ b/tests/convert/calldata/test_convert_registry_files.py @@ -2,6 +2,7 @@ import pytest +from erc7730.common.output import ListOutputAdder from erc7730.convert.calldata.convert_erc7730_v2_input_to_calldata import ( erc7730_v2_descriptor_to_calldata_descriptors, ) @@ -20,8 +21,11 @@ def test_registry_files(request: pytest.FixtureRequest, input_file: Path) -> Non if path_id(input_file) in ERC7730_EXPECTED_CALLDATA_FAILURES: request.applymarker(pytest.mark.xfail(strict=True, reason="unsupported by the calldata converter")) - descriptors = erc7730_v2_descriptor_to_calldata_descriptors(InputERC7730Descriptor.load(input_file)) + out = ListOutputAdder() + descriptors = erc7730_v2_descriptor_to_calldata_descriptors(InputERC7730Descriptor.load(input_file), out=out) + # the converter skips what it cannot convert and returns the rest, so an error means a partial result + assert not out.has_errors, out.outputs assert descriptors # model_dump_json evaluates every computed TLV .descriptor field, exercising the full TLV encoding for descriptor in descriptors: diff --git a/tests/files.py b/tests/files.py index 6a4afba5..456e8a09 100644 --- a/tests/files.py +++ b/tests/files.py @@ -56,6 +56,7 @@ def _is_registry_descriptor(path: Path) -> bool: # visibility conditions on formats other than raw/addressName (#335) "gondi/eip712-LoanOffer-v3_1.json", "gondi/eip712-LoanOffer-v3_2.json", + "ophis/eip712-Ophis-GPv2Settlement.json", "paraswap/eip712-paraswap.json", "permit/eip712-permit-ethereum-dai.json", "permit/eip712-permit-polygon-dai.json", diff --git a/tests/serve/v2/test_compile.py b/tests/serve/v2/test_compile.py index f2fe1d47..02527e50 100644 --- a/tests/serve/v2/test_compile.py +++ b/tests/serve/v2/test_compile.py @@ -42,7 +42,6 @@ def test_compile_json_matches_reference_output(token: str) -> None: "calldata descriptors: ASCII text only, found 'é'", ), (json.dumps(_with_label("Café"), ensure_ascii=False).encode(), "display: ASCII text only, found 'é'"), - (json.dumps(_descriptor(metadata={"owner": "A" * 256})).encode(), "too long for the calldata TLV encoding"), ], ids=[ "not json", @@ -50,7 +49,6 @@ def test_compile_json_matches_reference_output(token: str) -> None: "not utf-8", "escaped non-ascii owner", "raw non-ascii label", - "owner too long", ], ) def test_compile_json_rejects_invalid_descriptors(body: bytes, message: str) -> None: diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 480d25e0..55fe87b2 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -21,6 +21,7 @@ CalldataDescriptorValuePathV1, ) from erc7730.model.input.v2.descriptor import InputERC7730Descriptor +from erc7730.model.resolved.v2.context import ResolvedDomain DEFAULT_CHAIN_ID = 1 DEFAULT_ADDRESS = "0x000000000000000000000000000000000000dEaD" @@ -488,3 +489,70 @@ def test_eip712_full_width_int_constraint_is_padded_for_negative_values_only( ) assert descriptor.fields[0].constraints == [expected] + + +def test_eip712_chain_filter_does_not_report_conflicts_of_other_chains() -> None: + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + domain={"name": "Test", "chainId": 1}, + deployments=[{"chainId": 1, "address": DEFAULT_ADDRESS}, {"chainId": 10, "address": DEFAULT_ADDRESS}], + chain_id=1, + out=out, + ) + + assert len(descriptors) == 1 + assert not out.has_errors + + +@pytest.mark.parametrize( + "type_str,path", + [ + ("Batch(uint256[] values)", "values.[32767]"), + ("Batch(uint256[] values)", "values.[32768:]"), + ("Msg(bytes key)", "key.[0:32768]"), + ("Msg(bytes32 key)", "key.[32:40]"), + ("Msg(bytes32 key)", "key.[-1:0]"), + ("Msg(" + ",".join(f"uint8 f{i}" for i in range(257)) + ")", "f256"), + ], +) +def test_eip712_paths_the_device_cannot_represent_are_reported(type_str: str, path: str) -> None: + out = ListOutputAdder() + + assert _convert_all(type_str, [{"path": path, "label": "V", "format": "raw"}], out=out) == [] + assert _errors(out) == ["Invalid EIP-712 path"] + + +@pytest.mark.parametrize("type_str", ["uint9", "uint", "int", "uint0", "uint264", "uint08", "bytes0", "bytes33"]) +def test_eip712_non_canonical_types_are_rejected(type_str: str) -> None: + out = ListOutputAdder() + + assert reconstruct_schema(f"Msg({type_str} value)", None, False, out) is None + assert _errors(out) == ["Unsupported EIP-712 type"] + + +def test_eip712_message_type_matching_the_domain_is_reused() -> None: + schema = reconstruct_schema( + "Msg(EIP712Domain d)EIP712Domain(string name)", ResolvedDomain(name="Test"), False, ListOutputAdder() + ) + + assert schema is not None + assert [struct.name for struct in schema.structs] == ["EIP712Domain", "Msg"] + + +def test_eip712_message_type_conflicting_with_the_domain_is_rejected() -> None: + out = ListOutputAdder() + + assert ( + reconstruct_schema("Msg(EIP712Domain d)EIP712Domain(string version)", ResolvedDomain(name="Test"), False, out) + is None + ) + assert _errors(out) == ["Conflicting EIP712Domain"] + + +def test_eip712_undefined_referenced_struct_is_rejected() -> None: + out = ListOutputAdder() + + assert reconstruct_schema("Msg(uint256 value,Missing other)", None, False, out) is None + assert _errors(out) == ["Unsupported EIP-712 type"] From fc83db6f359c88d0997b3fa21eb6b0ba5c4ce2de Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 26 Nov 2026 11:17:31 +0100 Subject: [PATCH 10/13] fix(BACK-12243): address the latest Copilot review findings - count EIP-712 deployments in the serve expansion limit - hash only the types referenced by the primary type - reject @.chainId, @.to and chain dependent formats the domain cannot serve - validate leaf and array slice bounds, and the number of values selected by a path - reject non canonical array sizes and bytesN widths - enforce the value tree depth and require referenced types to be defined in the format key - keep the overflow handling of the serve endpoint Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/erc7730/common/abi.py | 28 +++- .../convert_erc7730_v2_input_to_calldata.py | 57 ++++++-- .../convert/calldata/v1/eip712_path.py | 83 +++++++++--- .../convert/calldata/v1/eip712_schema.py | 54 +++++++- src/erc7730/serve/v2/compile.py | 12 +- tests/serve/v2/test_compile.py | 40 +++++- .../convert/calldata/test_convert_eip712.py | 125 +++++++++++++++++- 7 files changed, 358 insertions(+), 41 deletions(-) diff --git a/src/erc7730/common/abi.py b/src/erc7730/common/abi.py index 879fd823..df778c60 100644 --- a/src/erc7730/common/abi.py +++ b/src/erc7730/common/abi.py @@ -187,11 +187,30 @@ def parse_encode_type(encode_type: str) -> tuple[str, dict[str, list[tuple[str, return primary_type, types +def referenced_types(primary_type: str, types: dict[str, list[tuple[str, str]]]) -> set[str]: + """Names of the struct types reachable from a primary type, the primary type excluded. + + :param primary_type: the primary (root) struct type name + :param types: struct name -> ordered list of (type, name) field tuples + :return: the defined struct types the primary type refers to, directly or not + """ + reachable: set[str] = set() + pending = [primary_type] + while pending: + for field_type, _ in types.get(pending.pop(), []): + name = field_type.split("[", 1)[0] + if name in types and name != primary_type and name not in reachable: + reachable.add(name) + pending.append(name) + return reachable + + def to_encode_type(primary_type: str, types: dict[str, list[tuple[str, str]]]) -> str: """Build the canonical EIP-712 ``encodeType`` string for a primary type. - Per EIP-712, the primary type is encoded first, followed by all referenced struct types sorted alphabetically by - name. This is the inverse of :func:`parse_encode_type` and normalizes the ordering of the input. + Per EIP-712, the primary type is encoded first, followed by the struct types it references (directly or not), + sorted alphabetically by name. Types that are not referenced are not part of the encoding. This is the inverse of + :func:`parse_encode_type` and normalizes the ordering of the input. :param primary_type: the primary (root) struct type name :param types: struct name -> ordered list of (type, name) field tuples, including the primary type @@ -202,8 +221,9 @@ def to_encode_type(primary_type: str, types: dict[str, list[tuple[str, str]]]) - def encode_one(name: str) -> str: return f"{name}(" + ",".join(f"{typ} {field_name}" for typ, field_name in types[name]) + ")" - dependencies = sorted(name for name in types if name != primary_type) - return encode_one(primary_type) + "".join(encode_one(name) for name in dependencies) + return encode_one(primary_type) + "".join( + encode_one(name) for name in sorted(referenced_types(primary_type, types)) + ) class ABIDataType(StrEnum): diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index 18bca22e..1be459e4 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -1278,12 +1278,31 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal return None fields.extend(output_fields) - # the device refuses a descriptor reading the value of the container, which a typed message does not have - if any(_reads_container_value(field) for field in fields): + # the device refuses a descriptor reading the value of the container, which a typed message does not have, and one + # needing a chain or a contract the domain does not give + containers = _container_values(fields) + if CalldataDescriptorContainerPathValueV1.VALUE in containers: return out.error( title="Unsupported container path", message="@.value cannot be used in an EIP-712 message, the device refuses it.", ) + if CalldataDescriptorContainerPathValueV1.CHAIN_ID in containers and chain_id is None: + return out.error( + title="Missing chain id", + message="@.chainId is read, but the domain has no chain id: declare a deployment or set it in the domain.", + ) + if CalldataDescriptorContainerPathValueV1.TO in containers and address is None: + return out.error( + title="Missing contract", + message="@.to is read, but the domain has no verifying contract: declare a deployment or set it in the " + "domain.", + ) + if chain_id is None and (formats := _chain_dependent_formats(format.fields)): + return out.error( + title="Missing chain id", + message=f"The {', '.join(sorted(formats))} format needs the chain of the message, but the domain has no " + "chain id: declare a deployment or set it in the domain.", + ) hash = hashlib.sha3_256() for field in fields: @@ -1320,14 +1339,34 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal ) -def _reads_container_value(model: Any) -> bool: - """Whether a serialized instruction holds a CONTAINER path reading the VALUE of the container.""" +# formats the device resolves with the chain of the message +_CHAIN_DEPENDENT_FORMATS = ( + FieldFormat.AMOUNT, + FieldFormat.TOKEN_AMOUNT, + FieldFormat.TOKEN_TICKER, + FieldFormat.NFT_NAME, +) + + +def _chain_dependent_formats(fields: list[ResolvedFieldDescription | ResolvedFieldGroup]) -> set[str]: + """Formats of the fields (nested ones included) the device resolves with the chain of the message.""" + formats: set[str] = set() + for field in fields: + if isinstance(field, ResolvedFieldGroup): + formats |= _chain_dependent_formats(field.fields) + elif field.format in _CHAIN_DEPENDENT_FORMATS: + formats.add(str(field.format)) + return formats + + +def _container_values(model: Any) -> set[CalldataDescriptorContainerPathValueV1]: + """What a serialized instruction reads of the container: the values of its CONTAINER paths.""" match model: - case CalldataDescriptorContainerPathV1(value=CalldataDescriptorContainerPathValueV1.VALUE): - return True + case CalldataDescriptorContainerPathV1(value=value): + return {value} case BaseModel(): - return any(_reads_container_value(getattr(model, name)) for name in type(model).model_fields) + return set().union(*(_container_values(getattr(model, name)) for name in type(model).model_fields)) case list(): - return any(_reads_container_value(item) for item in model) + return set().union(*(_container_values(item) for item in model)) case _: - return False + return set() diff --git a/src/erc7730/convert/calldata/v1/eip712_path.py b/src/erc7730/convert/calldata/v1/eip712_path.py index da0902fd..af0bfeea 100644 --- a/src/erc7730/convert/calldata/v1/eip712_path.py +++ b/src/erc7730/convert/calldata/v1/eip712_path.py @@ -42,6 +42,7 @@ _MIN_BOUND = -32768 _MAX_BOUND = 32767 _MAX_FIELD_INDEX = 255 +_MAX_SELECTED_VALUES = 16 _SLICEABLE_LEAVES = ( CalldataDescriptorEIP712SolType.BYTES_FIX, @@ -55,14 +56,36 @@ def _unrepresentable_bound(*bounds: int | None) -> int | None: return next((bound for bound in bounds if bound is not None and not _MIN_BOUND <= bound <= _MAX_BOUND), None) -def _leaf_slice_width(parsed: ParsedSolidityType, start: int | None, end: int | None) -> int | None: - """Width in bytes of a slice of a leaf, only known when the leaf has a fixed size (``bytesN``), 0 if empty.""" - if parsed.sol_type != CalldataDescriptorEIP712SolType.BYTES_FIX or parsed.type_size is None: - return None - size = parsed.type_size - first = min(max((start or 0) + (size if start is not None and start < 0 else 0), 0), size) - last = size if end is None else min(max(end + (size if end < 0 else 0), 0), size) - return max(last - first, 0) +def _resolve_bound(bound: int | None, size: int, default: int) -> int: + """Resolve a bound against the size of what it slices: a negative bound counts back from the end.""" + if bound is None: + return default + return bound + size if bound < 0 else bound + + +def _is_inside(start: int | None, end: int | None, size: int) -> bool: + """Whether a slice reaches neither before nor past what it slices, an empty selection being valid.""" + return _resolve_bound(start, size, 0) >= 0 and 0 <= _resolve_bound(end, size, size) <= size + + +def _current_dimension(parsed: ParsedSolidityType | None, remaining_dims: int) -> int | None: + """Size of the array dimension a selector applies to (outermost first), None when it is dynamic.""" + return parsed.array_dimensions[remaining_dims - 1] if parsed is not None else None + + +def _is_empty_leaf_slice(start: int | None, end: int | None) -> bool: + """Whether a leaf slice selects no byte whatever the length of the leaf (which the device refuses).""" + first = 0 if start is None else start + return end is not None and (end == 0 or ((first < 0) == (end < 0) and end <= first)) + + +def _selected_count(dimension: int | None, start: int | None, end: int | None) -> int: + """Number of elements of an array dimension a slice selects at the least, whatever the array it is applied to.""" + if dimension is not None: + return max(_resolve_bound(end, dimension, dimension) - _resolve_bound(start, dimension, 0), 0) + if (start is None or start >= 0) and end is not None and end >= 0: + return max(end - (start or 0), 0) + return 0 def _leaf_type_family_size(parsed: ParsedSolidityType) -> tuple[CalldataDescriptorTypeFamily, int | None]: @@ -103,6 +126,8 @@ def convert_eip712_data_path( remaining_dims = 0 leaf_sliced = False slice_width: int | None = None + # values the path selects at the least, the device refuses a path that necessarily selects more than it holds + selected = 1 last_index = len(data_path.elements) - 1 for position, element in enumerate(data_path.elements): @@ -154,6 +179,7 @@ def convert_eip712_data_path( title="Invalid EIP-712 path", message="Array selector applied to a non-array value.", ) + selected *= _selected_count(_current_dimension(current_parsed, remaining_dims), None, None) elements.append(CalldataDescriptorEIP712PathElementArraySliceV1()) remaining_dims -= 1 @@ -163,8 +189,7 @@ def convert_eip712_data_path( title="Invalid EIP-712 path", message="Array index applied to a non-array value.", ) - # the dimension this selector applies to, outermost first - dimension = current_parsed.array_dimensions[remaining_dims - 1] if current_parsed else None + dimension = _current_dimension(current_parsed, remaining_dims) if dimension is not None and not -dimension <= array_index < dimension: return out.error( title="Invalid EIP-712 path", @@ -186,7 +211,7 @@ def convert_eip712_data_path( and current_parsed is not None and current_parsed.sol_type in _SLICEABLE_LEAVES ): - if start is not None and end is not None and start >= 0 and end >= 0 and end <= start: + if _is_empty_leaf_slice(start, end): return out.error( title="Invalid EIP-712 path", message=f"Leaf slice [{start}:{end}] is empty, the device refuses a slice with no byte.", @@ -196,12 +221,22 @@ def convert_eip712_data_path( title="Invalid EIP-712 path", message=f"Leaf slice [{start}:{end}] is not supported, the device cannot represent {bound}.", ) - slice_width = _leaf_slice_width(current_parsed, start, end) - if slice_width == 0: - return out.error( - title="Invalid EIP-712 path", - message=f"Leaf slice [{start}:{end}] is empty, the device refuses a slice with no byte.", - ) + if current_parsed.sol_type == CalldataDescriptorEIP712SolType.BYTES_FIX and current_parsed.type_size: + # the length of the leaf is known: the slice has to be inside it and keep a byte + size = current_parsed.type_size + first = _resolve_bound(start, size, 0) + last = _resolve_bound(end, size, size) + if first < 0 or last > size: + return out.error( + title="Invalid EIP-712 path", + message=f"Leaf slice [{start}:{end}] is not inside the {size} bytes of the leaf.", + ) + if last <= first: + return out.error( + title="Invalid EIP-712 path", + message=f"Leaf slice [{start}:{end}] is empty, the device refuses a slice with no byte.", + ) + slice_width = last - first elements.append(CalldataDescriptorEIP712PathElementLeafSliceV1(start=start, end=end)) leaf_sliced = True @@ -216,6 +251,13 @@ def convert_eip712_data_path( title="Invalid EIP-712 path", message=f"Array slice [{start}:{end}] is not supported, the device cannot represent {bound}.", ) + dimension = _current_dimension(current_parsed, remaining_dims) + if dimension is not None and not _is_inside(start, end, dimension): + return out.error( + title="Invalid EIP-712 path", + message=f"Array slice [{start}:{end}] is out of bounds for array of dimension {dimension}.", + ) + selected *= _selected_count(dimension, start, end) elements.append(CalldataDescriptorEIP712PathElementArraySliceV1(start=start, end=end)) remaining_dims -= 1 @@ -244,6 +286,13 @@ def convert_eip712_data_path( f"{MAX_EIP712_PATH_ELEMENTS}.", ) + if selected > _MAX_SELECTED_VALUES: + return out.error( + title="Invalid EIP-712 path", + message=f"EIP-712 path {data_path} selects at least {selected} values, the device accepts at most " + f"{_MAX_SELECTED_VALUES}.", + ) + type_family, type_size = _leaf_type_family_size(current_parsed) if leaf_sliced: # the size of a slice is not the size of the type it is cut from, it is only known for a fixed size leaf diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py index 73eb907a..cce11abd 100644 --- a/src/erc7730/convert/calldata/v1/eip712_schema.py +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -24,6 +24,9 @@ from erc7730.model.resolved.v2.context import ResolvedDeployment, ResolvedDomain from erc7730.model.types import HexStr +# depth of the value tree the device holds (doc/eip712.md#implementation-limits in app-ethereum) +MAX_VALUE_TREE_DEPTH = 16 + @dataclass(frozen=True) class ParsedSolidityType: @@ -107,6 +110,8 @@ def parse_solidity_type(type_str: str) -> ParsedSolidityType: while base.endswith("]"): open_index = base.rfind("[") inner = base[open_index + 1 : -1] + if inner and re.fullmatch(r"0|[1-9][0-9]*", inner) is None: + raise ValueError(f"{type_str} is not a valid type, the array size {inner} is not written canonically") dimensions.append(int(inner) if inner else None) base = base[:open_index] # collected outermost first, but the spec wants innermost first @@ -133,7 +138,7 @@ def parse_solidity_type(type_str: str) -> ParsedSolidityType: elif (match := re.fullmatch(r"bytes(\d+)", base)) is not None: sol_type = CalldataDescriptorEIP712SolType.BYTES_FIX type_size = int(match.group(1)) - if not 1 <= type_size <= 32: + if match.group(1) != str(type_size) or not 1 <= type_size <= 32: raise ValueError(f"{base} is not a valid type, bytesN is 1 to 32 bytes") else: # TODO fixed/ufixed Solidity types are not handled (rare in EIP-712); anything else is treated as a struct @@ -233,10 +238,14 @@ def reconstruct_schema( # a type outside the limits of the device is reported for this format only try: structs.extend(_build_struct(type_name, type_fields) for type_name, type_fields in types.items()) - for type_name, type_fields in types.items(): + # the types of the format key are the ones the primary type hash covers, the domain one cannot be assumed + for type_name, type_fields in raw_types.items(): for type_str, field_name in type_fields: - if (struct_name := parse_solidity_type(type_str).struct_name) is not None and struct_name not in types: + if ( + struct_name := parse_solidity_type(type_str).struct_name + ) is not None and struct_name not in raw_types: raise ValueError(f"{type_name}.{field_name} refers to the undefined struct {struct_name}") + _check_value_tree_depth(primary_type, types) except ValueError as e: return out.error( title="Unsupported EIP-712 type", @@ -255,6 +264,45 @@ def reconstruct_schema( ) +def _check_value_tree_depth(primary_type: str, types: dict[str, list[tuple[str, str]]]) -> None: + """ + Check the value tree of a message can be as shallow as the device accepts. + + The device holds a value tree of at most ``MAX_VALUE_TREE_DEPTH`` levels, struct instances and array dimensions + together, below the message. Only the levels every message has are counted: a dynamic array or a struct reached + through one can be empty. A struct holding itself without any such array has no finite value. + + :raises ValueError: if every message of the schema is deeper than the device accepts + """ + depths: dict[str, int] = {} + + def depth(struct: str, path: tuple[str, ...]) -> int: + if struct in depths: + return depths[struct] + if struct in path: + raise ValueError(f"{struct} holds itself, so no message of it is finite") + deepest = 0 + for type_str, _ in types[struct]: + parsed = parse_solidity_type(type_str) + levels = 0 + # outermost dimension first: each one is a level, and only a fixed non empty one guarantees the next + for dimension in reversed(parsed.array_dimensions): + levels += 1 + if not dimension: + break + else: + if parsed.struct_name is not None: + levels += 1 + depth(parsed.struct_name, (*path, struct)) + deepest = max(deepest, levels) + depths[struct] = deepest + return deepest + + if (levels := depth(primary_type, ())) > MAX_VALUE_TREE_DEPTH: + raise ValueError( + f"the message of {primary_type} is {levels} levels deep, the device accepts at most {MAX_VALUE_TREE_DEPTH}" + ) + + def compute_domain_separator( domain_fields: list[tuple[str, str]], domain: ResolvedDomain | None, diff --git a/src/erc7730/serve/v2/compile.py b/src/erc7730/serve/v2/compile.py index c0484e04..d4835191 100644 --- a/src/erc7730/serve/v2/compile.py +++ b/src/erc7730/serve/v2/compile.py @@ -7,7 +7,7 @@ from erc7730.common.output import ListOutputAdder, Output from erc7730.convert.calldata.convert_erc7730_v2_input_to_calldata import erc7730_v2_descriptor_to_calldata_descriptors from erc7730.model.calldata.descriptor import CalldataDescriptor -from erc7730.model.input.v2.context import InputContractContext +from erc7730.model.input.v2.context import InputContractContext, InputEIP712Context from erc7730.model.input.v2.descriptor import InputERC7730Descriptor from erc7730.serve.v2.model import Compiled, CompileResult, ConversionFailed, Diagnostic, InvalidDescriptor @@ -58,6 +58,8 @@ def compile_calldata(descriptor: InputERC7730Descriptor) -> CompileResult: # the TLV is only encoded during serialization, and only supports ASCII text try: payload = RootModel[list[CalldataDescriptor]](descriptors).model_dump(mode="json", exclude_none=True) + except OverflowError: + return InvalidDescriptor("calldata descriptors: a value is out of the range of the calldata TLV encoding") except UnicodeEncodeError as e: return InvalidDescriptor(f"calldata descriptors: ASCII text only, found {e.object[e.start : e.end]!r}") return Compiled(tuple(payload), diagnostics) @@ -66,7 +68,13 @@ def compile_calldata(descriptor: InputERC7730Descriptor) -> CompileResult: # per deployment, the converter rebuilds each format with every enum entry, and each field with its map lookups def _generated_items(descriptor: InputERC7730Descriptor) -> int: context = descriptor.context - deployments = len(context.contract.deployments) if isinstance(context, InputContractContext) else 0 + if isinstance(context, InputContractContext): + deployments = len(context.contract.deployments) + elif isinstance(context, InputEIP712Context): + # a descriptor without deployment is converted once, for the domain it declares + deployments = max(len(context.eip712.deployments or []), 1) + else: + deployments = 0 formats = descriptor.display.formats.values() fields = sum(_nodes(f.model_dump(by_alias=True, exclude_none=True), {"path", "$ref", "value"}) for f in formats) map_lookups = _nodes(descriptor.display.model_dump(by_alias=True, exclude_none=True), {"map"}) diff --git a/tests/serve/v2/test_compile.py b/tests/serve/v2/test_compile.py index 02527e50..6b31ad05 100644 --- a/tests/serve/v2/test_compile.py +++ b/tests/serve/v2/test_compile.py @@ -4,7 +4,7 @@ import pytest from erc7730.common import client -from erc7730.serve.v2.compile import compile_json +from erc7730.serve.v2.compile import MAX_GENERATED_ITEMS, compile_json from erc7730.serve.v2.model import Compiled, ConversionFailed, InvalidDescriptor from tests.files import TEST_RESOURCES from tests.io import load_json_file @@ -174,3 +174,41 @@ def test_compile_json_returns_conversion_errors() -> None: assert isinstance(result, ConversionFailed) assert [(d.level, d.title) for d in result.diagnostics] == [("error", "Invalid map key")] + + +def _eip712_descriptor(deployments: int) -> dict[str, Any]: + return { + "$schema": "specs/erc7730-v2.schema.json", + "context": { + "$id": "test", + "eip712": { + "deployments": [{"chainId": 1 + i, "address": "0x" + "00" * 19 + "01"} for i in range(deployments)], + "domain": {"name": "Test"}, + }, + }, + "metadata": {"owner": "Test Owner"}, + "display": { + "formats": {"Msg(uint256 v)": {"intent": "Test", "fields": [{"path": "v", "label": "V", "format": "raw"}]}} + }, + } + + +def test_compile_json_limits_the_items_generated_for_eip712_deployments() -> None: + result = compile_json(json.dumps(_eip712_descriptor(MAX_GENERATED_ITEMS)).encode()) + assert isinstance(result, InvalidDescriptor) + assert "descriptor too large" in result.message + + assert isinstance(compile_json(json.dumps(_eip712_descriptor(2)).encode()), Compiled) + + +def test_compile_json_rejects_a_value_out_of_the_range_of_the_tlv_encoding() -> None: + descriptor = _descriptor() + descriptor["metadata"] = { + **descriptor["metadata"], + "info": {"deploymentDate": "1960-01-01T00:00:00Z", "url": "https://example.com"}, + } + + result = compile_json(json.dumps(descriptor).encode()) + + assert isinstance(result, InvalidDescriptor) + assert "out of the range" in result.message diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 55fe87b2..57b28808 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -276,7 +276,7 @@ def test_eip712_domain_separator_with_salt_and_without_contract() -> None: out = ListOutputAdder() descriptor = _convert( PERMIT_TYPE, - [{"path": "value", "label": "Value", "format": "amount"}], + [{"path": "value", "label": "Value", "format": "raw"}], domain={"name": "Test", "salt": salt}, deployments=[], domain_separator=expected, @@ -291,7 +291,7 @@ def test_eip712_domain_separator_with_salt_and_without_contract() -> None: def test_eip712_descriptor_without_deployment_is_not_bound_to_a_chain() -> None: descriptor = _convert( PERMIT_TYPE, - [{"path": "value", "label": "Value", "format": "amount"}], + [{"path": "value", "label": "Value", "format": "raw"}], domain={"name": "Test"}, deployments=[], domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), @@ -387,9 +387,11 @@ def test_eip712_message_keyed_map_does_not_need_a_deployment() -> None: descriptor = _convert( PERMIT_TYPE, [_token_amount("#.nonce")], - domain={"name": "Test"}, + domain={"name": "Test", "chainId": 1}, deployments=[], - domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), + domain_separator=_domain_separator( + [("string", "name", keccak(text="Test")), ("uint256", "chainId", (1).to_bytes(32))] + ), maps={"tokens": {"0": TOKEN}}, out=out, ) @@ -514,6 +516,16 @@ def test_eip712_chain_filter_does_not_report_conflicts_of_other_chains() -> None ("Msg(bytes key)", "key.[0:32768]"), ("Msg(bytes32 key)", "key.[32:40]"), ("Msg(bytes32 key)", "key.[-1:0]"), + ("Msg(bytes key)", "key.[:0]"), + ("Msg(bytes key)", "key.[-1:0]"), + ("Msg(bytes32 key)", "key.[0:40]"), + ("Msg(bytes32 key)", "key.[-40:]"), + ("Batch(uint256[2] values)", "values.[0:3]"), + ("Batch(uint256[2] values)", "values.[-3:]"), + ("Msg(uint256[17] values)", "values.[]"), + ("Msg(uint256[17] values)", "values.[0:17]"), + ("Msg(uint256[] values)", "values.[0:17]"), + ("Msg(uint256[4][5] values)", "values.[].[]"), ("Msg(" + ",".join(f"uint8 f{i}" for i in range(257)) + ")", "f256"), ], ) @@ -524,7 +536,9 @@ def test_eip712_paths_the_device_cannot_represent_are_reported(type_str: str, pa assert _errors(out) == ["Invalid EIP-712 path"] -@pytest.mark.parametrize("type_str", ["uint9", "uint", "int", "uint0", "uint264", "uint08", "bytes0", "bytes33"]) +@pytest.mark.parametrize( + "type_str", ["uint9", "uint", "int", "uint0", "uint264", "uint08", "bytes0", "bytes33", "bytes04", "uint8[02]"] +) def test_eip712_non_canonical_types_are_rejected(type_str: str) -> None: out = ListOutputAdder() @@ -556,3 +570,104 @@ def test_eip712_undefined_referenced_struct_is_rejected() -> None: assert reconstruct_schema("Msg(uint256 value,Missing other)", None, False, out) is None assert _errors(out) == ["Unsupported EIP-712 type"] + + +def test_eip712_message_type_referring_to_the_domain_must_define_it() -> None: + out = ListOutputAdder() + + assert reconstruct_schema("Msg(EIP712Domain d)", ResolvedDomain(name="Test"), False, out) is None + assert _errors(out) == ["Unsupported EIP-712 type"] + + +def test_eip712_primary_type_hash_ignores_unreferenced_types() -> None: + schema = reconstruct_schema("Msg(uint256 v)Extra(uint256 x)", None, False, ListOutputAdder()) + + assert schema is not None + assert schema.primary_type_hash == "0x" + keccak(text="Msg(uint256 v)").hex() + + +def test_eip712_primary_type_hash_covers_transitively_referenced_types() -> None: + schema = reconstruct_schema("A(B[] b)C(uint256 c)B(C c)Z(uint256 z)", None, False, ListOutputAdder()) + + assert schema is not None + assert schema.primary_type_hash == "0x" + keccak(text="A(B[] b)B(C c)C(uint256 c)").hex() + + +@pytest.mark.parametrize( + "encode_type,valid", + [ + # 17 mandatory levels below the message + ("S0(S1 a)" + "".join(f"S{i}(S{i + 1} a)" for i in range(1, 17)) + "S17(uint8 v)", False), + ("S0(S1 a)" + "".join(f"S{i}(S{i + 1} a)" for i in range(1, 16)) + "S16(uint8 v)", True), + # array dimensions are levels too + ("S0(uint8[1][1][1][1][1][1][1][1] a,S1 b)S1(uint8[1][1][1][1][1][1][1][1] a,S2 b)S2(uint8 v)", True), + ("S0(S1[1][1][1][1][1][1][1][1] a)" + "".join(f"S{i}(S{i + 1} a)" for i in range(1, 9)) + "S9(uint8 v)", False), + ("S0(S1[1][1][1][1][1][1][1][1] a)" + "".join(f"S{i}(S{i + 1} a)" for i in range(1, 8)) + "S8(uint8 v)", True), + # a dynamic array can be empty, a struct holding itself through one has finite values + ("S0(S1[] a)S1(S1[] a)", True), + ("S0(S1 a)S1(S1 a)", False), + ], +) +def test_eip712_value_tree_depth(encode_type: str, valid: bool) -> None: + out = ListOutputAdder() + + assert (reconstruct_schema(encode_type, None, False, out) is not None) is valid + assert _errors(out) == ([] if valid else ["Unsupported EIP-712 type"]) + + +@pytest.mark.parametrize( + "type_str,path", + [ + ("Msg(uint256[16] values)", "values.[]"), + ("Msg(uint256[2] values)", "values.[2:]"), + ("Msg(uint256[2] values)", "values.[-2:]"), + ("Msg(uint256[2] values)", "values.[0:2]"), + ("Msg(uint256[] values)", "values.[]"), + ("Msg(uint256[] values)", "values.[0:16]"), + ("Msg(uint256[17] values)", "values.[3:5]"), + ("Msg(uint256[17] values)", "values.[-1]"), + ("Msg(bytes32 key)", "key.[0:32]"), + ("Msg(bytes32 key)", "key.[-4:]"), + ("Msg(bytes key)", "key.[-4:]"), + ("Msg(bytes key)", "key.[:4]"), + ], +) +def test_eip712_paths_the_device_accepts(type_str: str, path: str) -> None: + out = ListOutputAdder() + + assert len(_convert_all(type_str, [{"path": path, "label": "V", "format": "raw"}], out=out)) == 1 + assert not out.has_errors + + +def test_eip712_container_reads_need_the_chain_and_the_contract_of_the_domain() -> None: + fields = [{"path": "@.chainId", "label": "Chain", "format": "chainId"}, {"path": "@.to", "label": "To"}] + for field, error in zip(fields, ["Missing chain id", "Missing contract"], strict=True): + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [field], + domain={"name": "Test"}, + deployments=[], + domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), + out=out, + ) + assert descriptors == [] + assert _errors(out) == [error] + + assert len(_convert_all(PERMIT_TYPE, fields)) == 1 + + +@pytest.mark.parametrize("format", ["amount", "tokenAmount", "tokenTicker"]) +def test_eip712_chain_dependent_format_needs_the_chain_of_the_domain(format: str) -> None: + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": format}], + domain={"name": "Test"}, + deployments=[], + domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), + out=out, + ) + + assert descriptors == [] + assert _errors(out) == ["Missing chain id"] From f96ae666f9f9ce3149a7b8b115cb30b0998b2834 Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 26 Nov 2026 12:08:07 +0100 Subject: [PATCH 11/13] fix(BACK-12243): address the latest Copilot review findings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../convert_erc7730_v2_input_to_calldata.py | 3 +- .../convert/calldata/v1/eip712_schema.py | 27 +++++++++--- .../convert/calldata/test_convert_eip712.py | 43 +++++++++++++++++++ 3 files changed, 67 insertions(+), 6 deletions(-) diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index 1be459e4..56d1c85f 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -1345,6 +1345,7 @@ def convert_path(data_path: DataPath, out: OutputAdder) -> CalldataDescriptorVal FieldFormat.TOKEN_AMOUNT, FieldFormat.TOKEN_TICKER, FieldFormat.NFT_NAME, + FieldFormat.ADDRESS_NAME, ) @@ -1354,7 +1355,7 @@ def _chain_dependent_formats(fields: list[ResolvedFieldDescription | ResolvedFie for field in fields: if isinstance(field, ResolvedFieldGroup): formats |= _chain_dependent_formats(field.fields) - elif field.format in _CHAIN_DEPENDENT_FORMATS: + elif field.visible != "never" and field.format in _CHAIN_DEPENDENT_FORMATS: formats.add(str(field.format)) return formats diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py index cce11abd..fa6b1308 100644 --- a/src/erc7730/convert/calldata/v1/eip712_schema.py +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -276,11 +276,17 @@ def _check_value_tree_depth(primary_type: str, types: dict[str, list[tuple[str, """ depths: dict[str, int] = {} - def depth(struct: str, path: tuple[str, ...]) -> int: - if struct in depths: - return depths[struct] + def depth(struct: str, path: tuple[str, ...], parent_depth: int) -> int: if struct in path: raise ValueError(f"{struct} holds itself, so no message of it is finite") + if struct in depths: + deepest = depths[struct] + if parent_depth + deepest > MAX_VALUE_TREE_DEPTH: + raise ValueError( + f"the message of {primary_type} is more than {MAX_VALUE_TREE_DEPTH} levels deep, " + f"the device accepts at most {MAX_VALUE_TREE_DEPTH}" + ) + return deepest deepest = 0 for type_str, _ in types[struct]: parsed = parse_solidity_type(type_str) @@ -292,12 +298,23 @@ def depth(struct: str, path: tuple[str, ...]) -> int: break else: if parsed.struct_name is not None: - levels += 1 + depth(parsed.struct_name, (*path, struct)) + nested_depth = parent_depth + levels + 1 + if nested_depth > MAX_VALUE_TREE_DEPTH: + raise ValueError( + f"the message of {primary_type} is more than {MAX_VALUE_TREE_DEPTH} levels deep, " + f"the device accepts at most {MAX_VALUE_TREE_DEPTH}" + ) + levels += 1 + depth(parsed.struct_name, (*path, struct), nested_depth) + if parent_depth + levels > MAX_VALUE_TREE_DEPTH: + raise ValueError( + f"the message of {primary_type} is more than {MAX_VALUE_TREE_DEPTH} levels deep, " + f"the device accepts at most {MAX_VALUE_TREE_DEPTH}" + ) deepest = max(deepest, levels) depths[struct] = deepest return deepest - if (levels := depth(primary_type, ())) > MAX_VALUE_TREE_DEPTH: + if (levels := depth(primary_type, (), 0)) > MAX_VALUE_TREE_DEPTH: raise ValueError( f"the message of {primary_type} is {levels} levels deep, the device accepts at most {MAX_VALUE_TREE_DEPTH}" ) diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 57b28808..638af8c5 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -615,6 +615,14 @@ def test_eip712_value_tree_depth(encode_type: str, valid: bool) -> None: assert _errors(out) == ([] if valid else ["Unsupported EIP-712 type"]) +def test_eip712_value_tree_depth_stops_at_device_limit() -> None: + encode_type = "S0(S1 a)" + "".join(f"S{i}(S{i + 1} a)" for i in range(1, 1100)) + "S1100(uint8 v)" + out = ListOutputAdder() + + assert reconstruct_schema(encode_type, None, False, out) is None + assert _errors(out) == ["Unsupported EIP-712 type"] + + @pytest.mark.parametrize( "type_str,path", [ @@ -671,3 +679,38 @@ def test_eip712_chain_dependent_format_needs_the_chain_of_the_domain(format: str assert descriptors == [] assert _errors(out) == ["Missing chain id"] + + +def test_eip712_address_name_needs_the_chain_of_the_domain() -> None: + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [{"path": "owner", "label": "Owner", "format": "addressName", "params": {"types": ["wallet"]}}], + domain={"name": "Test"}, + deployments=[], + domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), + out=out, + ) + + assert descriptors == [] + assert _errors(out) == ["Missing chain id"] + + +def test_eip712_chain_dependent_formats_ignore_never_visible_nested_fields() -> None: + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [ + {"path": "owner", "label": "Owner", "format": "raw"}, + {"fields": [{"path": "value", "label": "Hidden", "format": "amount", "visible": "never"}]}, + ], + domain={"name": "Test"}, + deployments=[], + domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), + out=out, + ) + + assert len(descriptors) == 1 + assert isinstance(descriptors[0], CalldataDescriptorEIP712V1) + assert [field.name for field in descriptors[0].fields] == ["Owner"] + assert not out.has_errors From 586f6bd7de9f1cc92fd734756d45b4520d7dd29e Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 26 Nov 2026 12:28:26 +0100 Subject: [PATCH 12/13] fix(BACK-12243): address remaining Copilot review findings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/erc7730/common/abi.py | 7 ++- .../convert_erc7730_v2_input_to_calldata.py | 4 +- .../convert/calldata/v1/eip712_path.py | 23 +++++++- .../convert/calldata/v1/eip712_schema.py | 9 +++ src/erc7730/convert/calldata/v1/map.py | 3 +- src/erc7730/convert/calldata/v1/tlv.py | 16 ++++- src/erc7730/serve/v2/compile.py | 6 +- tests/common/test_abi.py | 7 +++ .../convert/calldata/test_convert_eip712.py | 58 ++++++++++++++++++- 9 files changed, 122 insertions(+), 11 deletions(-) diff --git a/src/erc7730/common/abi.py b/src/erc7730/common/abi.py index df778c60..e6b52f7d 100644 --- a/src/erc7730/common/abi.py +++ b/src/erc7730/common/abi.py @@ -153,6 +153,7 @@ def get_functions(abis: list[ABI], *, include_read_only: bool = False) -> Functi _ENCODE_TYPE_RE = re.compile(r"([\w:$]+)\(([^)]*)\)") +_ENCODE_TYPES_RE = re.compile(r"(?:[\w:$]+\([^)]*\))+") def parse_encode_type(encode_type: str) -> tuple[str, dict[str, list[tuple[str, str]]]]: @@ -166,14 +167,16 @@ def parse_encode_type(encode_type: str) -> tuple[str, dict[str, list[tuple[str, :return: a tuple of (primaryType, types) where types is a dict mapping type names to lists of (type, name) tuples :raises ValueError: if the string cannot be parsed """ - matches = _ENCODE_TYPE_RE.findall(encode_type) - if not matches: + if _ENCODE_TYPES_RE.fullmatch(encode_type) is None: raise ValueError(f"Invalid encodeType string: {encode_type}") + matches = _ENCODE_TYPE_RE.findall(encode_type) primary_type = matches[0][0] types: dict[str, list[tuple[str, str]]] = {} for type_name, fields_str in matches: + if type_name in types: + raise ValueError(f"Type '{type_name}' is defined more than once in encodeType '{encode_type}'") fields: list[tuple[str, str]] = [] if fields_str.strip(): for field in fields_str.split(","): diff --git a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py index 56d1c85f..4025ac1a 100644 --- a/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py +++ b/src/erc7730/convert/calldata/convert_erc7730_v2_input_to_calldata.py @@ -1018,12 +1018,14 @@ def _convert_resolved_value( selector_val = _convert_resolved_value(field.params.selector, ABIDataType.STRING) amount_val = _convert_resolved_value(field.params.amount, ABIDataType.UINT) spender_val = _convert_resolved_value(field.params.spender, ABIDataType.ADDRESS) + chain_id_val = _convert_resolved_value(field.params.chainId, ABIDataType.UINT) # an optional parameter that is set but fails to convert must reject the field, not be omitted if ( (field.params.selector is not None and selector_val is None) or (field.params.amount is not None and amount_val is None) or (field.params.spender is not None and spender_val is None) + or (field.params.chainId is not None and chain_id_val is None) ): return None @@ -1031,7 +1033,7 @@ def _convert_resolved_value( value=value, callee=callee, selector=selector_val, - chain_id=None, # v2 calldata parameters have no chain id + chain_id=chain_id_val, amount=amount_val, spender=spender_val, ) diff --git a/src/erc7730/convert/calldata/v1/eip712_path.py b/src/erc7730/convert/calldata/v1/eip712_path.py index af0bfeea..03fbd30e 100644 --- a/src/erc7730/convert/calldata/v1/eip712_path.py +++ b/src/erc7730/convert/calldata/v1/eip712_path.py @@ -43,6 +43,7 @@ _MAX_BOUND = 32767 _MAX_FIELD_INDEX = 255 _MAX_SELECTED_VALUES = 16 +_MAX_TYPE_SIZE = 255 _SLICEABLE_LEAVES = ( CalldataDescriptorEIP712SolType.BYTES_FIX, @@ -83,9 +84,22 @@ def _selected_count(dimension: int | None, start: int | None, end: int | None) - """Number of elements of an array dimension a slice selects at the least, whatever the array it is applied to.""" if dimension is not None: return max(_resolve_bound(end, dimension, dimension) - _resolve_bound(start, dimension, 0), 0) - if (start is None or start >= 0) and end is not None and end >= 0: - return max(end - (start or 0), 0) - return 0 + return _relative_width(start, end) or 0 + + +def _relative_width(start: int | None, end: int | None) -> int | None: + """ + Number of elements a slice selects of a sequence of unknown length, when its bounds determine it. + + Bounds counted from the same side (both from the start, or both from the end, an omitted end being the end of the + sequence) have a known distance, bounds of opposite sides depend on the length. + """ + first = 0 if start is None else start + if first >= 0 and end is not None and end >= 0: + return max(end - first, 0) + if first < 0 and (end is None or end < 0): + return max((0 if end is None else end) - first, 0) + return None def _leaf_type_family_size(parsed: ParsedSolidityType) -> tuple[CalldataDescriptorTypeFamily, int | None]: @@ -237,6 +251,9 @@ def convert_eip712_data_path( message=f"Leaf slice [{start}:{end}] is empty, the device refuses a slice with no byte.", ) slice_width = last - first + elif (width := _relative_width(start, end)) is not None and width <= _MAX_TYPE_SIZE: + # a valid slice of a dynamic leaf always holds this many bytes + slice_width = width elements.append(CalldataDescriptorEIP712PathElementLeafSliceV1(start=start, end=end)) leaf_sliced = True diff --git a/src/erc7730/convert/calldata/v1/eip712_schema.py b/src/erc7730/convert/calldata/v1/eip712_schema.py index fa6b1308..c459015d 100644 --- a/src/erc7730/convert/calldata/v1/eip712_schema.py +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -49,6 +49,9 @@ class ReconstructedSchema: structs: list[CalldataDescriptorEIP712StructV1] = field(default_factory=list) +_MAX_CHAIN_ID = 0x7FFFFFFFFFFFFFDB + + @dataclass(frozen=True) class EIP712DomainBinding: """Chain id and verifying contract of the domain of the messages, either of which may be unknown.""" @@ -74,6 +77,12 @@ def bind_domain( """ domain_chain_id = domain.chainId if domain is not None else None domain_address = domain.verifyingContract if domain is not None else None + for chain_id in (domain_chain_id, deployment.chainId if deployment is not None else None): + if chain_id is not None and not 0 <= chain_id <= _MAX_CHAIN_ID: + return out.error( + title="Invalid chain id", + message=f"The chain id {chain_id} is not one the device accepts (0 to {_MAX_CHAIN_ID}).", + ) if deployment is None: return EIP712DomainBinding(chain_id=domain_chain_id, address=domain_address) diff --git a/src/erc7730/convert/calldata/v1/map.py b/src/erc7730/convert/calldata/v1/map.py index 09f46a0e..dbb40b78 100644 --- a/src/erc7730/convert/calldata/v1/map.py +++ b/src/erc7730/convert/calldata/v1/map.py @@ -245,7 +245,8 @@ def _is_single_element( """Whether an array path element selects a single array element.""" match element.start, element.end: case int(start), int(end): - return end == start + 1 + # bounds of opposite signs are resolved against the array, so they cannot be told apart statically + return end == start + 1 and (start < 0) == (end < 0) case -1, None: return True case _: diff --git a/src/erc7730/convert/calldata/v1/tlv.py b/src/erc7730/convert/calldata/v1/tlv.py index b416bf49..bc1f119b 100644 --- a/src/erc7730/convert/calldata/v1/tlv.py +++ b/src/erc7730/convert/calldata/v1/tlv.py @@ -294,6 +294,18 @@ class CalldataDescriptorPathSliceElementTag(IntEnum): END = 0x02 +# the Ethereum app parses an OPERATION_INFO in its 16 KB heap +MAX_OPERATION_INFO_SIZE = 16384 + + +def _check_operation_info_size(out: bytes | bytearray) -> bytes | bytearray: + if len(out) >= MAX_OPERATION_INFO_SIZE: + raise OverflowError( + f"operation info of {len(out)} bytes does not fit the {MAX_OPERATION_INFO_SIZE} bytes limit" + ) + return out + + def _tlv_operation_info_body(obj: CalldataDescriptorInstructionTransactionInfoBaseV1) -> bytes: """ Encode the tags TRANSACTION_INFO and EIP712_MESSAGE_INFO have in common, which are all but the VERSION and the tags @@ -338,7 +350,7 @@ def tlv_transaction_info(obj: CalldataDescriptorInstructionTransactionInfoV1) -> out += tlv(CalldataDescriptorTransactionInfoTag.CONTRACT_ADDR, from_hex(obj.address)) out += tlv(CalldataDescriptorTransactionInfoTag.SELECTOR, from_hex(obj.selector)) out += _tlv_operation_info_body(obj) - return out + return _check_operation_info_size(out) def tlv_eip712_message_info(obj: CalldataDescriptorInstructionEIP712MessageInfoV1) -> bytes: @@ -356,7 +368,7 @@ def tlv_eip712_message_info(obj: CalldataDescriptorInstructionEIP712MessageInfoV out += _tlv_operation_info_body(obj) out += tlv(CalldataDescriptorTransactionInfoTag.DOMAIN_SEPARATOR, from_hex(obj.domain_separator)) out += tlv(CalldataDescriptorTransactionInfoTag.PRIMARY_TYPE_HASH, from_hex(obj.primary_type_hash)) - return out + return _check_operation_info_size(out) def tlv_eip712_schema(obj: CalldataDescriptorInstructionEIP712SchemaV1) -> bytes: diff --git a/src/erc7730/serve/v2/compile.py b/src/erc7730/serve/v2/compile.py index d4835191..1a022b62 100644 --- a/src/erc7730/serve/v2/compile.py +++ b/src/erc7730/serve/v2/compile.py @@ -80,7 +80,11 @@ def _generated_items(descriptor: InputERC7730Descriptor) -> int: map_lookups = _nodes(descriptor.display.model_dump(by_alias=True, exclude_none=True), {"map"}) enum_entries = sum(len(enum) for enum in (descriptor.metadata.enums or {}).values() if isinstance(enum, dict)) map_entries = sum(len(m.values) for m in (descriptor.metadata.maps or {}).values()) - return deployments * (len(formats) * (1 + enum_entries) + fields * (1 + map_lookups * map_entries)) + # an EIP-712 format key lists the members of the schema it is generated with, one per comma separated field + members = ( + sum(key.count(",") + 1 for key in descriptor.display.formats) if isinstance(context, InputEIP712Context) else 0 + ) + return deployments * (len(formats) * (1 + enum_entries) + members + fields * (1 + map_lookups * map_entries)) def _nodes(node: Any, keys: set[str]) -> int: diff --git a/tests/common/test_abi.py b/tests/common/test_abi.py index 26dde7b1..c6496757 100644 --- a/tests/common/test_abi.py +++ b/tests/common/test_abi.py @@ -2,6 +2,7 @@ from erc7730.common.abi import ( compute_signature, + parse_encode_type, reduce_signature, signature_to_selector, ) @@ -132,3 +133,9 @@ def test_signature_to_selector() -> None: signature = "transfer(address,uint256)" expected = "0xa9059cbb" assert signature_to_selector(signature) == expected + + +@pytest.mark.parametrize("encode_type", ["Msg(uint256 v)junk", "Msg(uint256 v)Msg(uint256 w)"]) +def test_parse_encode_type_rejects_trailing_junk_and_duplicates(encode_type: str) -> None: + with pytest.raises(ValueError): + parse_encode_type(encode_type) diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 638af8c5..8f1eac53 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -47,6 +47,7 @@ def _convert_all( domain_separator: str | None = None, maps: dict[str, Any] | None = None, out: OutputAdder | None = None, + all_chains: bool = False, ) -> list[CalldataDescriptor]: """Build a minimal EIP-712 v2 descriptor and return the converted calldata descriptors.""" descriptor = InputERC7730Descriptor.model_validate_json( @@ -72,7 +73,7 @@ def _convert_all( ) ) - return erc7730_v2_descriptor_to_calldata_descriptors(descriptor, chain_id=chain_id, out=out) + return erc7730_v2_descriptor_to_calldata_descriptors(descriptor, chain_id=None if all_chains else chain_id, out=out) def _convert(encode_type: str, fields: list[dict[str, Any]], **kwargs: Any) -> CalldataDescriptorEIP712V1: @@ -525,6 +526,8 @@ def test_eip712_chain_filter_does_not_report_conflicts_of_other_chains() -> None ("Msg(uint256[17] values)", "values.[]"), ("Msg(uint256[17] values)", "values.[0:17]"), ("Msg(uint256[] values)", "values.[0:17]"), + ("Msg(uint256[] values)", "values.[-17:]"), + ("Msg(uint256[] values)", "values.[-18:-1]"), ("Msg(uint256[4][5] values)", "values.[].[]"), ("Msg(" + ",".join(f"uint8 f{i}" for i in range(257)) + ")", "f256"), ], @@ -714,3 +717,56 @@ def test_eip712_chain_dependent_formats_ignore_never_visible_nested_fields() -> assert isinstance(descriptors[0], CalldataDescriptorEIP712V1) assert [field.name for field in descriptors[0].fields] == ["Owner"] assert not out.has_errors + + +@pytest.mark.parametrize(("path", "width"), [("key.[:4]", 4), ("key.[-4:]", 4), ("key.[2:6]", 4), ("key.[-6:-2]", 4)]) +def test_eip712_leaf_slice_of_a_dynamic_leaf_has_a_derived_width(path: str, width: int) -> None: + descriptor = _convert("Msg(bytes key)", [{"path": path, "label": "K", "format": "raw"}]) + + value = descriptor.fields[0].param.value + assert isinstance(value, CalldataDescriptorValuePathV1) + assert value.type_size == width + + +@pytest.mark.parametrize("chain_id", [0x7FFFFFFFFFFFFFDC, 2**64]) +def test_eip712_out_of_range_chain_id_is_rejected_but_other_deployments_are_kept(chain_id: int) -> None: + out = ListOutputAdder() + descriptors = _convert_all( + PERMIT_TYPE, + [{"path": "value", "label": "Value", "format": "amount"}], + deployments=[{"chainId": chain_id, "address": DEFAULT_ADDRESS}, {"chainId": 1, "address": DEFAULT_ADDRESS}], + out=out, + all_chains=True, + ) + + assert len(descriptors) == 1 + assert _errors(out) == ["Invalid chain id"] + + +def test_eip712_map_key_slice_crossing_the_end_is_rejected() -> None: + out = ListOutputAdder() + + _convert_all( + "Msg(bytes ks)", + [{"path": "ks.[-1:0]", "label": "K", "format": "raw"}], + out=out, + ) + + assert not out.has_errors or _errors(out) # slice is not a single element: no crash + + +def test_eip712_oversized_operation_info_overflows() -> None: + descriptor = InputERC7730Descriptor.model_validate_json( + json.dumps( + { + "$schema": "specs/erc7730-v2.schema.json", + "context": {"$id": "test", "eip712": {"deployments": [{"chainId": 1, "address": DEFAULT_ADDRESS}]}}, + "metadata": {"owner": "A" * 16384}, + "display": {"formats": {PERMIT_TYPE: {"intent": "I", "fields": [{"path": "value", "label": "V"}]}}}, + } + ) + ) + descriptors = erc7730_v2_descriptor_to_calldata_descriptors(descriptor, out=ListOutputAdder()) + + with pytest.raises(OverflowError): + descriptors[0].model_dump(mode="json") From 84bc5966fff01064629e4866967d44de8c968bb8 Mon Sep 17 00:00:00 2001 From: Frederic Samier Date: Thu, 26 Nov 2026 13:29:21 +0100 Subject: [PATCH 13/13] test(BACK-12243): exercise the opposite-sign map key slice with a real map lookup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/v2/convert/calldata/test_convert_eip712.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/v2/convert/calldata/test_convert_eip712.py b/tests/v2/convert/calldata/test_convert_eip712.py index 8f1eac53..4b3eabca 100644 --- a/tests/v2/convert/calldata/test_convert_eip712.py +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -746,13 +746,15 @@ def test_eip712_out_of_range_chain_id_is_rejected_but_other_deployments_are_kept def test_eip712_map_key_slice_crossing_the_end_is_rejected() -> None: out = ListOutputAdder() - _convert_all( - "Msg(bytes ks)", - [{"path": "ks.[-1:0]", "label": "K", "format": "raw"}], + descriptors = _convert_all( + "Msg(uint256[] ids,uint256 value)", + [_token_amount("#.ids.[-1:0]")], + maps={"tokens": {"0": TOKEN}}, out=out, ) - assert not out.has_errors or _errors(out) # slice is not a single element: no crash + assert descriptors == [] + assert "Unsupported map key" in _errors(out) def test_eip712_oversized_operation_info_overflows() -> None: