ECDSA.sol 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
  3. pragma solidity ^0.8.20;
  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. }
  17. /**
  18. * @dev The signature derives the `address(0)`.
  19. */
  20. error ECDSAInvalidSignature();
  21. /**
  22. * @dev The signature has an invalid length.
  23. */
  24. error ECDSAInvalidSignatureLength(uint256 length);
  25. /**
  26. * @dev The signature has an S value that is in the upper half order.
  27. */
  28. error ECDSAInvalidSignatureS(bytes32 s);
  29. /**
  30. * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
  31. * return address(0) without also returning an error description. Errors are documented using an enum (error type)
  32. * and a bytes32 providing additional information about the error.
  33. *
  34. * If no error is returned, then the address can be used for verification purposes.
  35. *
  36. * The `ecrecover` EVM precompile 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 {MessageHashUtils-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. function tryRecover(
  51. bytes32 hash,
  52. bytes memory signature
  53. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  54. if (signature.length == 65) {
  55. bytes32 r;
  56. bytes32 s;
  57. uint8 v;
  58. // ecrecover takes the signature parameters, and the only way to get them
  59. // currently is to use assembly.
  60. assembly ("memory-safe") {
  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, bytes32(signature.length));
  68. }
  69. }
  70. /**
  71. * @dev Variant of {tryRecover} that takes a signature in calldata
  72. */
  73. function tryRecoverCalldata(
  74. bytes32 hash,
  75. bytes calldata signature
  76. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  77. if (signature.length == 65) {
  78. bytes32 r;
  79. bytes32 s;
  80. uint8 v;
  81. // ecrecover takes the signature parameters, calldata slices would work here, but are
  82. // significantly more expensive (length check) than using calldataload in assembly.
  83. assembly ("memory-safe") {
  84. r := calldataload(signature.offset)
  85. s := calldataload(add(signature.offset, 0x20))
  86. v := byte(0, calldataload(add(signature.offset, 0x40)))
  87. }
  88. return tryRecover(hash, v, r, s);
  89. } else {
  90. return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
  91. }
  92. }
  93. /**
  94. * @dev Returns the address that signed a hashed message (`hash`) with
  95. * `signature`. This address can then be used for verification purposes.
  96. *
  97. * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
  98. * this function rejects them by requiring the `s` value to be in the lower
  99. * half order, and the `v` value to be either 27 or 28.
  100. *
  101. * IMPORTANT: `hash` _must_ be the result of a hash operation for the
  102. * verification to be secure: it is possible to craft signatures that
  103. * recover to arbitrary addresses for non-hashed data. A safe way to ensure
  104. * this is by receiving a hash of the original message (which may otherwise
  105. * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
  106. */
  107. function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
  108. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
  109. _throwError(error, errorArg);
  110. return recovered;
  111. }
  112. /**
  113. * @dev Variant of {recover} that takes a signature in calldata
  114. */
  115. function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
  116. (address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
  117. _throwError(error, errorArg);
  118. return recovered;
  119. }
  120. /**
  121. * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
  122. *
  123. * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
  124. */
  125. function tryRecover(
  126. bytes32 hash,
  127. bytes32 r,
  128. bytes32 vs
  129. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  130. unchecked {
  131. bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
  132. // We do not check for an overflow here since the shift operation results in 0 or 1.
  133. uint8 v = uint8((uint256(vs) >> 255) + 27);
  134. return tryRecover(hash, v, r, s);
  135. }
  136. }
  137. /**
  138. * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
  139. */
  140. function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
  141. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
  142. _throwError(error, errorArg);
  143. return recovered;
  144. }
  145. /**
  146. * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
  147. * `r` and `s` signature fields separately.
  148. */
  149. function tryRecover(
  150. bytes32 hash,
  151. uint8 v,
  152. bytes32 r,
  153. bytes32 s
  154. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  155. // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
  156. // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
  157. // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
  158. // signatures from current libraries generate a unique signature with an s-value in the lower half order.
  159. //
  160. // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
  161. // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
  162. // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
  163. // these malleable signatures as well.
  164. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
  165. return (address(0), RecoverError.InvalidSignatureS, s);
  166. }
  167. // If the signature is valid (and not malleable), return the signer address
  168. address signer = ecrecover(hash, v, r, s);
  169. if (signer == address(0)) {
  170. return (address(0), RecoverError.InvalidSignature, bytes32(0));
  171. }
  172. return (signer, RecoverError.NoError, bytes32(0));
  173. }
  174. /**
  175. * @dev Overload of {ECDSA-recover} that receives the `v`,
  176. * `r` and `s` signature fields separately.
  177. */
  178. function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
  179. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
  180. _throwError(error, errorArg);
  181. return recovered;
  182. }
  183. /**
  184. * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
  185. */
  186. function _throwError(RecoverError error, bytes32 errorArg) private pure {
  187. if (error == RecoverError.NoError) {
  188. return; // no error: do nothing
  189. } else if (error == RecoverError.InvalidSignature) {
  190. revert ECDSAInvalidSignature();
  191. } else if (error == RecoverError.InvalidSignatureLength) {
  192. revert ECDSAInvalidSignatureLength(uint256(errorArg));
  193. } else if (error == RecoverError.InvalidSignatureS) {
  194. revert ECDSAInvalidSignatureS(errorArg);
  195. }
  196. }
  197. }