ECDSA.sol 8.5 KB

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