ECDSA.sol 9.0 KB

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