ECDSA.sol 9.4 KB

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