ECDSA.sol 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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} from "../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. function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
  60. if (signature.length == 65) {
  61. bytes32 r;
  62. bytes32 s;
  63. uint8 v;
  64. // ecrecover takes the signature parameters, and the only way to get them
  65. // currently is to use assembly.
  66. /// @solidity memory-safe-assembly
  67. assembly {
  68. r := mload(add(signature, 0x20))
  69. s := mload(add(signature, 0x40))
  70. v := byte(0, mload(add(signature, 0x60)))
  71. }
  72. return tryRecover(hash, v, r, s);
  73. } else {
  74. return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
  75. }
  76. }
  77. /**
  78. * @dev Returns the address that signed a hashed message (`hash`) with
  79. * `signature`. This address can then be used for verification purposes.
  80. *
  81. * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
  82. * this function rejects them by requiring the `s` value to be in the lower
  83. * half order, and the `v` value to be either 27 or 28.
  84. *
  85. * IMPORTANT: `hash` _must_ be the result of a hash operation for the
  86. * verification to be secure: it is possible to craft signatures that
  87. * recover to arbitrary addresses for non-hashed data. A safe way to ensure
  88. * this is by receiving a hash of the original message (which may otherwise
  89. * be too long), and then calling {toEthSignedMessageHash} on it.
  90. */
  91. function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
  92. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
  93. _throwError(error, errorArg);
  94. return recovered;
  95. }
  96. /**
  97. * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
  98. *
  99. * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
  100. */
  101. function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
  102. unchecked {
  103. bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
  104. // We do not check for an overflow here since the shift operation results in 0 or 1.
  105. uint8 v = uint8((uint256(vs) >> 255) + 27);
  106. return tryRecover(hash, v, r, s);
  107. }
  108. }
  109. /**
  110. * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
  111. */
  112. function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
  113. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
  114. _throwError(error, errorArg);
  115. return recovered;
  116. }
  117. /**
  118. * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
  119. * `r` and `s` signature fields separately.
  120. */
  121. function tryRecover(
  122. bytes32 hash,
  123. uint8 v,
  124. bytes32 r,
  125. bytes32 s
  126. ) internal pure returns (address, RecoverError, bytes32) {
  127. // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
  128. // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
  129. // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
  130. // signatures from current libraries generate a unique signature with an s-value in the lower half order.
  131. //
  132. // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
  133. // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
  134. // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
  135. // these malleable signatures as well.
  136. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
  137. return (address(0), RecoverError.InvalidSignatureS, s);
  138. }
  139. // If the signature is valid (and not malleable), return the signer address
  140. address signer = ecrecover(hash, v, r, s);
  141. if (signer == address(0)) {
  142. return (address(0), RecoverError.InvalidSignature, bytes32(0));
  143. }
  144. return (signer, RecoverError.NoError, bytes32(0));
  145. }
  146. /**
  147. * @dev Overload of {ECDSA-recover} that receives the `v`,
  148. * `r` and `s` signature fields separately.
  149. */
  150. function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
  151. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
  152. _throwError(error, errorArg);
  153. return recovered;
  154. }
  155. /**
  156. * @dev Returns an Ethereum Signed Message, created from a `hash`. This
  157. * produces hash corresponding to the one signed with the
  158. * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
  159. * JSON-RPC method as part of EIP-191.
  160. *
  161. * See {recover}.
  162. */
  163. function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
  164. // 32 is the length in bytes of hash,
  165. // enforced by the type signature above
  166. /// @solidity memory-safe-assembly
  167. assembly {
  168. mstore(0x00, "\x19Ethereum Signed Message:\n32")
  169. mstore(0x1c, hash)
  170. message := keccak256(0x00, 0x3c)
  171. }
  172. }
  173. /**
  174. * @dev Returns an Ethereum Signed Message, created from `s`. This
  175. * produces hash corresponding to the one signed with the
  176. * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
  177. * JSON-RPC method as part of EIP-191.
  178. *
  179. * See {recover}.
  180. */
  181. function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
  182. return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
  183. }
  184. /**
  185. * @dev Returns an Ethereum Signed Typed Data, created from a
  186. * `domainSeparator` and a `structHash`. This produces hash corresponding
  187. * to the one signed with the
  188. * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
  189. * JSON-RPC method as part of EIP-712.
  190. *
  191. * See {recover}.
  192. */
  193. function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
  194. /// @solidity memory-safe-assembly
  195. assembly {
  196. let ptr := mload(0x40)
  197. mstore(ptr, hex"19_01")
  198. mstore(add(ptr, 0x02), domainSeparator)
  199. mstore(add(ptr, 0x22), structHash)
  200. data := keccak256(ptr, 0x42)
  201. }
  202. }
  203. /**
  204. * @dev Returns an Ethereum Signed Data with intended validator, created from a
  205. * `validator` and `data` according to the version 0 of EIP-191.
  206. *
  207. * See {recover}.
  208. */
  209. function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
  210. return keccak256(abi.encodePacked(hex"19_00", validator, data));
  211. }
  212. }