ECDSA.sol 8.5 KB

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