SignatureChecker.sol 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol)
  3. pragma solidity ^0.8.19;
  4. import "./ECDSA.sol";
  5. import "../../interfaces/IERC1271.sol";
  6. /**
  7. * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
  8. * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
  9. * Argent and Gnosis Safe.
  10. *
  11. * _Available since v4.1._
  12. */
  13. library SignatureChecker {
  14. /**
  15. * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
  16. * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
  17. *
  18. * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
  19. * change through time. It could return true at block N and false at block N+1 (or the opposite).
  20. */
  21. function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
  22. (address recovered, ECDSA.RecoverError error, ) = ECDSA.tryRecover(hash, signature);
  23. return
  24. (error == ECDSA.RecoverError.NoError && recovered == signer) ||
  25. isValidERC1271SignatureNow(signer, hash, signature);
  26. }
  27. /**
  28. * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
  29. * against the signer smart contract using ERC1271.
  30. *
  31. * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
  32. * change through time. It could return true at block N and false at block N+1 (or the opposite).
  33. */
  34. function isValidERC1271SignatureNow(
  35. address signer,
  36. bytes32 hash,
  37. bytes memory signature
  38. ) internal view returns (bool) {
  39. (bool success, bytes memory result) = signer.staticcall(
  40. abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
  41. );
  42. return (success &&
  43. result.length >= 32 &&
  44. abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
  45. }
  46. }