draft-ERC7739Utils.sol 9.2 KB

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