diff --git a/src/erc7730/common/abi.py b/src/erc7730/common/abi.py index 1c496725..e6b52f7d 100644 --- a/src/erc7730/common/abi.py +++ b/src/erc7730/common/abi.py @@ -152,7 +152,8 @@ 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:$]+)\(([^)]*)\)") +_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(","): @@ -187,6 +190,45 @@ 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 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 + :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]) + ")" + + return encode_one(primary_type) + "".join( + encode_one(name) for name in sorted(referenced_types(primary_type, types)) + ) + + class ABIDataType(StrEnum): """Solidity data type.""" 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/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..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 @@ -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 ( @@ -21,27 +22,41 @@ 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.convert.calldata.v1.abi import ABITree, function_to_abi_tree +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 ( + 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 ( + DataPathConverter, convert_container_path, convert_data_path, ) 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, + 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, ) @@ -62,7 +77,10 @@ CalldataDescriptorParamV1, ) from erc7730.model.calldata.v1.value import ( + CalldataDescriptorContainerPathV1, + CalldataDescriptorContainerPathValueV1, CalldataDescriptorDataPathV1, + CalldataDescriptorEIP712PathV1, CalldataDescriptorPathElementLeafV1, CalldataDescriptorPathLeafType, CalldataDescriptorTypeFamily, @@ -71,7 +89,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 +98,8 @@ from erc7730.model.resolved.v2.context import ( ResolvedContractContext, ResolvedDeployment, + ResolvedDomain, + ResolvedEIP712Context, ) from erc7730.model.resolved.v2.descriptor import ResolvedERC7730Descriptor from erc7730.model.resolved.v2.display import ( @@ -100,6 +120,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. @@ -139,6 +162,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 +262,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 @@ -248,15 +277,16 @@ def _convert_v2_selector( else None ) - # 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.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: 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 +325,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 +343,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 +375,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 @@ -382,16 +414,27 @@ 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) ] 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) @@ -403,6 +446,47 @@ 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; 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: + 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. @@ -613,7 +697,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 +709,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 +725,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 +779,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 +790,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,11 +798,19 @@ 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: - return deployment_map_key(value_map.keyPath, maps.deployment.chainId, maps.deployment.address) + # 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 {key_path}, which the descriptor does not declare.", + ) + 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: @@ -738,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 @@ -747,7 +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 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 """ @@ -766,13 +860,15 @@ 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 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 maps.map_ref(resolved_value, abi_type, abi, out) + return None 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: @@ -827,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))] @@ -920,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 @@ -933,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, ) @@ -1001,3 +1101,275 @@ 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 and context.eip712.deployments: + 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] = [] + + # 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: + # 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 + + 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: + continue + + descriptor = _convert_eip712_message( + descriptor=resolved_descriptor, + binding=binding, + domain=domain, + domain_separator=resolved_context.eip712.domainSeparator, + 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, + binding: EIP712DomainBinding, + domain: ResolvedDomain | None, + domain_separator: str | None, + 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 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) + :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: + # 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") + if descriptor.metadata.info.deploymentDate + else None + ) + + 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 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) + 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()) + 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.", + ) + 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( + 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( + chain_id, address, 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=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, 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: + hash.update(from_hex(field.descriptor)) + + schema_info = CalldataDescriptorInstructionEIP712SchemaV1(structs=schema.structs) + + message_info = CalldataDescriptorInstructionEIP712MessageInfoV1( + chain_id=chain_id, + address=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] + 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=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, + message_info=message_info, + enums=enums, + maps=maps.entries, + fields=fields, + ) + + +# formats the device resolves with the chain of the message +_CHAIN_DEPENDENT_FORMATS = ( + FieldFormat.AMOUNT, + FieldFormat.TOKEN_AMOUNT, + FieldFormat.TOKEN_TICKER, + FieldFormat.NFT_NAME, + FieldFormat.ADDRESS_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.visible != "never" and 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=value): + return {value} + case BaseModel(): + return set().union(*(_container_values(getattr(model, name)) for name in type(model).model_fields)) + case list(): + return set().union(*(_container_values(item) for item in model)) + case _: + return set() 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..03fbd30e --- /dev/null +++ b/src/erc7730/convert/calldata/v1/eip712_path.py @@ -0,0 +1,323 @@ +""" +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 ( + MAX_EIP712_PATH_ELEMENTS, + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementLeafSliceV1, + 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, +} + + +# leaf types a leaf slice applies to +_MIN_BOUND = -32768 +_MAX_BOUND = 32767 +_MAX_FIELD_INDEX = 255 +_MAX_SELECTED_VALUES = 16 +_MAX_TYPE_SIZE = 255 + +_SLICEABLE_LEAVES = ( + CalldataDescriptorEIP712SolType.BYTES_FIX, + CalldataDescriptorEIP712SolType.BYTES_DYN, + CalldataDescriptorEIP712SolType.STRING, +) + + +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 _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) + 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]: + """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 + 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): + 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}".', + ) + + 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) + + case Array(): + if remaining_dims <= 0: + return out.error( + 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 + + 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.", + ) + 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", + 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 + 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 + + 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 _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.", + ) + 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}.", + ) + 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 + 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 + + 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.", + ) + 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}.", + ) + 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 + + 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.', + ) + + 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}.", + ) + + 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 + type_size = slice_width + + 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..c459015d --- /dev/null +++ b/src/erc7730/convert/calldata/v1/eip712_schema.py @@ -0,0 +1,387 @@ +""" +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.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 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: + """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) + + +_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.""" + + 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 + 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) + + 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 _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. + + :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] + 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 + 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 = _integer_size(base, match.group(1)) + elif (match := re.fullmatch(r"int(\d*)", base)) is not None: + sol_type = CalldataDescriptorEIP712SolType.INT + type_size = _integer_size(base, match.group(1)) + 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)) + 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 + 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}", + ) + + domain_fields = reconstruct_domain_fields(domain, has_deployments) + + # 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.extend(_build_struct(type_name, type_fields) 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 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", + 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 + 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, + ) + + +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, ...], 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) + 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: + 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, (), 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}" + ) + + +def compute_domain_separator( + domain_fields: list[tuple[str, str]], + domain: ResolvedDomain | None, + binding: EIP712DomainBinding, + out: OutputAdder, +) -> HexStr | None: + """ + Compute the domain separator, ``hashStruct(domain)``, of the messages of one deployment. + + :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_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": + if binding.chain_id is None: + _missing_domain_value(name, out) + return None + encoded += binding.chain_id.to_bytes(32) + case "verifyingContract": + if binding.address is None: + _missing_domain_value(name, out) + return None + encoded += from_hex(binding.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()) + + +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 3d78f6ab..9b27ca82 100644 --- a/src/erc7730/convert/calldata/v1/enum.py +++ b/src/erc7730/convert/calldata/v1/enum.py @@ -6,8 +6,7 @@ CalldataDescriptorInstructionEnumValueV1, ) 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 +30,22 @@ def enum_ordinal(ordinal: str) -> int: def convert_enums( - deployment: ResolvedDeployment, selector: Selector, enums: dict[Id, EnumDefinition] | None + chain_id: int | None, + address: str | None, + 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 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) + @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: @@ -44,9 +53,11 @@ def convert_enums( return [ CalldataDescriptorInstructionEnumValueV1( - chain_id=deployment.chainId, - address=deployment.address, + chain_id=chain_id, + address=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 ea4136cd..dbb40b78 100644 --- a/src/erc7730/convert/calldata/v1/map.py +++ b/src/erc7730/convert/calldata/v1/map.py @@ -9,23 +9,27 @@ - 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 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 ( CalldataDescriptorContainerPathV1, CalldataDescriptorContainerPathValueV1, CalldataDescriptorDataPathV1, + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathV1, CalldataDescriptorMapRefV1, CalldataDescriptorPathElementArrayV1, CalldataDescriptorPathElementLeafV1, @@ -36,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 @@ -61,16 +64,27 @@ 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 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 in one field and as strings in another) gets one id per encoding. """ - def __init__(self, deployment: ResolvedDeployment, selector: Selector) -> None: - self.deployment = deployment + def __init__( + self, + chain_id: int | None, + address: str | None, + selector: Selector | None = None, + domain_separator: HexStr | None = None, + primary_type_hash: HexStr | None = None, + ) -> None: + self.chain_id = chain_id + self.address = address 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] = {} @@ -78,7 +92,7 @@ def map_ref( self, value_map: ResolvedValueMap, abi_type: ABIDataType, - abi: ABITree, + convert_path: DataPathConverter, out: OutputAdder, ) -> CalldataDescriptorValueMapRefV1 | None: """ @@ -86,13 +100,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 @@ -119,9 +133,11 @@ 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.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, map=map_name, id=map_id, key_source=key_source, @@ -142,20 +158,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 +204,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,13 +212,22 @@ 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 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} 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 " @@ -214,11 +239,14 @@ 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): - 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 _: @@ -278,10 +306,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/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/selector.py b/src/erc7730/convert/calldata/v1/selector.py index dda3ab40..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, selector, descriptor.metadata.enums) + 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/convert/calldata/v1/tlv.py b/src/erc7730/convert/calldata/v1/tlv.py index 672220c6..bc1f119b 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 ( @@ -36,6 +43,11 @@ from erc7730.model.calldata.v1.value import ( CalldataDescriptorContainerPathV1, CalldataDescriptorDataPathV1, + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementLeafSliceV1, + CalldataDescriptorEIP712PathElementStructFieldV1, + CalldataDescriptorEIP712PathElementV1, + CalldataDescriptorEIP712PathV1, CalldataDescriptorMapRefV1, CalldataDescriptorPathElementArrayV1, CalldataDescriptorPathElementLeafV1, @@ -52,6 +64,8 @@ @pydantic_enum_by_name class CalldataDescriptorTransactionInfoTag(IntEnum): + # 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 @@ -63,9 +77,54 @@ 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 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 + EIP712_LEAF_SLICE = 0x03 + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712ArraySliceTag(IntEnum): + START = 0x01 + END = 0x02 + + +@pydantic_enum_by_name +class CalldataDescriptorEIP712LeafSliceTag(IntEnum): + START = 0x01 + END = 0x02 + + @pydantic_enum_by_name class CalldataDescriptorEnumValueTag(IntEnum): VERSION = 0x00 @@ -75,6 +134,8 @@ class CalldataDescriptorEnumValueTag(IntEnum): ID = 0x04 VALUE = 0x05 NAME = 0x06 + DOMAIN_SEPARATOR = 0x07 + PRIMARY_TYPE_HASH = 0x08 @pydantic_enum_by_name @@ -86,6 +147,8 @@ class CalldataDescriptorMapEntryTag(IntEnum): ID = 0x04 KEY = 0x05 VALUE = 0x06 + DOMAIN_SEPARATOR = 0x07 + PRIMARY_TYPE_HASH = 0x08 SIGNATURE = 0xFF @@ -231,18 +294,27 @@ class CalldataDescriptorPathSliceElementTag(IntEnum): END = 0x02 -def tlv_transaction_info(obj: CalldataDescriptorInstructionTransactionInfoV1) -> bytes: +# 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 a struct of type TRANSACTION_INFO. + 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 - @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(CalldataDescriptorTransactionInfoTag.SELECTOR, from_hex(obj.selector)) out += tlv(CalldataDescriptorTransactionInfoTag.FIELDS_HASH, from_hex(obj.hash)) out += tlv(CalldataDescriptorTransactionInfoTag.OPERATION_TYPE, obj.operation_type) @@ -265,6 +337,121 @@ 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 + """ + 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 _check_operation_info_size(out) + + +def tlv_eip712_message_info(obj: CalldataDescriptorInstructionEIP712MessageInfoV1) -> bytes: + """ + Encode a struct of type EIP712_MESSAGE_INFO (without its signature, which is computed by CAL). + + 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 + """ + 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 _check_operation_info_size(out) + + +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, (1).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, (1).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: + # 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)) + + if (struct_name := obj.struct_name) is not None: + out += tlv(CalldataDescriptorEIP712FieldTag.STRUCT_NAME, struct_name) + + 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: + 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)) + 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. @@ -274,9 +461,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) @@ -292,9 +477,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)) @@ -610,6 +793,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 +870,42 @@ 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 (a struct field index, an array slice or a leaf 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 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.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..b70667ac --- /dev/null +++ b/src/erc7730/lint/v2/lint_validate_eip712_domain_separator.py @@ -0,0 +1,75 @@ +""" +V2 linter that validates the ``domainSeparator`` of an EIP-712 context against the domain of the descriptor. + +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 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 +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. + """ + + @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 + + 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(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] + matching = [separator for separator in known if from_hex(separator) == declared_bytes] + + 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)) 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(matching) < len(computed): + out.warning( + title="Domain separator shared by several deployments", + 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 b64573f0..664e62b1 100644 --- a/src/erc7730/lint/v2/lint_validate_map_keys.py +++ b/src/erc7730/lint/v2/lint_validate_map_keys.py @@ -5,15 +5,21 @@ 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.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 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 ( @@ -30,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 @@ -39,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(): @@ -51,7 +67,7 @@ def lint( # only built when needed: some ABI types (fixed point numbers) cannot be converted to a tree abi_tree = function_to_abi_tree(abi) for value_map in value_maps: - encode_map_keys(value_map, abi_tree, out) + encode_map_keys(value_map, _path_converter(abi_tree), out) case _: assert_never(descriptor.context) @@ -71,3 +87,19 @@ 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 _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) + + return convert_path diff --git a/src/erc7730/model/calldata/__init__.py b/src/erc7730/model/calldata/__init__.py index 044da652..b4e3ef65 100644 --- a/src/erc7730/model/calldata/__init__.py +++ b/src/erc7730/model/calldata/__init__.py @@ -9,13 +9,11 @@ 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 class CalldataDescriptorVersion(StrEnum): @@ -26,42 +24,15 @@ 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 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", 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.", - ) - - 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..9c0cc5ed 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 Address, HexStr, Id, Selector class CalldataDescriptorV1(CalldataDescriptorBase): @@ -22,6 +27,33 @@ 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).", + ) + + 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.", + ) + version: Literal["v1"] = Field( default="v1", title="Descriptor type version", @@ -50,3 +82,87 @@ 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)", + ) + + 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.", + 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=66, + 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.", + ) + + 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 new file mode 100644 index 00000000..d3bde631 --- /dev/null +++ b/src/erc7730/model/calldata/v1/eip712.py @@ -0,0 +1,153 @@ +""" +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, Self + +from pydantic import Field, computed_field, model_validator + +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 + + +# 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).""" + + 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.", + ) + + @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).""" + + 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.", + ) + + @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).""" + + 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.", + 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: + 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..ad851f3e 100644 --- a/src/erc7730/model/calldata/v1/instruction.py +++ b/src/erc7730/model/calldata/v1/instruction.py @@ -64,34 +64,44 @@ class CalldataDescriptorFieldVisibilityV1(IntEnum): IF_NOT_IN = 0x02 +def _validate_operation_context( + 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: + 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.""" -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 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( default=1, title="Struct version", - description="Version of 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.", + description="Version of the struct", ) hash: str = Field( @@ -147,6 +157,26 @@ class CalldataDescriptorInstructionTransactionInfoV1(CalldataDescriptorInstructi description="Displayed in review first screens", ) + +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.", + ) + @computed_field(title="Descriptor", description="Hex encoded TRANSACTION_INFO TLV struct") # type: ignore[misc] @cached_property def descriptor(self) -> CalldataDescriptorInstructionHex: @@ -157,6 +187,53 @@ def descriptor(self) -> CalldataDescriptorInstructionHex: return tlv_transaction_info(self).hex() +class CalldataDescriptorInstructionEIP712MessageInfoV1(CalldataDescriptorInstructionTransactionInfoBaseV1): + """ + Instruction descriptor for the EIP712_MESSAGE_INFO struct. + + 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. + """ + + 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.", + 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=66, + 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.""" @@ -166,22 +243,49 @@ 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 = 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=66, + 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=66, + max_length=66, + ) + + @model_validator(mode="after") + def _validate_context(self) -> Self: + _validate_operation_context( + self.selector, self.chain_id, self.address, 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)", @@ -230,22 +334,49 @@ 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 = 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=66, + 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=66, + max_length=66, + ) + + @model_validator(mode="after") + def _validate_context(self) -> Self: + _validate_operation_context( + self.selector, self.chain_id, self.address, 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 26be1370..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): @@ -224,11 +227,136 @@ 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, + ) + + +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 + | CalldataDescriptorEIP712PathElementLeafSliceV1, + 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, " + "optionally followed by a leaf slice", + min_length=1, + 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, + 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/src/erc7730/serve/v2/compile.py b/src/erc7730/serve/v2/compile.py index cee55e2f..1a022b62 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 @@ -55,11 +55,11 @@ 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") + 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) @@ -68,13 +68,23 @@ 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"}) 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/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) 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..bcef8664 --- /dev/null +++ b/tests/convert/calldata/test_convert_registry_files.py @@ -0,0 +1,32 @@ +from pathlib import Path + +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, +) +from erc7730.model.input.v2.descriptor import InputERC7730Descriptor +from tests.cases import path_id +from tests.files import ERC7730_EIP712_DESCRIPTORS, ERC7730_EXPECTED_CALLDATA_FAILURES + +pytestmark = pytest.mark.integration + + +@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 EIP-712 files (also exercises resolution). + """ + if path_id(input_file) in ERC7730_EXPECTED_CALLDATA_FAILURES: + request.applymarker(pytest.mark.xfail(strict=True, reason="unsupported by the calldata converter")) + + 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: + assert descriptor.model_dump_json() diff --git a/tests/files.py b/tests/files.py index 626b423f..456e8a09 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,24 @@ def _is_registry_descriptor(path: Path) -> bool: ] ) ERC7730_DESCRIPTORS = sorted(ERC7730_CALLDATA_DESCRIPTORS + ERC7730_EIP712_DESCRIPTORS) + +# 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", + "ophis/eip712-Ophis-GPv2Settlement.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) diff --git a/tests/serve/v2/test_compile.py b/tests/serve/v2/test_compile.py index f2fe1d47..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 @@ -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: @@ -176,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 new file mode 100644 index 00000000..4b3eabca --- /dev/null +++ b/tests/v2/convert/calldata/test_convert_eip712.py @@ -0,0 +1,774 @@ +import json +from typing import Any + +import pytest +from eth_utils import keccak + +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 ( + CalldataDescriptorEIP712PathElementArraySliceV1, + CalldataDescriptorEIP712PathElementLeafSliceV1, + CalldataDescriptorEIP712PathElementStructFieldV1, + CalldataDescriptorEIP712PathV1, + CalldataDescriptorValuePathV1, +) +from erc7730.model.input.v2.descriptor import InputERC7730Descriptor +from erc7730.model.resolved.v2.context import ResolvedDomain + +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_all( + encode_type: str, + fields: list[dict[str, Any]], + *, + 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, + 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( + json.dumps( + { + "$schema": "specs/erc7730-v2.schema.json", + "context": { + "$id": "test", + "eip712": { + "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", + **({"maps": {name: {"values": values} for name, values in maps.items()}} if maps else {}), + }, + "display": {"formats": {encode_type: {"intent": "Test intent", "fields": fields}}}, + } + ) + ) + + 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: + """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) + 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" + + +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" + + +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": "raw"}], + 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": "raw"}], + domain={"name": "Test"}, + deployments=[], + domain_separator=_domain_separator([("string", "name", keccak(text="Test"))]), + 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_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"}], + domain_separator=expected, + out=out, + ) + + 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", "chainId": 1}, + deployments=[], + domain_separator=_domain_separator( + [("string", "name", keccak(text="Test")), ("uint256", "chainId", (1).to_bytes(32))] + ), + 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] + + +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(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[] 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"), + ], +) +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", "bytes04", "uint8[02]"] +) +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"] + + +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"]) + + +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", + [ + ("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"] + + +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 + + +@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() + + descriptors = _convert_all( + "Msg(uint256[] ids,uint256 value)", + [_token_amount("#.ids.[-1:0]")], + maps={"tokens": {"0": TOKEN}}, + out=out, + ) + + assert descriptors == [] + assert "Unsupported map key" in _errors(out) + + +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") 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: 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..215295c8 --- /dev/null +++ b/tests/v2/lint/test_lint_validate_eip712_domain_separator.py @@ -0,0 +1,117 @@ +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_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) == []