ECDSA.sol 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 opcode 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 opcode 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. bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
  95. uint8 v = uint8((uint256(vs) >> 255) + 27);
  96. return tryRecover(hash, v, r, s);
  97. }
  98. /**
  99. * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
  100. *
  101. * _Available since v4.2._
  102. */
  103. function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
  104. (address recovered, RecoverError error) = tryRecover(hash, r, vs);
  105. _throwError(error);
  106. return recovered;
  107. }
  108. /**
  109. * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
  110. * `r` and `s` signature fields separately.
  111. *
  112. * _Available since v4.3._
  113. */
  114. function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
  115. // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
  116. // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
  117. // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
  118. // signatures from current libraries generate a unique signature with an s-value in the lower half order.
  119. //
  120. // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
  121. // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
  122. // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
  123. // these malleable signatures as well.
  124. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
  125. return (address(0), RecoverError.InvalidSignatureS);
  126. }
  127. // If the signature is valid (and not malleable), return the signer address
  128. address signer = ecrecover(hash, v, r, s);
  129. if (signer == address(0)) {
  130. return (address(0), RecoverError.InvalidSignature);
  131. }
  132. return (signer, RecoverError.NoError);
  133. }
  134. /**
  135. * @dev Overload of {ECDSA-recover} that receives the `v`,
  136. * `r` and `s` signature fields separately.
  137. */
  138. function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
  139. (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
  140. _throwError(error);
  141. return recovered;
  142. }
  143. /**
  144. * @dev Returns an Ethereum Signed Message, created from a `hash`. This
  145. * produces hash corresponding to the one signed with the
  146. * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
  147. * JSON-RPC method as part of EIP-191.
  148. *
  149. * See {recover}.
  150. */
  151. function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
  152. // 32 is the length in bytes of hash,
  153. // enforced by the type signature above
  154. /// @solidity memory-safe-assembly
  155. assembly {
  156. mstore(0x00, "\x19Ethereum Signed Message:\n32")
  157. mstore(0x1c, hash)
  158. message := keccak256(0x00, 0x3c)
  159. }
  160. }
  161. /**
  162. * @dev Returns an Ethereum Signed Message, created from `s`. This
  163. * produces hash corresponding to the one signed with the
  164. * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
  165. * JSON-RPC method as part of EIP-191.
  166. *
  167. * See {recover}.
  168. */
  169. function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
  170. return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
  171. }
  172. /**
  173. * @dev Returns an Ethereum Signed Typed Data, created from a
  174. * `domainSeparator` and a `structHash`. This produces hash corresponding
  175. * to the one signed with the
  176. * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
  177. * JSON-RPC method as part of EIP-712.
  178. *
  179. * See {recover}.
  180. */
  181. function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
  182. /// @solidity memory-safe-assembly
  183. assembly {
  184. let ptr := mload(0x40)
  185. mstore(ptr, hex"19_01")
  186. mstore(add(ptr, 0x02), domainSeparator)
  187. mstore(add(ptr, 0x22), structHash)
  188. data := keccak256(ptr, 0x42)
  189. }
  190. }
  191. /**
  192. * @dev Returns an Ethereum Signed Data with intended validator, created from a
  193. * `validator` and `data` according to the version 0 of EIP-191.
  194. *
  195. * See {recover}.
  196. */
  197. function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
  198. return keccak256(abi.encodePacked(hex"19_00", validator, data));
  199. }
  200. }