ECDSA.sol 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
  41. * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
  42. * invalidation or nonces for replay protection.
  43. *
  44. * IMPORTANT: `hash` _must_ be the result of a hash operation for the
  45. * verification to be secure: it is possible to craft signatures that
  46. * recover to arbitrary addresses for non-hashed data. A safe way to ensure
  47. * this is by receiving a hash of the original message (which may otherwise
  48. * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
  49. *
  50. * Documentation for signature generation:
  51. * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
  52. * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
  53. */
  54. function tryRecover(
  55. bytes32 hash,
  56. bytes memory signature
  57. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  58. if (signature.length == 65) {
  59. bytes32 r;
  60. bytes32 s;
  61. uint8 v;
  62. // ecrecover takes the signature parameters, and the only way to get them
  63. // currently is to use assembly.
  64. assembly ("memory-safe") {
  65. r := mload(add(signature, 0x20))
  66. s := mload(add(signature, 0x40))
  67. v := byte(0, mload(add(signature, 0x60)))
  68. }
  69. return tryRecover(hash, v, r, s);
  70. } else {
  71. return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
  72. }
  73. }
  74. /**
  75. * @dev Variant of {tryRecover} that takes a signature in calldata
  76. */
  77. function tryRecoverCalldata(
  78. bytes32 hash,
  79. bytes calldata signature
  80. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  81. if (signature.length == 65) {
  82. bytes32 r;
  83. bytes32 s;
  84. uint8 v;
  85. // ecrecover takes the signature parameters, calldata slices would work here, but are
  86. // significantly more expensive (length check) than using calldataload in assembly.
  87. assembly ("memory-safe") {
  88. r := calldataload(signature.offset)
  89. s := calldataload(add(signature.offset, 0x20))
  90. v := byte(0, calldataload(add(signature.offset, 0x40)))
  91. }
  92. return tryRecover(hash, v, r, s);
  93. } else {
  94. return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
  95. }
  96. }
  97. /**
  98. * @dev Returns the address that signed a hashed message (`hash`) with
  99. * `signature`. This address can then be used for verification purposes.
  100. *
  101. * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
  102. * this function rejects them by requiring the `s` value to be in the lower
  103. * half order, and the `v` value to be either 27 or 28.
  104. *
  105. * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
  106. * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
  107. * invalidation or nonces for replay protection.
  108. *
  109. * IMPORTANT: `hash` _must_ be the result of a hash operation for the
  110. * verification to be secure: it is possible to craft signatures that
  111. * recover to arbitrary addresses for non-hashed data. A safe way to ensure
  112. * this is by receiving a hash of the original message (which may otherwise
  113. * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
  114. */
  115. function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
  116. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
  117. _throwError(error, errorArg);
  118. return recovered;
  119. }
  120. /**
  121. * @dev Variant of {recover} that takes a signature in calldata
  122. */
  123. function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
  124. (address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
  125. _throwError(error, errorArg);
  126. return recovered;
  127. }
  128. /**
  129. * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
  130. *
  131. * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
  132. */
  133. function tryRecover(
  134. bytes32 hash,
  135. bytes32 r,
  136. bytes32 vs
  137. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  138. unchecked {
  139. bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
  140. // We do not check for an overflow here since the shift operation results in 0 or 1.
  141. uint8 v = uint8((uint256(vs) >> 255) + 27);
  142. return tryRecover(hash, v, r, s);
  143. }
  144. }
  145. /**
  146. * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
  147. */
  148. function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
  149. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
  150. _throwError(error, errorArg);
  151. return recovered;
  152. }
  153. /**
  154. * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
  155. * `r` and `s` signature fields separately.
  156. */
  157. function tryRecover(
  158. bytes32 hash,
  159. uint8 v,
  160. bytes32 r,
  161. bytes32 s
  162. ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
  163. // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
  164. // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
  165. // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
  166. // signatures from current libraries generate a unique signature with an s-value in the lower half order.
  167. //
  168. // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
  169. // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
  170. // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
  171. // these malleable signatures as well.
  172. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
  173. return (address(0), RecoverError.InvalidSignatureS, s);
  174. }
  175. // If the signature is valid (and not malleable), return the signer address
  176. address signer = ecrecover(hash, v, r, s);
  177. if (signer == address(0)) {
  178. return (address(0), RecoverError.InvalidSignature, bytes32(0));
  179. }
  180. return (signer, RecoverError.NoError, bytes32(0));
  181. }
  182. /**
  183. * @dev Overload of {ECDSA-recover} that receives the `v`,
  184. * `r` and `s` signature fields separately.
  185. */
  186. function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
  187. (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
  188. _throwError(error, errorArg);
  189. return recovered;
  190. }
  191. /**
  192. * @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
  193. * formats. Returns (0,0,0) for invalid signatures. Consider skipping {tryRecover} or {recover} if so.
  194. */
  195. function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
  196. assembly ("memory-safe") {
  197. // Check the signature length
  198. switch mload(signature)
  199. // - case 65: r,s,v signature (standard)
  200. case 65 {
  201. r := mload(add(signature, 0x20))
  202. s := mload(add(signature, 0x40))
  203. v := byte(0, mload(add(signature, 0x60)))
  204. }
  205. // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
  206. case 64 {
  207. let vs := mload(add(signature, 0x40))
  208. r := mload(add(signature, 0x20))
  209. s := and(vs, shr(1, not(0)))
  210. v := add(shr(255, vs), 27)
  211. }
  212. default {
  213. r := 0
  214. s := 0
  215. v := 0
  216. }
  217. }
  218. }
  219. /**
  220. * @dev Variant of {parse} that takes a signature in calldata
  221. */
  222. function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
  223. assembly ("memory-safe") {
  224. // Check the signature length
  225. switch signature.length
  226. // - case 65: r,s,v signature (standard)
  227. case 65 {
  228. r := calldataload(signature.offset)
  229. s := calldataload(add(signature.offset, 0x20))
  230. v := byte(0, calldataload(add(signature.offset, 0x40)))
  231. }
  232. // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
  233. case 64 {
  234. let vs := calldataload(add(signature.offset, 0x20))
  235. r := calldataload(signature.offset)
  236. s := and(vs, shr(1, not(0)))
  237. v := add(shr(255, vs), 27)
  238. }
  239. default {
  240. r := 0
  241. s := 0
  242. v := 0
  243. }
  244. }
  245. }
  246. /**
  247. * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
  248. */
  249. function _throwError(RecoverError error, bytes32 errorArg) private pure {
  250. if (error == RecoverError.NoError) {
  251. return; // no error: do nothing
  252. } else if (error == RecoverError.InvalidSignature) {
  253. revert ECDSAInvalidSignature();
  254. } else if (error == RecoverError.InvalidSignatureLength) {
  255. revert ECDSAInvalidSignatureLength(uint256(errorArg));
  256. } else if (error == RecoverError.InvalidSignatureS) {
  257. revert ECDSAInvalidSignatureS(errorArg);
  258. }
  259. }
  260. }