ERC7739Utils.sol 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {Calldata} from "../Calldata.sol";
  4. /**
  5. * @dev Utilities to process https://ercs.ethereum.org/ERCS/erc-7739[ERC-7739] typed data signatures
  6. * that are specific to an EIP-712 domain.
  7. *
  8. * This library provides methods to wrap, unwrap and operate over typed data signatures with a defensive
  9. * rehashing mechanism that includes the app's xref:api:utils/cryptography#EIP712-_domainSeparatorV4[EIP-712]
  10. * and preserves readability of the signed content using an EIP-712 nested approach.
  11. *
  12. * A smart contract domain can validate a signature for a typed data structure in two ways:
  13. *
  14. * - As an application validating a typed data signature. See {typedDataSignStructHash}.
  15. * - As a smart contract validating a raw message signature. See {personalSignStructHash}.
  16. *
  17. * NOTE: A provider for a smart contract wallet would need to return this signature as the
  18. * result of a call to `personal_sign` or `eth_signTypedData`, and this may be unsupported by
  19. * API clients that expect a return value of 129 bytes, or specifically the `r,s,v` parameters
  20. * of an xref:api:utils/cryptography#ECDSA[ECDSA] signature, as is for example specified for
  21. * xref:api:utils/cryptography#EIP712[EIP-712].
  22. */
  23. library ERC7739Utils {
  24. /**
  25. * @dev An EIP-712 type to represent "personal" signatures
  26. * (i.e. mimic of `personal_sign` for smart contracts).
  27. */
  28. bytes32 private constant PERSONAL_SIGN_TYPEHASH = keccak256("PersonalSign(bytes prefixed)");
  29. /**
  30. * @dev Nest a signature for a given EIP-712 type into a nested signature for the domain of the app.
  31. *
  32. * Counterpart of {decodeTypedDataSig} to extract the original signature and the nested components.
  33. */
  34. function encodeTypedDataSig(
  35. bytes memory signature,
  36. bytes32 appSeparator,
  37. bytes32 contentsHash,
  38. string memory contentsDescr
  39. ) internal pure returns (bytes memory) {
  40. return
  41. abi.encodePacked(signature, appSeparator, contentsHash, contentsDescr, uint16(bytes(contentsDescr).length));
  42. }
  43. /**
  44. * @dev Parses a nested signature into its components.
  45. *
  46. * Constructed as follows:
  47. *
  48. * `signature ‖ APP_DOMAIN_SEPARATOR ‖ contentsHash ‖ contentsDescr ‖ uint16(contentsDescr.length)`
  49. *
  50. * - `signature` is the signature for the (ERC-7739) nested struct hash. This signature indirectly signs over the
  51. * original "contents" hash (from the app) and the account's domain separator.
  52. * - `APP_DOMAIN_SEPARATOR` is the EIP-712 {EIP712-_domainSeparatorV4} of the application smart contract that is
  53. * requesting the signature verification (though ERC-1271).
  54. * - `contentsHash` is the hash of the underlying data structure or message.
  55. * - `contentsDescr` is a descriptor of the "contents" part of the the EIP-712 type of the nested signature.
  56. *
  57. * NOTE: This function returns empty if the input format is invalid instead of reverting.
  58. * data instead.
  59. */
  60. function decodeTypedDataSig(
  61. bytes calldata encodedSignature
  62. )
  63. internal
  64. pure
  65. returns (bytes calldata signature, bytes32 appSeparator, bytes32 contentsHash, string calldata contentsDescr)
  66. {
  67. unchecked {
  68. uint256 sigLength = encodedSignature.length;
  69. // 66 bytes = contentsDescrLength (2 bytes) + contentsHash (32 bytes) + APP_DOMAIN_SEPARATOR (32 bytes).
  70. if (sigLength < 66) return (Calldata.emptyBytes(), 0, 0, Calldata.emptyString());
  71. uint256 contentsDescrEnd = sigLength - 2; // Last 2 bytes
  72. uint256 contentsDescrLength = uint16(bytes2(encodedSignature[contentsDescrEnd:]));
  73. // Check for space for `contentsDescr` in addition to the 66 bytes documented above
  74. if (sigLength < 66 + contentsDescrLength) return (Calldata.emptyBytes(), 0, 0, Calldata.emptyString());
  75. uint256 contentsHashEnd = contentsDescrEnd - contentsDescrLength;
  76. uint256 separatorEnd = contentsHashEnd - 32;
  77. uint256 signatureEnd = separatorEnd - 32;
  78. signature = encodedSignature[:signatureEnd];
  79. appSeparator = bytes32(encodedSignature[signatureEnd:separatorEnd]);
  80. contentsHash = bytes32(encodedSignature[separatorEnd:contentsHashEnd]);
  81. contentsDescr = string(encodedSignature[contentsHashEnd:contentsDescrEnd]);
  82. }
  83. }
  84. /**
  85. * @dev Nests an `ERC-191` digest into a `PersonalSign` EIP-712 struct, and returns the corresponding struct hash.
  86. * This struct hash must be combined with a domain separator, using {MessageHashUtils-toTypedDataHash} before
  87. * being verified/recovered.
  88. *
  89. * This is used to simulates the `personal_sign` RPC method in the context of smart contracts.
  90. */
  91. function personalSignStructHash(bytes32 contents) internal pure returns (bytes32) {
  92. return keccak256(abi.encode(PERSONAL_SIGN_TYPEHASH, contents));
  93. }
  94. /**
  95. * @dev Nests an `EIP-712` hash (`contents`) into a `TypedDataSign` EIP-712 struct, and returns the corresponding
  96. * struct hash. This struct hash must be combined with a domain separator, using {MessageHashUtils-toTypedDataHash}
  97. * before being verified/recovered.
  98. */
  99. function typedDataSignStructHash(
  100. string calldata contentsName,
  101. string calldata contentsType,
  102. bytes32 contentsHash,
  103. bytes memory domainBytes
  104. ) internal pure returns (bytes32 result) {
  105. return
  106. bytes(contentsName).length == 0
  107. ? bytes32(0)
  108. : keccak256(
  109. abi.encodePacked(typedDataSignTypehash(contentsName, contentsType), contentsHash, domainBytes)
  110. );
  111. }
  112. /**
  113. * @dev Variant of {typedDataSignStructHash-string-string-bytes32-bytes} that takes a content descriptor
  114. * and decodes the `contentsName` and `contentsType` out of it.
  115. */
  116. function typedDataSignStructHash(
  117. string calldata contentsDescr,
  118. bytes32 contentsHash,
  119. bytes memory domainBytes
  120. ) internal pure returns (bytes32 result) {
  121. (string calldata contentsName, string calldata contentsType) = decodeContentsDescr(contentsDescr);
  122. return typedDataSignStructHash(contentsName, contentsType, contentsHash, domainBytes);
  123. }
  124. /**
  125. * @dev Compute the EIP-712 typehash of the `TypedDataSign` structure for a given type (and typename).
  126. */
  127. function typedDataSignTypehash(
  128. string calldata contentsName,
  129. string calldata contentsType
  130. ) internal pure returns (bytes32) {
  131. return
  132. keccak256(
  133. abi.encodePacked(
  134. "TypedDataSign(",
  135. contentsName,
  136. " contents,string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)",
  137. contentsType
  138. )
  139. );
  140. }
  141. /**
  142. * @dev Parse the type name out of the ERC-7739 contents type description. Supports both the implicit and explicit
  143. * modes.
  144. *
  145. * Following ERC-7739 specifications, a `contentsName` is considered invalid if it's empty or it contains
  146. * any of the following bytes , )\x00
  147. *
  148. * If the `contentsType` is invalid, this returns an empty string. Otherwise, the return string has non-zero
  149. * length.
  150. */
  151. function decodeContentsDescr(
  152. string calldata contentsDescr
  153. ) internal pure returns (string calldata contentsName, string calldata contentsType) {
  154. bytes calldata buffer = bytes(contentsDescr);
  155. if (buffer.length == 0) {
  156. // pass through (fail)
  157. } else if (buffer[buffer.length - 1] == bytes1(")")) {
  158. // Implicit mode: read contentsName from the beginning, and keep the complete descr
  159. for (uint256 i = 0; i < buffer.length; ++i) {
  160. bytes1 current = buffer[i];
  161. if (current == bytes1("(")) {
  162. // if name is empty - passthrough (fail)
  163. if (i == 0) break;
  164. // we found the end of the contentsName
  165. return (string(buffer[:i]), contentsDescr);
  166. } else if (_isForbiddenChar(current)) {
  167. // we found an invalid character (forbidden) - passthrough (fail)
  168. break;
  169. }
  170. }
  171. } else {
  172. // Explicit mode: read contentsName from the end, and remove it from the descr
  173. for (uint256 i = buffer.length; i > 0; --i) {
  174. bytes1 current = buffer[i - 1];
  175. if (current == bytes1(")")) {
  176. // we found the end of the contentsName
  177. return (string(buffer[i:]), string(buffer[:i]));
  178. } else if (_isForbiddenChar(current)) {
  179. // we found an invalid character (forbidden) - passthrough (fail)
  180. break;
  181. }
  182. }
  183. }
  184. return (Calldata.emptyString(), Calldata.emptyString());
  185. }
  186. function _isForbiddenChar(bytes1 char) private pure returns (bool) {
  187. return char == 0x00 || char == bytes1(" ") || char == bytes1(",") || char == bytes1("(") || char == bytes1(")");
  188. }
  189. }