ECDSA.sol 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
  3. pragma solidity ^0.8.19;
  4. import "../Strings.sol";
  5. /**
  6. * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
  7. *
  8. * These functions can be used to verify that a message was signed by the holder
  9. * of the private keys of a given address.
  10. */
  11. library ECDSA {
  12. enum RecoverError {
  13. NoError,
  14. InvalidSignature,
  15. InvalidSignatureLength,
  16. InvalidSignatureS
  17. }
  18. /**
  19. * @dev The signature derives the `address(0)`.
  20. */
  21. error ECDSAInvalidSignature();
  22. /**
  23. * @dev The signature has an invalid length.
  24. */
  25. error ECDSAInvalidSignatureLength(uint256 length);
  26. /**
  27. * @dev The signature has an S value that is in the upper half order.
  28. */
  29. error ECDSAInvalidSignatureS(bytes32 s);
  30. function _throwError(RecoverError error, bytes32 errorArg) private pure {
  31. if (error == RecoverError.NoError) {
  32. return; // no error: do nothing
  33. } else if (error == RecoverError.InvalidSignature) {
  34. revert ECDSAInvalidSignature();
  35. } else if (error == RecoverError.InvalidSignatureLength) {
  36. revert ECDSAInvalidSignatureLength(uint256(errorArg));
  37. } else if (error == RecoverError.InvalidSignatureS) {
  38. revert ECDSAInvalidSignatureS(errorArg);
  39. }
  40. }
  41. /**
  42. * @dev Returns the address that signed a hashed message (`hash`) with
  43. * `signature` or error string. This address can then be used for verification purposes.
  44. *
  45. * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
  46. * this function rejects them by requiring the `s` value to be in the lower
  47. * half order, and the `v` value to be either 27 or 28.
  48. *
  49. * IMPORTANT: `hash` _must_ be the result of a hash operation for the
  50. * verification to be secure: it is possible to craft signatures that
  51. * recover to arbitrary addresses for non-hashed data. A safe way to ensure
  52. * this is by receiving a hash of the original message (which may otherwise
  53. * be too long), and then calling {toEthSignedMessageHash} on it.
  54. *
  55. * Documentation for signature generation:
  56. * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
  57. * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
  58. *
  59. * _Available since v4.3._
  60. */
  61. function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
  62. if (signature.length == 65) {
  63. bytes32 r;
  64. bytes32 s;
  65. uint8 v;
  66. // ecrecover takes the signature parameters, and the only way to get them
  67. // currently is to use assembly.
  68. /// @solidity memory-safe-assembly
  69. assembly {
  70. r := mload(add(signature, 0x20))
  71. s := mload(add(signature, 0x40))
  72. v := byte(0, mload(add(signature, 0x60)))
  73. }
  74. return tryRecover(hash, v, r, s);
  75. } else {
  76. return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
  77. }
  78. }
  79. /**
  80. * @dev Returns the address that signed a hashed message (`hash`) with
  81. * `signature`. This address can then be used for verification purposes.
  82. *
  83. * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
  84. * this function rejects them by requiring the `s` value to be in the lower
  85. * half order, and the `v` value to be either 27 or 28.
  86. *
  87. * IMPORTANT: `hash` _must_ be the result of a hash operation for the
  88. * verification to be secure: it is possible to craft signatures that
  89. * recover to arbitrary addresses for non-hashed data. A safe way to ensure
  90. * this is by receiving a hash of the original message (which may otherwise
  91. * be too long), and then calling {toEthSignedMessageHash} on it.
  92. */
  93. function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
  94. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
  95. _throwError(error, errorArg);
  96. return recovered;
  97. }
  98. /**
  99. * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
  100. *
  101. * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
  102. *
  103. * _Available since v4.3._
  104. */
  105. function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
  106. unchecked {
  107. bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
  108. // We do not check for an overflow here since the shift operation results in 0 or 1.
  109. uint8 v = uint8((uint256(vs) >> 255) + 27);
  110. return tryRecover(hash, v, r, s);
  111. }
  112. }
  113. /**
  114. * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
  115. *
  116. * _Available since v4.2._
  117. */
  118. function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
  119. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
  120. _throwError(error, errorArg);
  121. return recovered;
  122. }
  123. /**
  124. * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
  125. * `r` and `s` signature fields separately.
  126. *
  127. * _Available since v4.3._
  128. */
  129. function tryRecover(
  130. bytes32 hash,
  131. uint8 v,
  132. bytes32 r,
  133. bytes32 s
  134. ) internal pure returns (address, RecoverError, bytes32) {
  135. // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
  136. // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
  137. // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
  138. // signatures from current libraries generate a unique signature with an s-value in the lower half order.
  139. //
  140. // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
  141. // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
  142. // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
  143. // these malleable signatures as well.
  144. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
  145. return (address(0), RecoverError.InvalidSignatureS, s);
  146. }
  147. // If the signature is valid (and not malleable), return the signer address
  148. address signer = ecrecover(hash, v, r, s);
  149. if (signer == address(0)) {
  150. return (address(0), RecoverError.InvalidSignature, bytes32(0));
  151. }
  152. return (signer, RecoverError.NoError, bytes32(0));
  153. }
  154. /**
  155. * @dev Overload of {ECDSA-recover} that receives the `v`,
  156. * `r` and `s` signature fields separately.
  157. */
  158. function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
  159. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
  160. _throwError(error, errorArg);
  161. return recovered;
  162. }
  163. /**
  164. * @dev Returns an Ethereum Signed Message, created from a `hash`. This
  165. * produces hash corresponding to the one signed with the
  166. * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
  167. * JSON-RPC method as part of EIP-191.
  168. *
  169. * See {recover}.
  170. */
  171. function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
  172. // 32 is the length in bytes of hash,
  173. // enforced by the type signature above
  174. /// @solidity memory-safe-assembly
  175. assembly {
  176. mstore(0x00, "\x19Ethereum Signed Message:\n32")
  177. mstore(0x1c, hash)
  178. message := keccak256(0x00, 0x3c)
  179. }
  180. }
  181. /**
  182. * @dev Returns an Ethereum Signed Message, created from `s`. This
  183. * produces hash corresponding to the one signed with the
  184. * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
  185. * JSON-RPC method as part of EIP-191.
  186. *
  187. * See {recover}.
  188. */
  189. function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
  190. return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
  191. }
  192. /**
  193. * @dev Returns an Ethereum Signed Typed Data, created from a
  194. * `domainSeparator` and a `structHash`. This produces hash corresponding
  195. * to the one signed with the
  196. * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
  197. * JSON-RPC method as part of EIP-712.
  198. *
  199. * See {recover}.
  200. */
  201. function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
  202. /// @solidity memory-safe-assembly
  203. assembly {
  204. let ptr := mload(0x40)
  205. mstore(ptr, hex"19_01")
  206. mstore(add(ptr, 0x02), domainSeparator)
  207. mstore(add(ptr, 0x22), structHash)
  208. data := keccak256(ptr, 0x42)
  209. }
  210. }
  211. /**
  212. * @dev Returns an Ethereum Signed Data with intended validator, created from a
  213. * `validator` and `data` according to the version 0 of EIP-191.
  214. *
  215. * See {recover}.
  216. */
  217. function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
  218. return keccak256(abi.encodePacked(hex"19_00", validator, data));
  219. }
  220. }