ECDSA.sol 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.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
  31. * `signature` or error string. This address can then be used for verification purposes.
  32. *
  33. * The `ecrecover` EVM precompile 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 {MessageHashUtils-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. function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
  48. if (signature.length == 65) {
  49. bytes32 r;
  50. bytes32 s;
  51. uint8 v;
  52. // ecrecover takes the signature parameters, and the only way to get them
  53. // currently is to use assembly.
  54. /// @solidity memory-safe-assembly
  55. assembly {
  56. r := mload(add(signature, 0x20))
  57. s := mload(add(signature, 0x40))
  58. v := byte(0, mload(add(signature, 0x60)))
  59. }
  60. return tryRecover(hash, v, r, s);
  61. } else {
  62. return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
  63. }
  64. }
  65. /**
  66. * @dev Returns the address that signed a hashed message (`hash`) with
  67. * `signature`. This address can then be used for verification purposes.
  68. *
  69. * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
  70. * this function rejects them by requiring the `s` value to be in the lower
  71. * half order, and the `v` value to be either 27 or 28.
  72. *
  73. * IMPORTANT: `hash` _must_ be the result of a hash operation for the
  74. * verification to be secure: it is possible to craft signatures that
  75. * recover to arbitrary addresses for non-hashed data. A safe way to ensure
  76. * this is by receiving a hash of the original message (which may otherwise
  77. * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
  78. */
  79. function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
  80. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
  81. _throwError(error, errorArg);
  82. return recovered;
  83. }
  84. /**
  85. * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
  86. *
  87. * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
  88. */
  89. function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
  90. unchecked {
  91. bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
  92. // We do not check for an overflow here since the shift operation results in 0 or 1.
  93. uint8 v = uint8((uint256(vs) >> 255) + 27);
  94. return tryRecover(hash, v, r, s);
  95. }
  96. }
  97. /**
  98. * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
  99. */
  100. function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
  101. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
  102. _throwError(error, errorArg);
  103. return recovered;
  104. }
  105. /**
  106. * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
  107. * `r` and `s` signature fields separately.
  108. */
  109. function tryRecover(
  110. bytes32 hash,
  111. uint8 v,
  112. bytes32 r,
  113. bytes32 s
  114. ) internal pure returns (address, RecoverError, bytes32) {
  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, s);
  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, bytes32(0));
  131. }
  132. return (signer, RecoverError.NoError, bytes32(0));
  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, bytes32 errorArg) = tryRecover(hash, v, r, s);
  140. _throwError(error, errorArg);
  141. return recovered;
  142. }
  143. /**
  144. * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
  145. */
  146. function _throwError(RecoverError error, bytes32 errorArg) private pure {
  147. if (error == RecoverError.NoError) {
  148. return; // no error: do nothing
  149. } else if (error == RecoverError.InvalidSignature) {
  150. revert ECDSAInvalidSignature();
  151. } else if (error == RecoverError.InvalidSignatureLength) {
  152. revert ECDSAInvalidSignatureLength(uint256(errorArg));
  153. } else if (error == RecoverError.InvalidSignatureS) {
  154. revert ECDSAInvalidSignatureS(errorArg);
  155. }
  156. }
  157. }