SignatureChecker.sol 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/SignatureChecker.sol)
  3. pragma solidity ^0.8.20;
  4. import {ECDSA} from "./ECDSA.sol";
  5. import {IERC1271} from "../../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 ERC-1271 signatures from smart contract wallets like
  9. * Argent and Safe Wallet (previously Gnosis Safe).
  10. */
  11. library SignatureChecker {
  12. /**
  13. * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
  14. * signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`.
  15. *
  16. * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
  17. * change through time. It could return true at block N and false at block N+1 (or the opposite).
  18. */
  19. function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
  20. if (signer.code.length == 0) {
  21. (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
  22. return err == ECDSA.RecoverError.NoError && recovered == signer;
  23. } else {
  24. return isValidERC1271SignatureNow(signer, hash, signature);
  25. }
  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 ERC-1271.
  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.encodeCall(IERC1271.isValidSignature, (hash, signature))
  41. );
  42. return (success &&
  43. result.length >= 32 &&
  44. abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
  45. }
  46. }