ECDSA.sol 9.0 KB

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